loopback.rs 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  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::{InterfaceBuilder, NeighborCache, 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. let mut neighbor_cache_entries = [None; 8];
  68. let mut neighbor_cache = NeighborCache::new(&mut neighbor_cache_entries[..]);
  69. let mut ip_addrs = [IpCidr::new(IpAddress::v4(127, 0, 0, 1), 8)];
  70. let mut iface = InterfaceBuilder::new()
  71. .hardware_addr(EthernetAddress::default().into())
  72. .neighbor_cache(neighbor_cache)
  73. .ip_addrs(ip_addrs)
  74. .finalize(&mut device);
  75. let server_socket = {
  76. // It is not strictly necessary to use a `static mut` and unsafe code here, but
  77. // on embedded systems that smoltcp targets it is far better to allocate the data
  78. // statically to verify that it fits into RAM rather than get undefined behavior
  79. // when stack overflows.
  80. static mut TCP_SERVER_RX_DATA: [u8; 1024] = [0; 1024];
  81. static mut TCP_SERVER_TX_DATA: [u8; 1024] = [0; 1024];
  82. let tcp_rx_buffer = tcp::SocketBuffer::new(unsafe { &mut TCP_SERVER_RX_DATA[..] });
  83. let tcp_tx_buffer = tcp::SocketBuffer::new(unsafe { &mut TCP_SERVER_TX_DATA[..] });
  84. tcp::Socket::new(tcp_rx_buffer, tcp_tx_buffer)
  85. };
  86. let client_socket = {
  87. static mut TCP_CLIENT_RX_DATA: [u8; 1024] = [0; 1024];
  88. static mut TCP_CLIENT_TX_DATA: [u8; 1024] = [0; 1024];
  89. let tcp_rx_buffer = tcp::SocketBuffer::new(unsafe { &mut TCP_CLIENT_RX_DATA[..] });
  90. let tcp_tx_buffer = tcp::SocketBuffer::new(unsafe { &mut TCP_CLIENT_TX_DATA[..] });
  91. tcp::Socket::new(tcp_rx_buffer, tcp_tx_buffer)
  92. };
  93. let mut sockets: [_; 2] = Default::default();
  94. let mut sockets = SocketSet::new(&mut sockets[..]);
  95. let server_handle = sockets.add(server_socket);
  96. let client_handle = sockets.add(client_socket);
  97. let mut did_listen = false;
  98. let mut did_connect = false;
  99. let mut done = false;
  100. while !done && clock.elapsed() < Instant::from_millis(10_000) {
  101. match iface.poll(clock.elapsed(), &mut device, &mut sockets) {
  102. Ok(_) => {}
  103. Err(e) => {
  104. debug!("poll error: {}", e);
  105. }
  106. }
  107. let mut socket = sockets.get_mut::<tcp::Socket>(server_handle);
  108. if !socket.is_active() && !socket.is_listening() {
  109. if !did_listen {
  110. debug!("listening");
  111. socket.listen(1234).unwrap();
  112. did_listen = true;
  113. }
  114. }
  115. if socket.can_recv() {
  116. debug!(
  117. "got {:?}",
  118. socket.recv(|buffer| { (buffer.len(), str::from_utf8(buffer).unwrap()) })
  119. );
  120. socket.close();
  121. done = true;
  122. }
  123. let mut socket = sockets.get_mut::<tcp::Socket>(client_handle);
  124. let cx = &mut iface;
  125. if !socket.is_open() {
  126. if !did_connect {
  127. debug!("connecting");
  128. socket
  129. .connect(cx, (IpAddress::v4(127, 0, 0, 1), 1234), 65000)
  130. .unwrap();
  131. did_connect = true;
  132. }
  133. }
  134. if socket.can_send() {
  135. debug!("sending");
  136. socket.send_slice(b"0123456789abcdef").unwrap();
  137. socket.close();
  138. }
  139. match iface.poll_delay(clock.elapsed(), &sockets) {
  140. Some(Duration::ZERO) => debug!("resuming"),
  141. Some(delay) => {
  142. debug!("sleeping for {} ms", delay);
  143. clock.advance(delay)
  144. }
  145. None => clock.advance(Duration::from_millis(1)),
  146. }
  147. }
  148. if done {
  149. info!("done")
  150. } else {
  151. error!("this is taking too long, bailing out")
  152. }
  153. }