loopback.rs 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  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};
  10. use smoltcp::phy::{Loopback, Medium};
  11. use smoltcp::socket::{SocketSet, TcpSocket, TcpSocketBuffer};
  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 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(device)
  71. .ethernet_addr(EthernetAddress::default())
  72. .neighbor_cache(neighbor_cache)
  73. .ip_addrs(ip_addrs)
  74. .finalize();
  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 = TcpSocketBuffer::new(unsafe { &mut TCP_SERVER_RX_DATA[..] });
  83. let tcp_tx_buffer = TcpSocketBuffer::new(unsafe { &mut TCP_SERVER_TX_DATA[..] });
  84. TcpSocket::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 = TcpSocketBuffer::new(unsafe { &mut TCP_CLIENT_RX_DATA[..] });
  90. let tcp_tx_buffer = TcpSocketBuffer::new(unsafe { &mut TCP_CLIENT_TX_DATA[..] });
  91. TcpSocket::new(tcp_rx_buffer, tcp_tx_buffer)
  92. };
  93. let mut socket_set_entries: [_; 2] = Default::default();
  94. let mut socket_set = SocketSet::new(&mut socket_set_entries[..]);
  95. let server_handle = socket_set.add(server_socket);
  96. let client_handle = socket_set.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(&mut socket_set, clock.elapsed()) {
  102. Ok(_) => {}
  103. Err(e) => {
  104. debug!("poll error: {}", e);
  105. }
  106. }
  107. {
  108. let mut socket = socket_set.get::<TcpSocket>(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. }
  125. {
  126. let mut socket = socket_set.get::<TcpSocket>(client_handle);
  127. if !socket.is_open() {
  128. if !did_connect {
  129. debug!("connecting");
  130. socket
  131. .connect(
  132. (IpAddress::v4(127, 0, 0, 1), 1234),
  133. (IpAddress::Unspecified, 65000),
  134. )
  135. .unwrap();
  136. did_connect = true;
  137. }
  138. }
  139. if socket.can_send() {
  140. debug!("sending");
  141. socket.send_slice(b"0123456789abcdef").unwrap();
  142. socket.close();
  143. }
  144. }
  145. match iface.poll_delay(&socket_set, clock.elapsed()) {
  146. Some(Duration { millis: 0 }) => debug!("resuming"),
  147. Some(delay) => {
  148. debug!("sleeping for {} ms", delay);
  149. clock.advance(delay)
  150. }
  151. None => clock.advance(Duration::from_millis(1)),
  152. }
  153. }
  154. if done {
  155. info!("done")
  156. } else {
  157. error!("this is taking too long, bailing out")
  158. }
  159. }