loopback.rs 5.7 KB

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