sixlowpan.rs 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. //! 6lowpan example
  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::os::unix::io::AsRawFd;
  45. use std::str;
  46. use smoltcp::iface::{Config, Interface, SocketSet};
  47. use smoltcp::phy::{wait as phy_wait, Device, Medium, RawSocket};
  48. use smoltcp::socket::tcp;
  49. use smoltcp::socket::udp;
  50. use smoltcp::time::Instant;
  51. use smoltcp::wire::{EthernetAddress, Ieee802154Address, Ieee802154Pan, IpAddress, IpCidr};
  52. fn main() {
  53. utils::setup_logging("");
  54. let (mut opts, mut free) = utils::create_options();
  55. utils::add_middleware_options(&mut opts, &mut free);
  56. let mut matches = utils::parse_options(&opts, free);
  57. let device = RawSocket::new("wpan1", Medium::Ieee802154).unwrap();
  58. let fd = device.as_raw_fd();
  59. let mut device =
  60. utils::parse_middleware_options(&mut matches, device, /*loopback=*/ false);
  61. // Create interface
  62. let mut config = match device.capabilities().medium {
  63. Medium::Ethernet => {
  64. Config::new(EthernetAddress([0x02, 0x00, 0x00, 0x00, 0x00, 0x01]).into())
  65. }
  66. Medium::Ip => Config::new(smoltcp::wire::HardwareAddress::Ip),
  67. Medium::Ieee802154 => Config::new(
  68. Ieee802154Address::Extended([0x1a, 0x0b, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42]).into(),
  69. ),
  70. };
  71. config.random_seed = rand::random();
  72. config.pan_id = Some(Ieee802154Pan(0xbeef));
  73. let mut iface = Interface::new(config, &mut device, Instant::now());
  74. iface.update_ip_addrs(|ip_addrs| {
  75. ip_addrs
  76. .push(IpCidr::new(
  77. IpAddress::v6(0xfe80, 0, 0, 0, 0x180b, 0x4242, 0x4242, 0x4242),
  78. 64,
  79. ))
  80. .unwrap();
  81. });
  82. // Create sockets
  83. let udp_rx_buffer = udp::PacketBuffer::new(vec![udp::PacketMetadata::EMPTY], vec![0; 1280]);
  84. let udp_tx_buffer = udp::PacketBuffer::new(vec![udp::PacketMetadata::EMPTY], vec![0; 1280]);
  85. let udp_socket = udp::Socket::new(udp_rx_buffer, udp_tx_buffer);
  86. let tcp_rx_buffer = tcp::SocketBuffer::new(vec![0; 4096]);
  87. let tcp_tx_buffer = tcp::SocketBuffer::new(vec![0; 4096]);
  88. let tcp_socket = tcp::Socket::new(tcp_rx_buffer, tcp_tx_buffer);
  89. let mut sockets = SocketSet::new(vec![]);
  90. let udp_handle = sockets.add(udp_socket);
  91. let tcp_handle = sockets.add(tcp_socket);
  92. let socket = sockets.get_mut::<tcp::Socket>(tcp_handle);
  93. socket.listen(50000).unwrap();
  94. let mut tcp_active = false;
  95. loop {
  96. let timestamp = Instant::now();
  97. iface.poll(timestamp, &mut device, &mut sockets);
  98. // udp:6969: respond "hello"
  99. let socket = sockets.get_mut::<udp::Socket>(udp_handle);
  100. if !socket.is_open() {
  101. socket.bind(6969).unwrap()
  102. }
  103. let mut buffer = vec![0; 1500];
  104. let client = match socket.recv() {
  105. Ok((data, endpoint)) => {
  106. debug!(
  107. "udp:6969 recv data: {:?} from {}",
  108. str::from_utf8(data).unwrap(),
  109. endpoint
  110. );
  111. buffer[..data.len()].copy_from_slice(data);
  112. Some((data.len(), endpoint))
  113. }
  114. Err(_) => None,
  115. };
  116. if let Some((len, endpoint)) = client {
  117. debug!(
  118. "udp:6969 send data: {:?}",
  119. str::from_utf8(&buffer[..len]).unwrap()
  120. );
  121. socket.send_slice(&buffer[..len], endpoint).unwrap();
  122. }
  123. let socket = sockets.get_mut::<tcp::Socket>(tcp_handle);
  124. if socket.is_active() && !tcp_active {
  125. debug!("connected");
  126. } else if !socket.is_active() && tcp_active {
  127. debug!("disconnected");
  128. }
  129. tcp_active = socket.is_active();
  130. if socket.may_recv() {
  131. let data = socket
  132. .recv(|data| {
  133. let data = data.to_owned();
  134. if !data.is_empty() {
  135. debug!(
  136. "recv data: {:?}",
  137. str::from_utf8(data.as_ref()).unwrap_or("(invalid utf8)")
  138. );
  139. }
  140. (data.len(), data)
  141. })
  142. .unwrap();
  143. if socket.can_send() && !data.is_empty() {
  144. debug!(
  145. "send data: {:?}",
  146. str::from_utf8(data.as_ref()).unwrap_or("(invalid utf8)")
  147. );
  148. socket.send_slice(&data[..]).unwrap();
  149. }
  150. } else if socket.may_send() {
  151. debug!("close");
  152. socket.close();
  153. }
  154. phy_wait(fd, iface.poll_delay(timestamp, &sockets)).expect("wait error");
  155. }
  156. }