sixlowpan.rs 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. //! 6lowpan exmaple
  2. //!
  3. //! This example is designed to run using the Linux ieee802154/6lowpan support,
  4. //! using mac802154_hwsim.
  5. //!
  6. //! mac802154_hwsim allows you to create multiple "virtual" radios and specify
  7. //! which is in range with which. This is very useful for testing without
  8. //! needing real hardware. By default it creates two interfaces `wpan0` and
  9. //! `wpan1` that are in range with each other. You can customize this with
  10. //! the `wpan-hwsim` tool.
  11. //!
  12. //! We'll configure Linux to speak 6lowpan on `wpan0`, and leave `wpan1`
  13. //! unconfigured so smoltcp can use it with a raw socket.
  14. //!
  15. //! # Setup
  16. //!
  17. //! modprobe mac802154_hwsim
  18. //!
  19. //! ip link set wpan0 down
  20. //! ip link set wpan1 down
  21. //! iwpan dev wpan0 set pan_id 0xbeef
  22. //! iwpan dev wpan1 set pan_id 0xbeef
  23. //! ip link add link wpan0 name lowpan0 type lowpan
  24. //! ip link set wpan0 up
  25. //! ip link set wpan1 up
  26. //! ip link set lowpan0 up
  27. //!
  28. //! # Running
  29. //!
  30. //! Run it with `sudo ./target/debug/examples/sixlowpan`.
  31. //!
  32. //! You can set wireshark to sniff on interface `wpan0` to see the packets.
  33. //!
  34. //! Ping it with `ping fe80::180b:4242:4242:4242%lowpan0`.
  35. //!
  36. //! Speak UDP with `nc -uv fe80::180b:4242:4242:4242%lowpan0 6969`.
  37. //!
  38. //! # Teardown
  39. //!
  40. //! rmmod mac802154_hwsim
  41. //!
  42. mod utils;
  43. use log::debug;
  44. use std::collections::BTreeMap;
  45. use std::os::unix::io::AsRawFd;
  46. use std::str;
  47. use smoltcp::iface::{FragmentsCache, InterfaceBuilder, NeighborCache};
  48. use smoltcp::phy::{wait as phy_wait, Medium, RawSocket};
  49. use smoltcp::socket::udp;
  50. use smoltcp::time::Instant;
  51. use smoltcp::wire::{Ieee802154Pan, IpAddress, IpCidr};
  52. use smoltcp::socket::tcp;
  53. use smoltcp::storage::RingBuffer;
  54. fn main() {
  55. utils::setup_logging("");
  56. let (mut opts, mut free) = utils::create_options();
  57. utils::add_middleware_options(&mut opts, &mut free);
  58. let mut matches = utils::parse_options(&opts, free);
  59. let device = RawSocket::new("wpan1", Medium::Ieee802154).unwrap();
  60. let fd = device.as_raw_fd();
  61. let device = utils::parse_middleware_options(&mut matches, device, /*loopback=*/ false);
  62. let neighbor_cache = NeighborCache::new(BTreeMap::new());
  63. let udp_rx_buffer = udp::PacketBuffer::new(vec![udp::PacketMetadata::EMPTY], vec![0; 64]);
  64. let udp_tx_buffer = udp::PacketBuffer::new(vec![udp::PacketMetadata::EMPTY], vec![0; 128]);
  65. let udp_socket = udp::Socket::new(udp_rx_buffer, udp_tx_buffer);
  66. let tcp_rx_buffer = tcp::SocketBuffer::new(vec![0; 4096]);
  67. let tcp_tx_buffer = tcp::SocketBuffer::new(vec![0; 4096]);
  68. let tcp_socket = tcp::Socket::new(tcp_rx_buffer, tcp_tx_buffer);
  69. let ieee802154_addr = smoltcp::wire::Ieee802154Address::Extended([
  70. 0x1a, 0x0b, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42,
  71. ]);
  72. let ip_addrs = [IpCidr::new(
  73. IpAddress::v6(0xfe80, 0, 0, 0, 0x180b, 0x4242, 0x4242, 0x4242),
  74. 64,
  75. )];
  76. let cache = FragmentsCache::new(vec![], BTreeMap::new());
  77. let buffer: Vec<(usize, managed::ManagedSlice<'_, u8>)> = (0..12)
  78. .into_iter()
  79. .map(|_| (0_usize, managed::ManagedSlice::from(vec![0; 127])))
  80. .collect();
  81. let out_fragments_cache = RingBuffer::new(buffer);
  82. let mut builder = InterfaceBuilder::new(device, vec![])
  83. .ip_addrs(ip_addrs)
  84. .pan_id(Ieee802154Pan(0xbeef));
  85. builder = builder
  86. .hardware_addr(ieee802154_addr.into())
  87. .neighbor_cache(neighbor_cache)
  88. .sixlowpan_fragments_cache(cache)
  89. .out_fragments_cache(out_fragments_cache);
  90. let mut iface = builder.finalize();
  91. let udp_handle = iface.add_socket(udp_socket);
  92. let tcp_handle = iface.add_socket(tcp_socket);
  93. let socket = iface.get_socket::<tcp::Socket>(tcp_handle);
  94. socket.listen(50000).unwrap();
  95. let mut tcp_active = false;
  96. loop {
  97. let timestamp = Instant::now();
  98. let mut poll = true;
  99. while poll {
  100. match iface.poll(timestamp) {
  101. Ok(r) => poll = r,
  102. Err(e) => {
  103. debug!("poll error: {}", e);
  104. break;
  105. }
  106. }
  107. }
  108. // udp:6969: respond "hello"
  109. let socket = iface.get_socket::<udp::Socket>(udp_handle);
  110. if !socket.is_open() {
  111. socket.bind(6969).unwrap()
  112. }
  113. let mut buffer = vec![0; 1500];
  114. let client = match socket.recv() {
  115. Ok((data, endpoint)) => {
  116. debug!(
  117. "udp:6969 recv data: {:?} from {}",
  118. str::from_utf8(data).unwrap(),
  119. endpoint
  120. );
  121. buffer[..data.len()].copy_from_slice(data);
  122. Some((data.len(), endpoint))
  123. }
  124. Err(_) => None,
  125. };
  126. if let Some((len, endpoint)) = client {
  127. debug!(
  128. "udp:6969 send data: {:?}",
  129. str::from_utf8(&buffer[..len]).unwrap()
  130. );
  131. socket.send_slice(&buffer[..len], endpoint).unwrap();
  132. }
  133. let socket = iface.get_socket::<tcp::Socket>(tcp_handle);
  134. if socket.is_active() && !tcp_active {
  135. debug!("connected");
  136. } else if !socket.is_active() && tcp_active {
  137. debug!("disconnected");
  138. }
  139. tcp_active = socket.is_active();
  140. if socket.may_recv() {
  141. let data = socket
  142. .recv(|data| {
  143. let data = data.to_owned();
  144. if !data.is_empty() {
  145. debug!(
  146. "recv data: {:?}",
  147. str::from_utf8(data.as_ref()).unwrap_or("(invalid utf8)")
  148. );
  149. }
  150. (data.len(), data)
  151. })
  152. .unwrap();
  153. if socket.can_send() && !data.is_empty() {
  154. debug!(
  155. "send data: {:?}",
  156. str::from_utf8(data.as_ref()).unwrap_or("(invalid utf8)")
  157. );
  158. socket.send_slice(&data[..]).unwrap();
  159. }
  160. } else if socket.may_send() {
  161. debug!("close");
  162. socket.close();
  163. }
  164. phy_wait(fd, iface.poll_delay(timestamp)).expect("wait error");
  165. }
  166. }