loopback.rs 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. #![cfg_attr(not(feature = "std"), no_std)]
  2. #![allow(unused_mut)]
  3. #![allow(clippy::collapsible_if)]
  4. #[cfg(feature = "std")]
  5. #[allow(dead_code)]
  6. mod utils;
  7. use core::str;
  8. use log::{debug, error, info};
  9. use smoltcp::iface::{Config, Interface, SocketSet};
  10. use smoltcp::phy::{Loopback, Medium};
  11. use smoltcp::socket::tcp;
  12. use smoltcp::time::{Duration, Instant};
  13. use smoltcp::wire::{EthernetAddress, IpAddress, IpCidr};
  14. #[cfg(not(feature = "std"))]
  15. mod mock {
  16. use core::cell::Cell;
  17. use smoltcp::time::{Duration, Instant};
  18. #[derive(Debug)]
  19. #[cfg_attr(feature = "defmt", derive(defmt::Format))]
  20. pub struct Clock(Cell<Instant>);
  21. impl Clock {
  22. pub fn new() -> Clock {
  23. Clock(Cell::new(Instant::from_millis(0)))
  24. }
  25. pub fn advance(&self, duration: Duration) {
  26. self.0.set(self.0.get() + duration)
  27. }
  28. pub fn elapsed(&self) -> Instant {
  29. self.0.get()
  30. }
  31. }
  32. }
  33. #[cfg(feature = "std")]
  34. mod mock {
  35. use smoltcp::time::{Duration, Instant};
  36. use std::sync::atomic::{AtomicUsize, Ordering};
  37. use std::sync::Arc;
  38. // should be AtomicU64 but that's unstable
  39. #[derive(Debug, Clone)]
  40. #[cfg_attr(feature = "defmt", derive(defmt::Format))]
  41. pub struct Clock(Arc<AtomicUsize>);
  42. impl Clock {
  43. pub fn new() -> Clock {
  44. Clock(Arc::new(AtomicUsize::new(0)))
  45. }
  46. pub fn advance(&self, duration: Duration) {
  47. self.0
  48. .fetch_add(duration.total_millis() as usize, Ordering::SeqCst);
  49. }
  50. pub fn elapsed(&self) -> Instant {
  51. Instant::from_millis(self.0.load(Ordering::SeqCst) as i64)
  52. }
  53. }
  54. }
  55. fn main() {
  56. let clock = mock::Clock::new();
  57. let device = Loopback::new(Medium::Ethernet);
  58. #[cfg(feature = "std")]
  59. let mut device = {
  60. let clock = clock.clone();
  61. utils::setup_logging_with_clock("", move || clock.elapsed());
  62. let (mut opts, mut free) = utils::create_options();
  63. utils::add_middleware_options(&mut opts, &mut free);
  64. let mut matches = utils::parse_options(&opts, free);
  65. utils::parse_middleware_options(&mut matches, device, /*loopback=*/ true)
  66. };
  67. // Create interface
  68. let mut config = Config::new();
  69. config.hardware_addr = Some(EthernetAddress([0x02, 0x00, 0x00, 0x00, 0x00, 0x01]).into());
  70. let mut iface = Interface::new(config, &mut device);
  71. iface.update_ip_addrs(|ip_addrs| {
  72. ip_addrs
  73. .push(IpCidr::new(IpAddress::v4(127, 0, 0, 1), 8))
  74. .unwrap();
  75. });
  76. // Create sockets
  77. let server_socket = {
  78. // It is not strictly necessary to use a `static mut` and unsafe code here, but
  79. // on embedded systems that smoltcp targets it is far better to allocate the data
  80. // statically to verify that it fits into RAM rather than get undefined behavior
  81. // when stack overflows.
  82. static mut TCP_SERVER_RX_DATA: [u8; 1024] = [0; 1024];
  83. static mut TCP_SERVER_TX_DATA: [u8; 1024] = [0; 1024];
  84. let tcp_rx_buffer = tcp::SocketBuffer::new(unsafe { &mut TCP_SERVER_RX_DATA[..] });
  85. let tcp_tx_buffer = tcp::SocketBuffer::new(unsafe { &mut TCP_SERVER_TX_DATA[..] });
  86. tcp::Socket::new(tcp_rx_buffer, tcp_tx_buffer)
  87. };
  88. let client_socket = {
  89. static mut TCP_CLIENT_RX_DATA: [u8; 1024] = [0; 1024];
  90. static mut TCP_CLIENT_TX_DATA: [u8; 1024] = [0; 1024];
  91. let tcp_rx_buffer = tcp::SocketBuffer::new(unsafe { &mut TCP_CLIENT_RX_DATA[..] });
  92. let tcp_tx_buffer = tcp::SocketBuffer::new(unsafe { &mut TCP_CLIENT_TX_DATA[..] });
  93. tcp::Socket::new(tcp_rx_buffer, tcp_tx_buffer)
  94. };
  95. let mut sockets: [_; 2] = Default::default();
  96. let mut sockets = SocketSet::new(&mut sockets[..]);
  97. let server_handle = sockets.add(server_socket);
  98. let client_handle = sockets.add(client_socket);
  99. let mut did_listen = false;
  100. let mut did_connect = false;
  101. let mut done = false;
  102. while !done && clock.elapsed() < Instant::from_millis(10_000) {
  103. iface.poll(clock.elapsed(), &mut device, &mut sockets);
  104. let mut socket = sockets.get_mut::<tcp::Socket>(server_handle);
  105. if !socket.is_active() && !socket.is_listening() {
  106. if !did_listen {
  107. debug!("listening");
  108. socket.listen(1234).unwrap();
  109. did_listen = true;
  110. }
  111. }
  112. if socket.can_recv() {
  113. debug!(
  114. "got {:?}",
  115. socket.recv(|buffer| { (buffer.len(), str::from_utf8(buffer).unwrap()) })
  116. );
  117. socket.close();
  118. done = true;
  119. }
  120. let mut socket = sockets.get_mut::<tcp::Socket>(client_handle);
  121. let cx = iface.context();
  122. if !socket.is_open() {
  123. if !did_connect {
  124. debug!("connecting");
  125. socket
  126. .connect(cx, (IpAddress::v4(127, 0, 0, 1), 1234), 65000)
  127. .unwrap();
  128. did_connect = true;
  129. }
  130. }
  131. if socket.can_send() {
  132. debug!("sending");
  133. socket.send_slice(b"0123456789abcdef").unwrap();
  134. socket.close();
  135. }
  136. match iface.poll_delay(clock.elapsed(), &sockets) {
  137. Some(Duration::ZERO) => debug!("resuming"),
  138. Some(delay) => {
  139. debug!("sleeping for {} ms", delay);
  140. clock.advance(delay)
  141. }
  142. None => clock.advance(Duration::from_millis(1)),
  143. }
  144. }
  145. if done {
  146. info!("done")
  147. } else {
  148. error!("this is taking too long, bailing out")
  149. }
  150. }