ieee802154.rs 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085
  1. use core::fmt;
  2. use byteorder::{ByteOrder, LittleEndian};
  3. use super::{Error, Result};
  4. use crate::wire::ipv6::Address as Ipv6Address;
  5. enum_with_unknown! {
  6. /// IEEE 802.15.4 frame type.
  7. pub enum FrameType(u8) {
  8. Beacon = 0b000,
  9. Data = 0b001,
  10. Acknowledgement = 0b010,
  11. MacCommand = 0b011,
  12. Multipurpose = 0b101,
  13. FragmentOrFrak = 0b110,
  14. Extended = 0b111,
  15. }
  16. }
  17. impl fmt::Display for FrameType {
  18. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  19. match self {
  20. FrameType::Beacon => write!(f, "Beacon"),
  21. FrameType::Data => write!(f, "Data"),
  22. FrameType::Acknowledgement => write!(f, "Ack"),
  23. FrameType::MacCommand => write!(f, "MAC command"),
  24. FrameType::Multipurpose => write!(f, "Multipurpose"),
  25. FrameType::FragmentOrFrak => write!(f, "FragmentOrFrak"),
  26. FrameType::Extended => write!(f, "Extended"),
  27. FrameType::Unknown(id) => write!(f, "0b{id:04b}"),
  28. }
  29. }
  30. }
  31. enum_with_unknown! {
  32. /// IEEE 802.15.4 addressing mode for destination and source addresses.
  33. pub enum AddressingMode(u8) {
  34. Absent = 0b00,
  35. Short = 0b10,
  36. Extended = 0b11,
  37. }
  38. }
  39. impl AddressingMode {
  40. /// Return the size in octets of the address.
  41. const fn size(&self) -> usize {
  42. match self {
  43. AddressingMode::Absent => 0,
  44. AddressingMode::Short => 2,
  45. AddressingMode::Extended => 8,
  46. AddressingMode::Unknown(_) => 0, // TODO(thvdveld): what do we need to here?
  47. }
  48. }
  49. }
  50. impl fmt::Display for AddressingMode {
  51. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  52. match self {
  53. AddressingMode::Absent => write!(f, "Absent"),
  54. AddressingMode::Short => write!(f, "Short"),
  55. AddressingMode::Extended => write!(f, "Extended"),
  56. AddressingMode::Unknown(id) => write!(f, "0b{id:04b}"),
  57. }
  58. }
  59. }
  60. /// A IEEE 802.15.4 PAN.
  61. #[derive(Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)]
  62. pub struct Pan(pub u16);
  63. impl Pan {
  64. pub const BROADCAST: Self = Self(0xffff);
  65. /// Return the PAN ID as bytes.
  66. pub fn as_bytes(&self) -> [u8; 2] {
  67. let mut pan = [0u8; 2];
  68. LittleEndian::write_u16(&mut pan, self.0);
  69. pan
  70. }
  71. }
  72. impl fmt::Display for Pan {
  73. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  74. write!(f, "{:0x}", self.0)
  75. }
  76. }
  77. #[cfg(feature = "defmt")]
  78. impl defmt::Format for Pan {
  79. fn format(&self, fmt: defmt::Formatter) {
  80. defmt::write!(fmt, "{:02x}", self.0)
  81. }
  82. }
  83. /// A IEEE 802.15.4 address.
  84. #[derive(Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)]
  85. pub enum Address {
  86. Absent,
  87. Short([u8; 2]),
  88. Extended([u8; 8]),
  89. }
  90. #[cfg(feature = "defmt")]
  91. impl defmt::Format for Address {
  92. fn format(&self, f: defmt::Formatter) {
  93. match self {
  94. Self::Absent => defmt::write!(f, "not-present"),
  95. Self::Short(bytes) => defmt::write!(f, "{:02x}:{:02x}", bytes[0], bytes[1]),
  96. Self::Extended(bytes) => defmt::write!(
  97. f,
  98. "{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}",
  99. bytes[0],
  100. bytes[1],
  101. bytes[2],
  102. bytes[3],
  103. bytes[4],
  104. bytes[5],
  105. bytes[6],
  106. bytes[7]
  107. ),
  108. }
  109. }
  110. }
  111. #[cfg(test)]
  112. impl Default for Address {
  113. fn default() -> Self {
  114. Address::Extended([0u8; 8])
  115. }
  116. }
  117. impl Address {
  118. /// The broadcast address.
  119. pub const BROADCAST: Address = Address::Short([0xff; 2]);
  120. /// Query whether the address is an unicast address.
  121. pub fn is_unicast(&self) -> bool {
  122. !self.is_broadcast()
  123. }
  124. /// Query whether this address is the broadcast address.
  125. pub fn is_broadcast(&self) -> bool {
  126. *self == Self::BROADCAST
  127. }
  128. const fn short_from_bytes(a: [u8; 2]) -> Self {
  129. Self::Short(a)
  130. }
  131. const fn extended_from_bytes(a: [u8; 8]) -> Self {
  132. Self::Extended(a)
  133. }
  134. pub fn from_bytes(a: &[u8]) -> Self {
  135. if a.len() == 2 {
  136. let mut b = [0u8; 2];
  137. b.copy_from_slice(a);
  138. Address::Short(b)
  139. } else if a.len() == 8 {
  140. let mut b = [0u8; 8];
  141. b.copy_from_slice(a);
  142. Address::Extended(b)
  143. } else {
  144. panic!("Not an IEEE802.15.4 address");
  145. }
  146. }
  147. pub const fn as_bytes(&self) -> &[u8] {
  148. match self {
  149. Address::Absent => &[],
  150. Address::Short(value) => value,
  151. Address::Extended(value) => value,
  152. }
  153. }
  154. /// Convert the extended address to an Extended Unique Identifier (EUI-64)
  155. pub fn as_eui_64(&self) -> Option<[u8; 8]> {
  156. match self {
  157. Address::Absent | Address::Short(_) => None,
  158. Address::Extended(value) => {
  159. let mut bytes = [0; 8];
  160. bytes.copy_from_slice(&value[..]);
  161. bytes[0] ^= 1 << 1;
  162. Some(bytes)
  163. }
  164. }
  165. }
  166. /// Convert an extended address to a link-local IPv6 address using the EUI-64 format from
  167. /// RFC2464.
  168. pub fn as_link_local_address(&self) -> Option<Ipv6Address> {
  169. let mut bytes = [0; 16];
  170. bytes[0] = 0xfe;
  171. bytes[1] = 0x80;
  172. bytes[8..].copy_from_slice(&self.as_eui_64()?);
  173. Some(Ipv6Address::from_bytes(&bytes))
  174. }
  175. }
  176. impl fmt::Display for Address {
  177. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  178. match self {
  179. Self::Absent => write!(f, "not-present"),
  180. Self::Short(bytes) => write!(f, "{:02x}:{:02x}", bytes[0], bytes[1]),
  181. Self::Extended(bytes) => write!(
  182. f,
  183. "{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}",
  184. bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7]
  185. ),
  186. }
  187. }
  188. }
  189. enum_with_unknown! {
  190. /// IEEE 802.15.4 addressing mode for destination and source addresses.
  191. pub enum FrameVersion(u8) {
  192. Ieee802154_2003 = 0b00,
  193. Ieee802154_2006 = 0b01,
  194. Ieee802154 = 0b10,
  195. }
  196. }
  197. /// A read/write wrapper around an IEEE 802.15.4 frame buffer.
  198. #[derive(Debug, Clone)]
  199. pub struct Frame<T: AsRef<[u8]>> {
  200. buffer: T,
  201. }
  202. mod field {
  203. use crate::wire::field::*;
  204. pub const FRAMECONTROL: Field = 0..2;
  205. pub const SEQUENCE_NUMBER: usize = 2;
  206. pub const ADDRESSING: Rest = 3..;
  207. }
  208. macro_rules! fc_bit_field {
  209. ($field:ident, $bit:literal) => {
  210. #[inline]
  211. pub fn $field(&self) -> bool {
  212. let data = self.buffer.as_ref();
  213. let raw = LittleEndian::read_u16(&data[field::FRAMECONTROL]);
  214. ((raw >> $bit) & 0b1) == 0b1
  215. }
  216. };
  217. }
  218. macro_rules! set_fc_bit_field {
  219. ($field:ident, $bit:literal) => {
  220. #[inline]
  221. pub fn $field(&mut self, val: bool) {
  222. let data = &mut self.buffer.as_mut()[field::FRAMECONTROL];
  223. let mut raw = LittleEndian::read_u16(data);
  224. raw |= ((val as u16) << $bit);
  225. data.copy_from_slice(&raw.to_le_bytes());
  226. }
  227. };
  228. }
  229. impl<T: AsRef<[u8]>> Frame<T> {
  230. /// Input a raw octet buffer with Ethernet frame structure.
  231. pub const fn new_unchecked(buffer: T) -> Frame<T> {
  232. Frame { buffer }
  233. }
  234. /// Shorthand for a combination of [new_unchecked] and [check_len].
  235. ///
  236. /// [new_unchecked]: #method.new_unchecked
  237. /// [check_len]: #method.check_len
  238. pub fn new_checked(buffer: T) -> Result<Frame<T>> {
  239. let packet = Self::new_unchecked(buffer);
  240. packet.check_len()?;
  241. if matches!(packet.dst_addressing_mode(), AddressingMode::Unknown(_)) {
  242. return Err(Error);
  243. }
  244. if matches!(packet.src_addressing_mode(), AddressingMode::Unknown(_)) {
  245. return Err(Error);
  246. }
  247. Ok(packet)
  248. }
  249. /// Ensure that no accessor method will panic if called.
  250. /// Returns `Err(Error)` if the buffer is too short.
  251. pub fn check_len(&self) -> Result<()> {
  252. // We need at least 3 bytes
  253. if self.buffer.as_ref().len() < 3 {
  254. return Err(Error);
  255. }
  256. let mut offset = field::ADDRESSING.start + 2;
  257. // Calculate the size of the addressing field.
  258. offset += self.dst_addressing_mode().size();
  259. offset += self.src_addressing_mode().size();
  260. if !self.pan_id_compression() {
  261. offset += 2;
  262. }
  263. if offset > self.buffer.as_ref().len() {
  264. return Err(Error);
  265. }
  266. Ok(())
  267. }
  268. /// Consumes the frame, returning the underlying buffer.
  269. pub fn into_inner(self) -> T {
  270. self.buffer
  271. }
  272. /// Return the FrameType field.
  273. #[inline]
  274. pub fn frame_type(&self) -> FrameType {
  275. let data = self.buffer.as_ref();
  276. let raw = LittleEndian::read_u16(&data[field::FRAMECONTROL]);
  277. let ft = (raw & 0b11) as u8;
  278. FrameType::from(ft)
  279. }
  280. fc_bit_field!(security_enabled, 3);
  281. fc_bit_field!(frame_pending, 4);
  282. fc_bit_field!(ack_request, 5);
  283. fc_bit_field!(pan_id_compression, 6);
  284. fc_bit_field!(sequence_number_suppression, 8);
  285. fc_bit_field!(ie_present, 9);
  286. /// Return the destination addressing mode.
  287. #[inline]
  288. pub fn dst_addressing_mode(&self) -> AddressingMode {
  289. let data = self.buffer.as_ref();
  290. let raw = LittleEndian::read_u16(&data[field::FRAMECONTROL]);
  291. let am = ((raw >> 10) & 0b11) as u8;
  292. AddressingMode::from(am)
  293. }
  294. /// Return the frame version.
  295. #[inline]
  296. pub fn frame_version(&self) -> FrameVersion {
  297. let data = self.buffer.as_ref();
  298. let raw = LittleEndian::read_u16(&data[field::FRAMECONTROL]);
  299. let fv = ((raw >> 12) & 0b11) as u8;
  300. FrameVersion::from(fv)
  301. }
  302. /// Return the source addressing mode.
  303. #[inline]
  304. pub fn src_addressing_mode(&self) -> AddressingMode {
  305. let data = self.buffer.as_ref();
  306. let raw = LittleEndian::read_u16(&data[field::FRAMECONTROL]);
  307. let am = ((raw >> 14) & 0b11) as u8;
  308. AddressingMode::from(am)
  309. }
  310. /// Return the sequence number of the frame.
  311. #[inline]
  312. pub fn sequence_number(&self) -> Option<u8> {
  313. match self.frame_type() {
  314. FrameType::Beacon
  315. | FrameType::Data
  316. | FrameType::Acknowledgement
  317. | FrameType::MacCommand
  318. | FrameType::Multipurpose => {
  319. let data = self.buffer.as_ref();
  320. let raw = data[field::SEQUENCE_NUMBER];
  321. Some(raw)
  322. }
  323. FrameType::Extended | FrameType::FragmentOrFrak | FrameType::Unknown(_) => None,
  324. }
  325. }
  326. /// Return the addressing fields.
  327. #[inline]
  328. fn addressing_fields(&self) -> Option<&[u8]> {
  329. match self.frame_type() {
  330. FrameType::Beacon
  331. | FrameType::Data
  332. | FrameType::MacCommand
  333. | FrameType::Multipurpose => (),
  334. FrameType::Acknowledgement if self.frame_version() == FrameVersion::Ieee802154 => (),
  335. FrameType::Acknowledgement
  336. | FrameType::Extended
  337. | FrameType::FragmentOrFrak
  338. | FrameType::Unknown(_) => return None,
  339. }
  340. let mut offset = 2;
  341. // Calculate the size of the addressing field.
  342. offset += self.dst_addressing_mode().size();
  343. offset += self.src_addressing_mode().size();
  344. if !self.pan_id_compression() {
  345. offset += 2;
  346. }
  347. Some(&self.buffer.as_ref()[field::ADDRESSING][..offset])
  348. }
  349. /// Return the destination PAN field.
  350. #[inline]
  351. pub fn dst_pan_id(&self) -> Option<Pan> {
  352. let addressing_fields = self.addressing_fields()?;
  353. match self.dst_addressing_mode() {
  354. AddressingMode::Absent => None,
  355. AddressingMode::Short | AddressingMode::Extended => {
  356. Some(Pan(LittleEndian::read_u16(&addressing_fields[0..2])))
  357. }
  358. AddressingMode::Unknown(_) => None,
  359. }
  360. }
  361. /// Return the destination address field.
  362. #[inline]
  363. pub fn dst_addr(&self) -> Option<Address> {
  364. let addressing_fields = self.addressing_fields()?;
  365. match self.dst_addressing_mode() {
  366. AddressingMode::Absent => Some(Address::Absent),
  367. AddressingMode::Short => {
  368. let mut raw = [0u8; 2];
  369. raw.clone_from_slice(&addressing_fields[2..4]);
  370. raw.reverse();
  371. Some(Address::short_from_bytes(raw))
  372. }
  373. AddressingMode::Extended => {
  374. let mut raw = [0u8; 8];
  375. raw.clone_from_slice(&addressing_fields[2..10]);
  376. raw.reverse();
  377. Some(Address::extended_from_bytes(raw))
  378. }
  379. AddressingMode::Unknown(_) => None,
  380. }
  381. }
  382. /// Return the destination PAN field.
  383. #[inline]
  384. pub fn src_pan_id(&self) -> Option<Pan> {
  385. if self.pan_id_compression() {
  386. return None;
  387. }
  388. let addressing_fields = self.addressing_fields()?;
  389. let offset = self.dst_addressing_mode().size() + 2;
  390. match self.src_addressing_mode() {
  391. AddressingMode::Absent => None,
  392. AddressingMode::Short | AddressingMode::Extended => Some(Pan(LittleEndian::read_u16(
  393. &addressing_fields[offset..offset + 2],
  394. ))),
  395. AddressingMode::Unknown(_) => None,
  396. }
  397. }
  398. /// Return the source address field.
  399. #[inline]
  400. pub fn src_addr(&self) -> Option<Address> {
  401. let addressing_fields = self.addressing_fields()?;
  402. let mut offset = match self.dst_addressing_mode() {
  403. AddressingMode::Absent => 0,
  404. AddressingMode::Short => 2,
  405. AddressingMode::Extended => 8,
  406. _ => return None, // TODO(thvdveld): what do we do here?
  407. } + 2;
  408. if !self.pan_id_compression() {
  409. offset += 2;
  410. }
  411. match self.src_addressing_mode() {
  412. AddressingMode::Absent => Some(Address::Absent),
  413. AddressingMode::Short => {
  414. let mut raw = [0u8; 2];
  415. raw.clone_from_slice(&addressing_fields[offset..offset + 2]);
  416. raw.reverse();
  417. Some(Address::short_from_bytes(raw))
  418. }
  419. AddressingMode::Extended => {
  420. let mut raw = [0u8; 8];
  421. raw.clone_from_slice(&addressing_fields[offset..offset + 8]);
  422. raw.reverse();
  423. Some(Address::extended_from_bytes(raw))
  424. }
  425. AddressingMode::Unknown(_) => None,
  426. }
  427. }
  428. /// Return the index where the auxiliary security header starts.
  429. fn aux_security_header_start(&self) -> usize {
  430. // We start with 3, because 2 bytes for frame control and the sequence number.
  431. let mut index = 3;
  432. index += self.addressing_fields().unwrap().len();
  433. index
  434. }
  435. /// Return the index where the payload starts.
  436. fn payload_start(&self) -> usize {
  437. let mut index = self.aux_security_header_start();
  438. if self.security_enabled() {
  439. // We add 5 because 1 byte for control bits and 4 bytes for frame counter.
  440. index += 5;
  441. index += if let Some(len) = self.key_identifier_length() {
  442. len as usize
  443. } else {
  444. 0
  445. };
  446. }
  447. index
  448. }
  449. /// Return the length of the key identifier field.
  450. fn key_identifier_length(&self) -> Option<u8> {
  451. Some(match self.key_identifier_mode() {
  452. 0 => 0,
  453. 1 => 1,
  454. 2 => 5,
  455. 3 => 9,
  456. _ => return None,
  457. })
  458. }
  459. /// Return the security level of the auxiliary security header.
  460. pub fn security_level(&self) -> u8 {
  461. let index = self.aux_security_header_start();
  462. let b = self.buffer.as_ref()[index..][0];
  463. b & 0b111
  464. }
  465. /// Return the key identifier mode used by the auxiliary security header.
  466. pub fn key_identifier_mode(&self) -> u8 {
  467. let index = self.aux_security_header_start();
  468. let b = self.buffer.as_ref()[index..][0];
  469. (b >> 3) & 0b11
  470. }
  471. /// Return the frame counter field.
  472. pub fn frame_counter(&self) -> u32 {
  473. let index = self.aux_security_header_start();
  474. let b = &self.buffer.as_ref()[index..];
  475. LittleEndian::read_u32(&b[1..1 + 4])
  476. }
  477. /// Return the Key Identifier field.
  478. fn key_identifier(&self) -> &[u8] {
  479. let index = self.aux_security_header_start();
  480. let b = &self.buffer.as_ref()[index..];
  481. let length = if let Some(len) = self.key_identifier_length() {
  482. len as usize
  483. } else {
  484. 0
  485. };
  486. &b[5..][..length]
  487. }
  488. /// Return the Key Source field.
  489. pub fn key_source(&self) -> Option<&[u8]> {
  490. let ki = self.key_identifier();
  491. let len = ki.len();
  492. if len > 1 {
  493. Some(&ki[..len - 1])
  494. } else {
  495. None
  496. }
  497. }
  498. /// Return the Key Index field.
  499. pub fn key_index(&self) -> Option<u8> {
  500. let ki = self.key_identifier();
  501. let len = ki.len();
  502. if len > 0 {
  503. Some(ki[len - 1])
  504. } else {
  505. None
  506. }
  507. }
  508. /// Return the Message Integrity Code (MIC).
  509. pub fn message_integrity_code(&self) -> Option<&[u8]> {
  510. let mic_len = match self.security_level() {
  511. 0 | 4 => return None,
  512. 1 | 5 => 4,
  513. 2 | 6 => 8,
  514. 3 | 7 => 16,
  515. _ => panic!(),
  516. };
  517. let data = &self.buffer.as_ref();
  518. let len = data.len();
  519. Some(&data[len - mic_len..])
  520. }
  521. /// Return the MAC header.
  522. pub fn mac_header(&self) -> &[u8] {
  523. let data = &self.buffer.as_ref();
  524. &data[..self.payload_start()]
  525. }
  526. }
  527. impl<'a, T: AsRef<[u8]> + ?Sized> Frame<&'a T> {
  528. /// Return a pointer to the payload.
  529. #[inline]
  530. pub fn payload(&self) -> Option<&'a [u8]> {
  531. match self.frame_type() {
  532. FrameType::Data => {
  533. let index = self.payload_start();
  534. let data = &self.buffer.as_ref();
  535. Some(&data[index..])
  536. }
  537. _ => None,
  538. }
  539. }
  540. }
  541. impl<T: AsRef<[u8]> + AsMut<[u8]>> Frame<T> {
  542. /// Set the frame type.
  543. #[inline]
  544. pub fn set_frame_type(&mut self, frame_type: FrameType) {
  545. let data = &mut self.buffer.as_mut()[field::FRAMECONTROL];
  546. let mut raw = LittleEndian::read_u16(data);
  547. raw = (raw & !(0b111)) | (u8::from(frame_type) as u16 & 0b111);
  548. data.copy_from_slice(&raw.to_le_bytes());
  549. }
  550. set_fc_bit_field!(set_security_enabled, 3);
  551. set_fc_bit_field!(set_frame_pending, 4);
  552. set_fc_bit_field!(set_ack_request, 5);
  553. set_fc_bit_field!(set_pan_id_compression, 6);
  554. /// Set the frame version.
  555. #[inline]
  556. pub fn set_frame_version(&mut self, version: FrameVersion) {
  557. let data = &mut self.buffer.as_mut()[field::FRAMECONTROL];
  558. let mut raw = LittleEndian::read_u16(data);
  559. raw = (raw & !(0b11 << 12)) | ((u8::from(version) as u16 & 0b11) << 12);
  560. data.copy_from_slice(&raw.to_le_bytes());
  561. }
  562. /// Set the frame sequence number.
  563. #[inline]
  564. pub fn set_sequence_number(&mut self, value: u8) {
  565. let data = self.buffer.as_mut();
  566. data[field::SEQUENCE_NUMBER] = value;
  567. }
  568. /// Set the destination PAN ID.
  569. #[inline]
  570. pub fn set_dst_pan_id(&mut self, value: Pan) {
  571. // NOTE the destination addressing mode must be different than Absent.
  572. // This is the reason why we set it to Extended.
  573. self.set_dst_addressing_mode(AddressingMode::Extended);
  574. let data = self.buffer.as_mut();
  575. data[field::ADDRESSING][..2].copy_from_slice(&value.as_bytes());
  576. }
  577. /// Set the destination address.
  578. #[inline]
  579. pub fn set_dst_addr(&mut self, value: Address) {
  580. match value {
  581. Address::Absent => self.set_dst_addressing_mode(AddressingMode::Absent),
  582. Address::Short(mut value) => {
  583. value.reverse();
  584. self.set_dst_addressing_mode(AddressingMode::Short);
  585. let data = self.buffer.as_mut();
  586. data[field::ADDRESSING][2..2 + 2].copy_from_slice(&value);
  587. value.reverse();
  588. }
  589. Address::Extended(mut value) => {
  590. value.reverse();
  591. self.set_dst_addressing_mode(AddressingMode::Extended);
  592. let data = &mut self.buffer.as_mut()[field::ADDRESSING];
  593. data[2..2 + 8].copy_from_slice(&value);
  594. value.reverse();
  595. }
  596. }
  597. }
  598. /// Set the destination addressing mode.
  599. #[inline]
  600. fn set_dst_addressing_mode(&mut self, value: AddressingMode) {
  601. let data = &mut self.buffer.as_mut()[field::FRAMECONTROL];
  602. let mut raw = LittleEndian::read_u16(data);
  603. raw = (raw & !(0b11 << 10)) | ((u8::from(value) as u16 & 0b11) << 10);
  604. data.copy_from_slice(&raw.to_le_bytes());
  605. }
  606. /// Set the source PAN ID.
  607. #[inline]
  608. pub fn set_src_pan_id(&mut self, value: Pan) {
  609. let offset = match self.dst_addressing_mode() {
  610. AddressingMode::Absent => 0,
  611. AddressingMode::Short => 2,
  612. AddressingMode::Extended => 8,
  613. _ => unreachable!(),
  614. } + 2;
  615. let data = &mut self.buffer.as_mut()[field::ADDRESSING];
  616. data[offset..offset + 2].copy_from_slice(&value.as_bytes());
  617. }
  618. /// Set the source address.
  619. #[inline]
  620. pub fn set_src_addr(&mut self, value: Address) {
  621. let offset = match self.dst_addressing_mode() {
  622. AddressingMode::Absent => 0,
  623. AddressingMode::Short => 2,
  624. AddressingMode::Extended => 8,
  625. _ => unreachable!(),
  626. } + 2;
  627. let offset = offset + if self.pan_id_compression() { 0 } else { 2 };
  628. match value {
  629. Address::Absent => self.set_src_addressing_mode(AddressingMode::Absent),
  630. Address::Short(mut value) => {
  631. value.reverse();
  632. self.set_src_addressing_mode(AddressingMode::Short);
  633. let data = &mut self.buffer.as_mut()[field::ADDRESSING];
  634. data[offset..offset + 2].copy_from_slice(&value);
  635. value.reverse();
  636. }
  637. Address::Extended(mut value) => {
  638. value.reverse();
  639. self.set_src_addressing_mode(AddressingMode::Extended);
  640. let data = &mut self.buffer.as_mut()[field::ADDRESSING];
  641. data[offset..offset + 8].copy_from_slice(&value);
  642. value.reverse();
  643. }
  644. }
  645. }
  646. /// Set the source addressing mode.
  647. #[inline]
  648. fn set_src_addressing_mode(&mut self, value: AddressingMode) {
  649. let data = &mut self.buffer.as_mut()[field::FRAMECONTROL];
  650. let mut raw = LittleEndian::read_u16(data);
  651. raw = (raw & !(0b11 << 14)) | ((u8::from(value) as u16 & 0b11) << 14);
  652. data.copy_from_slice(&raw.to_le_bytes());
  653. }
  654. /// Return a mutable pointer to the payload.
  655. #[inline]
  656. pub fn payload_mut(&mut self) -> Option<&mut [u8]> {
  657. match self.frame_type() {
  658. FrameType::Data => {
  659. let index = self.payload_start();
  660. let data = self.buffer.as_mut();
  661. Some(&mut data[index..])
  662. }
  663. _ => None,
  664. }
  665. }
  666. }
  667. impl<T: AsRef<[u8]>> fmt::Display for Frame<T> {
  668. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  669. write!(f, "IEEE802.15.4 frame type={}", self.frame_type())?;
  670. if let Some(seq) = self.sequence_number() {
  671. write!(f, " seq={:02x}", seq)?;
  672. }
  673. if let Some(pan) = self.dst_pan_id() {
  674. write!(f, " dst-pan={}", pan)?;
  675. }
  676. if let Some(pan) = self.src_pan_id() {
  677. write!(f, " src-pan={}", pan)?;
  678. }
  679. if let Some(addr) = self.dst_addr() {
  680. write!(f, " dst={}", addr)?;
  681. }
  682. if let Some(addr) = self.src_addr() {
  683. write!(f, " src={}", addr)?;
  684. }
  685. Ok(())
  686. }
  687. }
  688. #[cfg(feature = "defmt")]
  689. impl<T: AsRef<[u8]>> defmt::Format for Frame<T> {
  690. fn format(&self, f: defmt::Formatter) {
  691. defmt::write!(f, "IEEE802.15.4 frame type={}", self.frame_type());
  692. if let Some(seq) = self.sequence_number() {
  693. defmt::write!(f, " seq={:02x}", seq);
  694. }
  695. if let Some(pan) = self.dst_pan_id() {
  696. defmt::write!(f, " dst-pan={}", pan);
  697. }
  698. if let Some(pan) = self.src_pan_id() {
  699. defmt::write!(f, " src-pan={}", pan);
  700. }
  701. if let Some(addr) = self.dst_addr() {
  702. defmt::write!(f, " dst={}", addr);
  703. }
  704. if let Some(addr) = self.src_addr() {
  705. defmt::write!(f, " src={}", addr);
  706. }
  707. }
  708. }
  709. /// A high-level representation of an IEEE802.15.4 frame.
  710. #[derive(Debug, PartialEq, Eq, Clone, Copy)]
  711. #[cfg_attr(feature = "defmt", derive(defmt::Format))]
  712. pub struct Repr {
  713. pub frame_type: FrameType,
  714. pub security_enabled: bool,
  715. pub frame_pending: bool,
  716. pub ack_request: bool,
  717. pub sequence_number: Option<u8>,
  718. pub pan_id_compression: bool,
  719. pub frame_version: FrameVersion,
  720. pub dst_pan_id: Option<Pan>,
  721. pub dst_addr: Option<Address>,
  722. pub src_pan_id: Option<Pan>,
  723. pub src_addr: Option<Address>,
  724. }
  725. impl Repr {
  726. /// Parse an IEEE 802.15.4 frame and return a high-level representation.
  727. pub fn parse<T: AsRef<[u8]> + ?Sized>(packet: &Frame<&T>) -> Result<Repr> {
  728. // Ensure the basic accessors will work.
  729. packet.check_len()?;
  730. Ok(Repr {
  731. frame_type: packet.frame_type(),
  732. security_enabled: packet.security_enabled(),
  733. frame_pending: packet.frame_pending(),
  734. ack_request: packet.ack_request(),
  735. sequence_number: packet.sequence_number(),
  736. pan_id_compression: packet.pan_id_compression(),
  737. frame_version: packet.frame_version(),
  738. dst_pan_id: packet.dst_pan_id(),
  739. dst_addr: packet.dst_addr(),
  740. src_pan_id: packet.src_pan_id(),
  741. src_addr: packet.src_addr(),
  742. })
  743. }
  744. /// Return the length of a buffer required to hold a packet with the payload of a given length.
  745. #[inline]
  746. pub const fn buffer_len(&self) -> usize {
  747. 3 + 2
  748. + match self.dst_addr {
  749. Some(Address::Absent) | None => 0,
  750. Some(Address::Short(_)) => 2,
  751. Some(Address::Extended(_)) => 8,
  752. }
  753. + if !self.pan_id_compression { 2 } else { 0 }
  754. + match self.src_addr {
  755. Some(Address::Absent) | None => 0,
  756. Some(Address::Short(_)) => 2,
  757. Some(Address::Extended(_)) => 8,
  758. }
  759. }
  760. /// Emit a high-level representation into an IEEE802.15.4 frame.
  761. pub fn emit<T: AsRef<[u8]> + AsMut<[u8]>>(&self, frame: &mut Frame<T>) {
  762. frame.set_frame_type(self.frame_type);
  763. frame.set_security_enabled(self.security_enabled);
  764. frame.set_frame_pending(self.frame_pending);
  765. frame.set_ack_request(self.ack_request);
  766. frame.set_pan_id_compression(self.pan_id_compression);
  767. frame.set_frame_version(self.frame_version);
  768. if let Some(sequence_number) = self.sequence_number {
  769. frame.set_sequence_number(sequence_number);
  770. }
  771. if let Some(dst_pan_id) = self.dst_pan_id {
  772. frame.set_dst_pan_id(dst_pan_id);
  773. }
  774. if let Some(dst_addr) = self.dst_addr {
  775. frame.set_dst_addr(dst_addr);
  776. }
  777. if !self.pan_id_compression && self.src_pan_id.is_some() {
  778. frame.set_src_pan_id(self.src_pan_id.unwrap());
  779. }
  780. if let Some(src_addr) = self.src_addr {
  781. frame.set_src_addr(src_addr);
  782. }
  783. }
  784. }
  785. #[cfg(test)]
  786. mod test {
  787. use super::*;
  788. #[test]
  789. fn test_broadcast() {
  790. assert!(Address::BROADCAST.is_broadcast());
  791. assert!(!Address::BROADCAST.is_unicast());
  792. }
  793. #[test]
  794. fn prepare_frame() {
  795. let mut buffer = [0u8; 128];
  796. let repr = Repr {
  797. frame_type: FrameType::Data,
  798. security_enabled: false,
  799. frame_pending: false,
  800. ack_request: true,
  801. pan_id_compression: true,
  802. frame_version: FrameVersion::Ieee802154,
  803. sequence_number: Some(1),
  804. dst_pan_id: Some(Pan(0xabcd)),
  805. dst_addr: Some(Address::BROADCAST),
  806. src_pan_id: None,
  807. src_addr: Some(Address::Extended([
  808. 0xc7, 0xd9, 0xb5, 0x14, 0x00, 0x4b, 0x12, 0x00,
  809. ])),
  810. };
  811. let buffer_len = repr.buffer_len();
  812. let mut frame = Frame::new_unchecked(&mut buffer[..buffer_len]);
  813. repr.emit(&mut frame);
  814. println!("{frame:2x?}");
  815. assert_eq!(frame.frame_type(), FrameType::Data);
  816. assert!(!frame.security_enabled());
  817. assert!(!frame.frame_pending());
  818. assert!(frame.ack_request());
  819. assert!(frame.pan_id_compression());
  820. assert_eq!(frame.frame_version(), FrameVersion::Ieee802154);
  821. assert_eq!(frame.sequence_number(), Some(1));
  822. assert_eq!(frame.dst_pan_id(), Some(Pan(0xabcd)));
  823. assert_eq!(frame.dst_addr(), Some(Address::BROADCAST));
  824. assert_eq!(frame.src_pan_id(), None);
  825. assert_eq!(
  826. frame.src_addr(),
  827. Some(Address::Extended([
  828. 0xc7, 0xd9, 0xb5, 0x14, 0x00, 0x4b, 0x12, 0x00
  829. ]))
  830. );
  831. }
  832. macro_rules! vector_test {
  833. ($name:ident $bytes:expr ; $($test_method:ident -> $expected:expr,)*) => {
  834. #[test]
  835. #[allow(clippy::bool_assert_comparison)]
  836. fn $name() -> Result<()> {
  837. let frame = &$bytes;
  838. let frame = Frame::new_checked(frame)?;
  839. $(
  840. assert_eq!(frame.$test_method(), $expected, stringify!($test_method));
  841. )*
  842. Ok(())
  843. }
  844. }
  845. }
  846. vector_test! {
  847. extended_addr
  848. [
  849. 0b0000_0001, 0b1100_1100, // frame control
  850. 0b0, // seq
  851. 0xcd, 0xab, // pan id
  852. 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, // dst addr
  853. 0x03, 0x04, // pan id
  854. 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x02, // src addr
  855. ];
  856. frame_type -> FrameType::Data,
  857. dst_addr -> Some(Address::Extended([0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00])),
  858. src_addr -> Some(Address::Extended([0x02, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00])),
  859. dst_pan_id -> Some(Pan(0xabcd)),
  860. }
  861. vector_test! {
  862. short_addr
  863. [
  864. 0x01, 0x98, // frame control
  865. 0x00, // sequence number
  866. 0x34, 0x12, 0x78, 0x56, // PAN identifier and address of destination
  867. 0x34, 0x12, 0xbc, 0x9a, // PAN identifier and address of source
  868. ];
  869. frame_type -> FrameType::Data,
  870. security_enabled -> false,
  871. frame_pending -> false,
  872. ack_request -> false,
  873. pan_id_compression -> false,
  874. dst_addressing_mode -> AddressingMode::Short,
  875. frame_version -> FrameVersion::Ieee802154_2006,
  876. src_addressing_mode -> AddressingMode::Short,
  877. dst_pan_id -> Some(Pan(0x1234)),
  878. dst_addr -> Some(Address::Short([0x56, 0x78])),
  879. src_pan_id -> Some(Pan(0x1234)),
  880. src_addr -> Some(Address::Short([0x9a, 0xbc])),
  881. }
  882. vector_test! {
  883. zolertia_remote
  884. [
  885. 0x41, 0xd8, // frame control
  886. 0x01, // sequence number
  887. 0xcd, 0xab, // Destination PAN id
  888. 0xff, 0xff, // Short destination address
  889. 0xc7, 0xd9, 0xb5, 0x14, 0x00, 0x4b, 0x12, 0x00, // Extended source address
  890. 0x2b, 0x00, 0x00, 0x00, // payload
  891. ];
  892. frame_type -> FrameType::Data,
  893. security_enabled -> false,
  894. frame_pending -> false,
  895. ack_request -> false,
  896. pan_id_compression -> true,
  897. dst_addressing_mode -> AddressingMode::Short,
  898. frame_version -> FrameVersion::Ieee802154_2006,
  899. src_addressing_mode -> AddressingMode::Extended,
  900. payload -> Some(&[0x2b, 0x00, 0x00, 0x00][..]),
  901. }
  902. vector_test! {
  903. security
  904. [
  905. 0x69,0xdc, // frame control
  906. 0x32, // sequence number
  907. 0xcd,0xab, // destination PAN id
  908. 0xbf,0x9b,0x15,0x06,0x00,0x4b,0x12,0x00, // extended destination address
  909. 0xc7,0xd9,0xb5,0x14,0x00,0x4b,0x12,0x00, // extended source address
  910. 0x05, // security control field
  911. 0x31,0x01,0x00,0x00, // frame counter
  912. 0x3e,0xe8,0xfb,0x85,0xe4,0xcc,0xf4,0x48,0x90,0xfe,0x56,0x66,0xf7,0x1c,0x65,0x9e,0xf9, // data
  913. 0x93,0xc8,0x34,0x2e,// MIC
  914. ];
  915. frame_type -> FrameType::Data,
  916. security_enabled -> true,
  917. frame_pending -> false,
  918. ack_request -> true,
  919. pan_id_compression -> true,
  920. dst_addressing_mode -> AddressingMode::Extended,
  921. frame_version -> FrameVersion::Ieee802154_2006,
  922. src_addressing_mode -> AddressingMode::Extended,
  923. dst_pan_id -> Some(Pan(0xabcd)),
  924. dst_addr -> Some(Address::Extended([0x00,0x12,0x4b,0x00,0x06,0x15,0x9b,0xbf])),
  925. src_pan_id -> None,
  926. src_addr -> Some(Address::Extended([0x00,0x12,0x4b,0x00,0x14,0xb5,0xd9,0xc7])),
  927. security_level -> 5,
  928. key_identifier_mode -> 0,
  929. frame_counter -> 305,
  930. key_source -> None,
  931. key_index -> None,
  932. payload -> Some(&[0x3e,0xe8,0xfb,0x85,0xe4,0xcc,0xf4,0x48,0x90,0xfe,0x56,0x66,0xf7,0x1c,0x65,0x9e,0xf9,0x93,0xc8,0x34,0x2e][..]),
  933. message_integrity_code -> Some(&[0x93, 0xC8, 0x34, 0x2E][..]),
  934. mac_header -> &[
  935. 0x69,0xdc, // frame control
  936. 0x32, // sequence number
  937. 0xcd,0xab, // destination PAN id
  938. 0xbf,0x9b,0x15,0x06,0x00,0x4b,0x12,0x00, // extended destination address
  939. 0xc7,0xd9,0xb5,0x14,0x00,0x4b,0x12,0x00, // extended source address
  940. 0x05, // security control field
  941. 0x31,0x01,0x00,0x00, // frame counter
  942. ][..],
  943. }
  944. }