1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179
//! Partial implementation of the IEEE 802.15.4 Frame //! //! The main type in this module is [Frame], a type that represents an IEEE //! 802.15.4 MAC frame. The other types in this module are supporting types //! that are either part of [Frame] or are required to support its API. //! //! [Frame]: struct.Frame.html use core::mem::size_of_val; use byteorder::{ ByteOrder, LittleEndian, }; use hash32_derive::Hash32; use crate::mac::beacon::Beacon; use crate::mac::command::Command; /// An IEEE 802.15.4 MAC frame /// /// Represents a MAC frame. Can be used to [decode] a frame from bytes, or /// [encode] a frame to bytes. /// /// [decode]: #method.decode /// [encode]: #method.encode #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub struct Frame<'p> { /// Header pub header: Header, /// Content pub content: FrameContent, /// Payload pub payload: &'p [u8], /// Footer /// /// This is a 2-byte CRC checksum. /// /// When creating an instance of this struct for encoding, you don't /// necessarily need to write an actual CRC checksum here. [`Frame::encode`] /// can omit writing this checksum, for example if the transceiver hardware /// automatically adds the checksum for you. pub footer: [u8; 2], } impl<'p> Frame<'p> { /// Decodes a frame from a byte buffer /// /// # Errors /// /// This function returns an error, if the bytes either don't encode a valid /// IEEE 802.15.4 frame, or encode a frame that is not fully supported by /// this implementation. Please refer to [`DecodeError`] for details. /// /// # Example /// /// ``` rust /// use ieee802154::mac::{ /// Address, /// ShortAddress, /// Frame, /// FrameType, /// PanId, /// Security, /// }; /// /// # fn main() -> Result<(), ::ieee802154::mac::DecodeError> { /// // Construct a simple MAC frame. The CRC checksum (the last 2 bytes) is /// // invalid, for the sake of convenience. /// let bytes = [ /// 0x01, 0x98, // frame control /// 0x00, // sequence number /// 0x12, 0x34, 0x56, 0x78, // PAN identifier and address of destination /// 0x12, 0x34, 0x9a, 0xbc, // PAN identifier and address of source /// 0xde, 0xf0, // payload /// 0x12, 0x34, // footer /// ]; /// /// let frame = Frame::decode(&bytes, true)?; /// /// assert_eq!(frame.header.seq, 0x00); /// assert_eq!(frame.header.frame_type, FrameType::Data); /// assert_eq!(frame.header.security, Security::None); /// assert_eq!(frame.header.frame_pending, false); /// assert_eq!(frame.header.ack_request, false); /// assert_eq!(frame.header.pan_id_compress, false); /// /// assert_eq!( /// frame.header.destination, /// Address::Short(PanId(0x3412), ShortAddress(0x7856)) /// ); /// assert_eq!( /// frame.header.source, /// Address::Short(PanId(0x3412), ShortAddress(0xbc9a)) /// ); /// /// assert_eq!(frame.payload, &[0xde, 0xf0]); /// assert_eq!(frame.footer, [0x12, 0x34]); /// # /// # Ok(()) /// # } /// ``` pub fn decode(buf: &'p [u8], contains_footer: bool) -> Result<Self, DecodeError> { let (header, len) = Header::decode(buf)?; let mut footer = [0; 2]; let payload = if contains_footer { if buf[len..].len() < 2 { return Err(DecodeError::NotEnoughBytes); } let footer_pos = buf.len() - 2; footer.copy_from_slice(&buf[footer_pos..]); &buf[len..footer_pos] } else { &buf[len..] }; let (content, used) = FrameContent::decode(payload, &header)?; let payload = &payload[used..]; Ok(Frame { header, content, payload, footer, }) } /// Encodes the frame into a buffer /// /// Returns the number of bytes written to the buffer. /// /// # Panics /// /// Panics, if the buffer is not long enough to hold the frame. If you /// believe that this behavior is inappropriate, please leave your feedback /// on the [issue tracker]. /// /// # Example /// /// ``` rust /// use ieee802154::mac::{ /// Address, /// ShortAddress, /// Frame, /// FrameContent, /// FrameType, /// FrameVersion, /// Header, /// PanId, /// Security, /// WriteFooter, /// }; /// /// let frame = Frame { /// header: Header { /// seq: 0x00, /// frame_type: FrameType::Data, /// security: Security::None, /// frame_pending: false, /// ack_request: false, /// pan_id_compress: false, /// version: FrameVersion::Ieee802154_2006, /// /// destination: Address::Short(PanId(0x1234), ShortAddress(0x5678)), /// source: Address::Short(PanId(0x1234), ShortAddress(0x9abc)), /// }, /// content: FrameContent::Data, /// payload: &[0xde, 0xf0], /// footer: [0x12, 0x34] /// }; /// /// let mut bytes = [0u8; 32]; /// /// frame.encode(&mut bytes, WriteFooter::No); /// /// let expected_bytes = [ /// 0x01, 0x98, // frame control /// 0x00, // sequence number /// 0x34, 0x12, 0x78, 0x56, // PAN identifier and address of destination /// 0x34, 0x12, 0xbc, 0x9a, // PAN identifier and address of source /// 0xde, 0xf0, // payload /// 0x00, 0x00, // footer, not written /// ]; /// assert_eq!(bytes[..expected_bytes.len()], expected_bytes[..]); /// ``` /// /// [issue tracker]: https://github.com/braun-robotics/ieee-802.15.4/issues/9 pub fn encode(&self, buf: &mut [u8], write_footer: WriteFooter) -> usize { let mut len = 0; // Write header len += self.header.encode(&mut buf[len..]); // Write content len += self.content.encode(&mut buf[len..]); // Write payload buf[len .. len+self.payload.len()].copy_from_slice(self.payload); len += self.payload.len(); // Write footer match write_footer { WriteFooter::No => (), } len } } /// Tells [`Frame::encode`] whether to write the footer /// /// Eventually, this should support three options: /// - Don't write the footer /// - Calculate the 2-byte CRC checksum and write that as the footer /// - Write the footer as written into the `footer` field /// /// For now, only not writing the footer is supported. pub enum WriteFooter { /// Don't write the footer No, } /// MAC frame header #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub struct Header { /// Frame Type pub frame_type: FrameType, /// Auxiliary Security header pub security: Security, /// Frame Pending pub frame_pending: bool, /// Acknowledgement Request pub ack_request: bool, /// PAN ID Compress pub pan_id_compress: bool, /// Frame version pub version: FrameVersion, /// Destination Address pub destination: Address, /// Source Address pub source: Address, /// Sequence Number pub seq: u8, } impl Header { /// Decodes a header from a byte buffer /// /// This method is used by [`Frame::decode`] to decode the frame header. /// Unless you decide to write your own code for decoding frames, there /// should be no reason to call this method directly. /// /// # Errors /// /// This function returns an error, if the bytes either don't encode a valid /// IEEE 802.15.4 frame header, or encode a frame header that is not fully /// supported by this implementation. Please refer to [`DecodeError`] for /// details. /// /// # Example /// /// ``` rust /// use ieee802154::mac::{ /// Address, /// ShortAddress, /// FrameType, /// Header, /// PanId, /// Security, /// }; /// /// # fn main() -> Result<(), ::ieee802154::mac::DecodeError> { /// // Construct a simple header. /// let bytes = [ /// 0x01, 0x98, // frame control /// 0x00, // sequence number /// 0x12, 0x34, 0x56, 0x78, // PAN identifier and address of destination /// 0x12, 0x34, 0x9a, 0xbc, // PAN identifier and address of source /// ]; /// /// let (header, num_bytes) = Header::decode(&bytes)?; /// /// assert_eq!(num_bytes, bytes.len()); /// /// assert_eq!(header.seq, 0x00); /// assert_eq!(header.frame_type, FrameType::Data); /// assert_eq!(header.security, Security::None); /// assert_eq!(header.frame_pending, false); /// assert_eq!(header.ack_request, false); /// assert_eq!(header.pan_id_compress, false); /// /// assert_eq!( /// header.destination, /// Address::Short(PanId(0x3412), ShortAddress(0x7856)) /// ); /// assert_eq!( /// header.source, /// Address::Short(PanId(0x3412), ShortAddress(0xbc9a)) /// ); /// # /// # Ok(()) /// # } /// ``` pub fn decode(buf: &[u8]) -> Result<(Self, usize), DecodeError> { // First, make sure we have enough buffer for the Frame Control field if buf.len() < 2 { return Err(DecodeError::NotEnoughBytes); } let mut len = 0; let frame_type = (buf[0] >> 0) & 0x7; let security = (buf[0] >> 3) & 0x1; let frame_pending = (buf[0] >> 4) & 0x1; let ack_request = (buf[0] >> 5) & 0x1; let pan_id_compress = (buf[0] >> 6) & 0x1; let dest_addr_mode = (buf[1] >> 2) & 0x3; let frame_version = (buf[1] >> 4) & 0x3; let source_addr_mode = (buf[1] >> 6) & 0x3; let frame_type = FrameType::from_bits(frame_type) .ok_or(DecodeError::InvalidFrameType(frame_type))?; let security = Security::from_bits(security) .ok_or(DecodeError::SecurityNotSupported)?; let frame_pending = frame_pending == 0b1; let ack_request = ack_request == 0b1; let pan_id_compress = pan_id_compress == 0x01; let dest_addr_mode = AddressMode::from_bits(dest_addr_mode)?; let source_addr_mode = AddressMode::from_bits(source_addr_mode)?; if frame_version > 0b01 { return Err(DecodeError::InvalidFrameVersion(frame_version)); } let version = FrameVersion::from_bits(frame_version) .ok_or(DecodeError::InvalidFrameVersion(frame_version))?; len += 2; let seq = buf[len]; len += 1; let (destination, addr_len) = Address::decode(&buf[len..], &dest_addr_mode)?; len += addr_len; let source = if !pan_id_compress { let (source, addr_len) = Address::decode(&buf[len..], &source_addr_mode)?; len += addr_len; source } else { let pan_id = destination.pan_id() .ok_or(DecodeError::InvalidAddressMode(dest_addr_mode as u8))?; let (source, addr_len) = Address::decode_compress( &buf[len..], &source_addr_mode, pan_id, )?; len += addr_len; source }; let header = Header { frame_type, security, frame_pending, ack_request, pan_id_compress, version, destination, source, seq, }; Ok((header, len)) } /// Encodes the header into a buffer /// /// Returns the number of bytes written to the buffer. /// /// # Panics /// /// Panics, if the buffer is not long enough to hold the header. If you /// believe that this behavior is inappropriate, please leave your feedback /// on the [issue tracker]. Will also panic if the destination PAN /// identifier differs from the source PAN identifier when using PAN /// identifier compress. /// /// The header length depends on the options chosen and varies between 3 and /// 30 octets. /// /// # Example /// /// ``` rust /// use ieee802154::mac::{ /// Address, /// ShortAddress, /// FrameType, /// FrameVersion, /// Header, /// PanId, /// Security, /// }; /// /// let header = Header { /// seq: 0x00, /// frame_type: FrameType::Data, /// security: Security::None, /// frame_pending: false, /// ack_request: false, /// pan_id_compress: false, /// version: FrameVersion::Ieee802154_2006, /// /// destination: Address::Short(PanId(0x1234), ShortAddress(0x5678)), /// source: Address::Short(PanId(0x1234), ShortAddress(0x9abc)), /// }; /// /// let mut bytes = [0u8; 11]; /// /// header.encode(&mut bytes); /// /// let expected_bytes = [ /// 0x01, 0x98, // frame control /// 0x00, // sequence number /// 0x34, 0x12, 0x78, 0x56, // PAN identifier and address of destination /// 0x34, 0x12, 0xbc, 0x9a, // PAN identifier and address of source /// ]; /// assert_eq!(bytes[..expected_bytes.len()], expected_bytes[..]); /// ``` /// /// [issue tracker]: https://github.com/braun-robotics/ieee-802.15.4/issues/9 pub fn encode(&self, buf: &mut [u8]) -> usize { let frame_control = (self.frame_type as u16) << 0 | (self.security as u16) << 3 | (self.frame_pending as u16) << 4 | (self.ack_request as u16) << 5 | (self.pan_id_compress as u16) << 6 | (self.destination.address_mode() as u16) << 10 | (self.version as u16) << 12 | (self.source.address_mode() as u16) << 14; let mut len = 0; // Write Frame Control LittleEndian::write_u16(&mut buf[len..], frame_control); len += size_of_val(&frame_control); // Write Sequence Number buf[len] = self.seq; len += size_of_val(&self.seq); // Write addresses len += self.destination.encode(&mut buf[len..]); len += if self.pan_id_compress { assert_eq!(self.destination.pan_id(), self.source.pan_id()); self.source.encode_compress(&mut buf[len..]) } else { self.source.encode(&mut buf[len..]) }; len } } /// Defines the type of a MAC frame /// /// Part of [`Header`]. #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub enum FrameType { /// Beacon Beacon = 0b000, /// Data Data = 0b001, /// Acknowledgement Acknowledgement = 0b010, /// MAC command MacCommand = 0b011, } impl FrameType { /// Creates an instance of [`FrameType`] from the provided bits /// /// Returns `None`, if the provided bits don't encode a valid frame type. /// /// # Example /// /// ``` rust /// use ieee802154::mac::FrameType; /// /// let frame_type = FrameType::from_bits(0b001); /// assert_eq!(frame_type, Some(FrameType::Data)); /// ``` pub fn from_bits(bits: u8) -> Option<Self> { match bits { 0b000 => Some(FrameType::Beacon), 0b001 => Some(FrameType::Data), 0b010 => Some(FrameType::Acknowledgement), 0b011 => Some(FrameType::MacCommand), _ => None, } } } /// Defines whether an auxiliary security header is present in the MAC header /// /// Part of [`Header`]. Auxiliary security headers are currently unsupported by /// this implementation. #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub enum Security { /// No auxiliary security header is present None = 0b0, } impl Security { /// Creates an instance of [`Security`] from the provided bits /// /// Returns `None`, if the provided bits don't encode a valid value of /// `Security`. /// /// # Example /// /// ``` rust /// use ieee802154::mac::Security; /// /// let security = Security::from_bits(0b0); /// assert_eq!(security, Some(Security::None)); /// ``` pub fn from_bits(bits: u8) -> Option<Self> { match bits { 0b0 => Some(Security::None), _ => None, } } } /// Defines version information for a frame #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub enum FrameVersion { /// A frame conforming to the 802.15.4-2003 standard Ieee802154_2003 = 0b00, /// A frame conforming to the 802.15.4-2006 standard Ieee802154_2006 = 0b01, /// A frame conforming to the current 802.15.4 standard Ieee802154 = 0b10, } impl FrameVersion { /// Creates an instance of [`FrameVersion`] from the provided bits /// /// Returns `None`, if the provided bits don't encode a valid value of /// `FrameVersion`. /// /// # Example /// /// ``` rust /// use ieee802154::mac::FrameVersion; /// /// let version = FrameVersion::from_bits(0b0); /// assert_eq!(version, Some(FrameVersion::Ieee802154_2003)); /// ``` pub fn from_bits(bits: u8) -> Option<Self> { match bits { 0b00 => Some(FrameVersion::Ieee802154_2003), 0b01 => Some(FrameVersion::Ieee802154_2006), 0b10 => Some(FrameVersion::Ieee802154), _ => None, } } } /// Defines the type of Address #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub enum AddressMode { /// PAN identifier and address field are not present None = 0b00, /// Address field contains a 16 bit short address Short = 0b10, /// Address field contains a 64 bit extended address Extended = 0b11, } impl AddressMode { /// Creates an instance of [`AddressMode`] from the provided bits /// /// Returns `None`, if the provided bits don't encode a valid value of /// `AddressMode`. /// /// # Example /// /// ``` rust /// use ieee802154::mac::AddressMode; /// /// let address_mode = AddressMode::from_bits(0b10).unwrap(); /// assert_eq!(address_mode, AddressMode::Short); /// ``` pub fn from_bits(bits: u8) -> Result<Self, DecodeError> { match bits { 0b00 => Ok(AddressMode::None), 0b10 => Ok(AddressMode::Short), 0b11 => Ok(AddressMode::Extended), _ => Err(DecodeError::InvalidAddressMode(bits)), } } } /// Personal Area Network Identifier /// /// A 16-bit value that identifies a PAN #[derive(Clone, Copy, Debug, Eq, Hash, Hash32, PartialEq)] pub struct PanId(pub u16); impl PanId { /// Get the broadcast PAN identifier pub fn broadcast() -> Self { Self(0xffff) } /// Decodes an PAN identifier from a byte buffer /// /// # Errors /// /// This function returns an error, if there are not enough bytes in the /// buffer to encode a valid `Address` instance. /// /// # Example /// /// ``` rust /// use ieee802154::mac::PanId; /// /// # fn main() -> Result<(), ::ieee802154::mac::DecodeError> { /// let bytes = [0x56, 0x78]; /// let (address, num_bytes) = PanId::decode(&bytes)?; /// /// assert_eq!(num_bytes, bytes.len()); /// assert_eq!(address.0, 0x7856); /// # /// # Ok(()) /// # } /// ``` pub fn decode(buf: &[u8]) -> Result<(Self, usize), DecodeError> { if buf.len() < 2 { return Err(DecodeError::NotEnoughBytes); } let pan_id = LittleEndian::read_u16(buf); let len = size_of_val(&pan_id); Ok((PanId(pan_id), len)) } /// Encodes the PAN identifier into a buffer /// /// Returns the number of bytes written to the buffer. /// /// # Panics /// /// Panics, if the buffer is less than 2 bytes long. If you believe that /// this behavior is inappropriate, please leave your feedback on the /// [issue tracker]. /// /// # Example /// /// ``` rust /// use ieee802154::mac::PanId; /// /// let address = PanId(0x1234); /// /// let mut bytes = [0u8; 2]; /// address.encode(&mut bytes); /// /// let expected_bytes = [0x34, 0x12]; /// assert_eq!(bytes[..expected_bytes.len()], expected_bytes[..]); /// ``` /// /// [issue tracker]: https://github.com/braun-robotics/ieee-802.15.4/issues/9 pub fn encode(&self, buf: &mut [u8]) -> usize { LittleEndian::write_u16(buf, self.0); size_of_val(&self.0) } } /// A 16-bit short address /// /// Short address assigned to a device during association, used to identify the /// device in the PAN. #[derive(Clone, Copy, Debug, Eq, Hash, Hash32, PartialEq)] pub struct ShortAddress(pub u16); impl ShortAddress { /// Creates an instance of `Address` that presents the broadcast address pub fn broadcast() -> Self { ShortAddress(0xffff) } /// Decodes an address from a byte buffer /// /// This method is used by [`Header::decode`] to decode addresses. Unless /// you decide to write your own code for decoding headers, there should be /// no reason to call this method directly. /// /// # Errors /// /// This function returns an error, if there are not enough bytes in the /// buffer to encode a valid `Address` instance. /// /// # Example /// /// ``` rust /// use ieee802154::mac::ShortAddress; /// /// # fn main() -> Result<(), ::ieee802154::mac::DecodeError> { /// let bytes = [0x56, 0x78]; /// let (address, num_bytes) = ShortAddress::decode(&bytes)?; /// /// assert_eq!(num_bytes, bytes.len()); /// assert_eq!(address, ShortAddress(0x7856)); /// # /// # Ok(()) /// # } /// ``` pub fn decode(buf: &[u8]) -> Result<(Self, usize), DecodeError> { if buf.len() < 2 { return Err(DecodeError::NotEnoughBytes); } let addr = LittleEndian::read_u16(&buf); Ok((ShortAddress(addr), size_of_val(&addr))) } /// Encodes the address into a buffer /// /// Returns the number of bytes written to the buffer. /// /// # Panics /// /// Panics, if the buffer is less than 2 bytes long. If you believe that /// this behavior is inappropriate, please leave your feedback on the /// [issue tracker]. /// /// # Example /// /// ``` rust /// use ieee802154::mac::ShortAddress; /// /// let address = ShortAddress(0x5678); /// /// let mut bytes = [0u8; 2]; /// address.encode(&mut bytes); /// /// let expected_bytes = [0x78, 0x56]; /// assert_eq!(bytes[..expected_bytes.len()], expected_bytes[..]); /// ``` /// /// [issue tracker]: https://github.com/braun-robotics/ieee-802.15.4/issues/9 pub fn encode(&self, buf: &mut [u8]) -> usize { LittleEndian::write_u16(buf, self.0); size_of_val(&self.0) } } /// A 64-bit extended address /// /// A unique address that is used to identify an device in the PAN. #[derive(Clone, Copy, Debug, Eq, Hash, Hash32, PartialEq)] pub struct ExtendedAddress(pub u64); impl ExtendedAddress { /// Creates an instance of `Address` that presents the broadcast address pub fn broadcast() -> Self { ExtendedAddress(0xffffffffffffffffu64) } /// Decodes an address from a byte buffer pub fn decode(buf: &[u8]) -> Result<(Self, usize), DecodeError> { if buf.len() < 8 { return Err(DecodeError::NotEnoughBytes); } let addr = LittleEndian::read_u64(&buf); Ok((ExtendedAddress(addr), size_of_val(&addr))) } /// Encodes the address into a buffer pub fn encode(&self, buf: &mut [u8]) -> usize { LittleEndian::write_u64(buf, self.0); size_of_val(&self.0) } } /// An address that might contain an PAN ID and address #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub enum Address { /// No address None, /// Short (16-bit) address and PAN ID (16-bit) Short(PanId, ShortAddress), /// Extended (64-bit) address and PAN ID (16-bit) Extended(PanId, ExtendedAddress), } impl Address { /// Creates an instance of `Address` that represents the broadcast address pub fn broadcast(mode: &AddressMode) -> Self { match mode { AddressMode::None => Address::None, AddressMode::Short => Address::Short(PanId::broadcast(), ShortAddress::broadcast()), AddressMode::Extended => { Address::Extended(PanId::broadcast(), ExtendedAddress::broadcast()) } } } /// Decodes an address from a byte buffer pub fn decode(buf: &[u8], mode: &AddressMode) -> Result<(Self, usize), DecodeError> { let (address, len) = match mode { AddressMode::None => (Address::None, 0), AddressMode::Short => { let mut length = 0; let (i, l) = PanId::decode(buf)?; length += l; let (a, l) = ShortAddress::decode(&buf[l..])?; length += l; (Address::Short(i, a), length) } AddressMode::Extended => { let mut length = 0; let (i, l) = PanId::decode(buf)?; length += l; let (a, l) = ExtendedAddress::decode(&buf[l..])?; length += l; (Address::Extended(i, a), length) } }; Ok((address, len)) } /// Decodes an address from a byte buffer pub fn decode_compress( buf: &[u8], mode: &AddressMode, pan_id: PanId, ) -> Result<(Self, usize), DecodeError> { let (address, len) = match mode { AddressMode::None => (Address::None, 0), AddressMode::Short => { let (a, l) = ShortAddress::decode(buf)?; (Address::Short(pan_id, a), l) } AddressMode::Extended => { let (a, l) = ExtendedAddress::decode(buf)?; (Address::Extended(pan_id, a), l) } }; Ok((address, len)) } /// Encodes the address into a buffer pub fn encode(&self, buf: &mut [u8]) -> usize { match *self { Address::None => 0, Address::Short(i, a) => { let pan_id_size = i.encode(buf); let address_size = a.encode(&mut buf[pan_id_size..]); pan_id_size + address_size } Address::Extended(i, a) => { let pan_id_size = i.encode(buf); let address_size = a.encode(&mut buf[pan_id_size..]); pan_id_size + address_size } } } /// Encodes the address into a buffer pub fn encode_compress(&self, buf: &mut [u8]) -> usize { match *self { Address::None => 0, Address::Short(_, a) => a.encode(buf), Address::Extended(_, a) => a.encode(buf), } } /// Get the PAN ID for this address pub fn pan_id(&self) -> Option<PanId> { match *self { Address::None => None, Address::Short(pan_id, _) => Some(pan_id), Address::Extended(pan_id, _) => Some(pan_id), } } /// Get the address mode for this address pub fn address_mode(&self) -> AddressMode { match *self { Address::None => AddressMode::None, Address::Short(_, _) => AddressMode::Short, Address::Extended(_, _) => AddressMode::Extended, } } } /// Content of a frame #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub enum FrameContent { /// Beacon frame content Beacon(Beacon), /// Data frame Data, /// Acknowledgement frame Acknowledgement, /// MAC command frame Command(Command), } impl FrameContent { /// Decode frame content from byte buffer pub fn decode(buf: &[u8], header: &Header) -> Result<(Self, usize), DecodeError> { match header.frame_type { FrameType::Beacon => { let (beacon, used) = Beacon::decode(buf)?; Ok((FrameContent::Beacon(beacon), used)) } FrameType::Data => { Ok((FrameContent::Data, 0)) } FrameType::Acknowledgement => { Ok((FrameContent::Acknowledgement, 0)) } FrameType::MacCommand => { let (command, used) = Command::decode(buf)?; Ok((FrameContent::Command(command), used)) } } } /// Encode frame content into byte buffer pub fn encode(&self, buf: &mut [u8]) -> usize { match self { FrameContent::Beacon(beacon) => { beacon.encode(buf) } FrameContent::Data | FrameContent::Acknowledgement => { 0 } FrameContent::Command(command) => { command.encode(buf) } } } } /// Signals an error that occured while decoding bytes #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub enum DecodeError { /// Buffer does not contain enough bytes NotEnoughBytes, /// The frame type is invalid InvalidFrameType(u8), /// The frame has the security bit set, which is not supported SecurityNotSupported, /// The frame's address mode is invalid InvalidAddressMode(u8), /// The frame's version is invalid or not supported InvalidFrameVersion(u8), /// The data stream contains an invalid value InvalidValue } #[cfg(test)] mod tests { use super::*; use crate::mac::beacon; use crate::mac::command; #[test] fn decode_ver0_pan_id_compression() { let data = [ 0x41, 0x88, 0x91, 0x8f, 0x20, 0xff, 0xff, 0x33, 0x44, 0x00, 0x00, ]; let frame = Frame::decode(&data, true).unwrap(); assert_eq!(frame.header.frame_type, FrameType::Data); assert_eq!(frame.header.security, Security::None); assert_eq!(frame.header.frame_pending, false); assert_eq!(frame.header.ack_request, false); assert_eq!(frame.header.pan_id_compress, true); assert_eq!(frame.header.version, FrameVersion::Ieee802154_2003); assert_eq!( frame.header.destination, Address::Short(PanId(0x208f), ShortAddress(0xffff)) ); assert_eq!( frame.header.source, Address::Short(PanId(0x208f), ShortAddress(0x4433)) ); assert_eq!(frame.header.seq, 145); } #[test] fn decode_ver0_pan_id_compression_bad() { let data = [ 0x41, 0x80, 0x91, 0x8f, 0x20, 0xff, 0xff, 0x33, 0x44, 0x00, 0x00, ]; let frame = Frame::decode(&data, true); assert!(frame.is_err()); if let Err(e) = frame { assert_eq!(e, DecodeError::InvalidAddressMode(0)) } } #[test] fn decode_ver0_extended() { let data = [ 0x21, 0xc8, 0x8b, 0xff, 0xff, 0x02, 0x00, 0x23, 0x00, 0x60, 0xe2, 0x16, 0x21, 0x1c, 0x4a, 0xc2, 0xae, 0xaa, 0xbb, 0xcc, ]; let frame = Frame::decode(&data, true).unwrap(); assert_eq!(frame.header.frame_type, FrameType::Data); assert_eq!(frame.header.security, Security::None); assert_eq!(frame.header.frame_pending, false); assert_eq!(frame.header.ack_request, true); assert_eq!(frame.header.pan_id_compress, false); assert_eq!(frame.header.version, FrameVersion::Ieee802154_2003); assert_eq!( frame.header.destination, Address::Short(PanId(0xffff), ShortAddress(0x0002)) ); assert_eq!( frame.header.source, Address::Extended(PanId(0x0023), ExtendedAddress(0xaec24a1c2116e260)) ); assert_eq!(frame.header.seq, 139); } #[test] fn encode_ver0_short() { let frame = Frame { header: Header { frame_type: FrameType::Data, security: Security::None, frame_pending: false, ack_request: false, pan_id_compress: false, version: FrameVersion::Ieee802154_2003, destination: Address::Short(PanId(0x1234), ShortAddress(0x5678)), source: Address::Short(PanId(0x4321), ShortAddress(0x9abc)), seq: 0x01, }, content: FrameContent::Data, payload: &[0xde, 0xf0], footer: [0x00, 0x00], }; let mut buf = [0u8; 32]; let size = frame.encode(&mut buf, WriteFooter::No); assert_eq!(size, 13); assert_eq!( buf[..size], [0x01, 0x88, 0x01, 0x34, 0x12, 0x78, 0x56, 0x21, 0x43, 0xbc, 0x9a, 0xde, 0xf0] ); } #[test] fn encode_ver1_extended() { let frame = Frame { header: Header { frame_type: FrameType::Beacon, security: Security::None, frame_pending: true, ack_request: false, pan_id_compress: false, version: FrameVersion::Ieee802154_2006, destination: Address::Extended(PanId(0x1234), ExtendedAddress(0x1122334455667788)), source: Address::Short(PanId(0x4321), ShortAddress(0x9abc)), seq: 0xff, }, content: FrameContent::Beacon( beacon::Beacon { superframe_spec: beacon::SuperframeSpecification { beacon_order: beacon::BeaconOrder::OnDemand, superframe_order: beacon::SuperframeOrder::Inactive, final_cap_slot: 15, battery_life_extension: false, pan_coordinator: false, association_permit: false, }, guaranteed_time_slot_info: beacon::GuaranteedTimeSlotInformation::new(), pending_address: beacon::PendingAddress::new(), } ), payload: &[0xde, 0xf0], footer: [0x00, 0x00], }; let mut buf = [0u8; 32]; let size = frame.encode(&mut buf, WriteFooter::No); assert_eq!(size, 23); assert_eq!( buf[..size], [ 0x10, 0x9c, 0xff, 0x34, 0x12, 0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11, 0x21, 0x43, 0xbc, 0x9a, 0xff, 0x0f, 0x00, 0x00, 0xde, 0xf0 ] ); } #[test] fn encode_ver0_pan_compress() { let frame = Frame { header: Header { frame_type: FrameType::Acknowledgement, security: Security::None, frame_pending: false, ack_request: false, pan_id_compress: true, version: FrameVersion::Ieee802154_2003, destination: Address::Extended(PanId(0x1234), ExtendedAddress(0x1122334455667788)), source: Address::Short(PanId(0x1234), ShortAddress(0x9abc)), seq: 0xff, }, content: FrameContent::Acknowledgement, payload: &[], footer: [0x00, 0x00], }; let mut buf = [0u8; 32]; let size = frame.encode(&mut buf, WriteFooter::No); assert_eq!(size, 15); assert_eq!( buf[..size], [ 0x42, 0x8c, 0xff, 0x34, 0x12, 0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11, 0xbc, 0x9a ] ); } #[test] fn encode_ver2_none() { let frame = Frame { header: Header { frame_type: FrameType::MacCommand, security: Security::None, frame_pending: false, ack_request: true, pan_id_compress: false, version: FrameVersion::Ieee802154, destination: Address::None, source: Address::Short(PanId(0x1234), ShortAddress(0x9abc)), seq: 0xff, }, content: FrameContent::Command(command::Command::DataRequest), payload: &[], footer: [0x00, 0x00], }; let mut buf = [0u8; 32]; let size = frame.encode(&mut buf, WriteFooter::No); assert_eq!(size, 8); assert_eq!( buf[..size], [0x23, 0xa0, 0xff, 0x34, 0x12, 0xbc, 0x9a, 0x04] ); } }