// This file was modified as part of a University of St Andrews Computer Science BSC Senior Honours Dissertation Project.
//! # use sacn::packet::{AcnRootLayerProtocol, E131RootLayer, E131RootLayerData, DataPacketFramingLayer, DataPacketDmpLayer};
/// The core crate is used for string processing during packet parsing/packing as well as to provide access to the Hash trait.
/// The uuid crate is used for working with/generating UUIDs which sACN uses as part of the cid field in the protocol.
/// The universe used for universe discovery as defined in ANSI E1.31-2018 Appendix A: Defined Parameters (Normative)
/// The default priority used for the E1.31 packet priority field, as per ANSI E1.31-2018 Section 4.1 Table 4-1
/// Value of the highest byte of the IPV4 multicast address as specified in section 9.3.1 of ANSI E1.31-2018.
/// Value of the second highest byte of the IPV4 multicast address as specified in section 9.3.1 of ANSI E1.31-2018.
/// The maximum universe number that can be used with the E1.31 protocol as specified in section 9.1.1 of ANSI E1.31-2018.
/// The lowest / minimum universe number that can be used with the E1.31 protocol as specified in section 9.1.1 of ANSI E1.31-2018.
/// The synchronisation address used to indicate that there is no synchronisation required for the data packet.
/// The DMX512-A Null START Code, the first property value of a data packet carrying ordinary dimmer levels.
/// The interval between universe discovery packets (adverts) as defined by ANSI E1.31-2018 Appendix A.
/// The exclusive lower bound on the different between the received and expected sequence numbers within which a
/// packet will be discarded. Outside of the range specified by (`E131_SEQ_DIFF_DISCARD_LOWER_BOUND`, `E131_SEQ_DIFF_DISCARD_UPPER_BOUND`]
/// The inclusive upper bound on the different between the received and expected sequence numbers within which a
/// packet will be discarded. Outside of the range specified by (`E131_SEQ_DIFF_DISCARD_LOWER_BOUND`, `E131_SEQ_DIFF_DISCARD_UPPER_BOUND`]
/// The bit mask used to get the stream-termination option within the packet option field as per
/// The bit mask used to get the force-synchronisation option within the packet option field as per
/// The minimum allowed length of the discovery layer of an ANSI E1.31-2018 universe discovery packet.
/// The maximum allowed length of the discovery layer of an ANSI E1.31-2018 universe discovery packet.
/// The pdu flags expected for an ANSI E1.31-2018 packet as per ANSI E1.31-2018 Section 4 Table 4-1, 4-2, 4-3.
/// The length in bytes of the root layer vector field as per ANSI E1.31-2018 Section 4 Table 4-1, 4-2, 4-3.
/// The length in bytes of the E1.31 framing layer vector field as per ANSI E1.31-2018 Section 4 Table 4-1, 4-2, 4-3.
/// The length in bytes of the priority field within an ANSI E1.31-2018 data packet as defined in ANSI E1.31-2018 Section 4, Table 4-1.
/// The length in bytes of the sequence number field within an ANSI E1.31-2018 packet as defined in ANSI E1.31-2018 Section 4, Table 4-1, 4-2.
/// The length in bytes of the options field within an ANSI E1.31-2018 data packet as defined in ANSI E1.31-2018 Section 4, Table 4-1.
/// The length in bytes of a universe field within an ANSI E1.31-2018 packet as defined in ANSI E1.31-2018 Section 4, Table 4-1, 4-3.
/// The length in bytes of the Vector field within the DMP layer of an ANSI E1.31-2018 data packet as per ANSI E1.31-2018
/// The length in bytes of the "Address Type and Data Type" field within an ANSI E1.31-2018 data packet DMP layer as per
/// The length in bytes of the "First Property Address" field within an ANSI E1.31-2018 data packet DMP layer as per
/// The length in bytes of the "Address Increment" field within an ANSI E1.31-2018 data packet DMP layer as per
/// The length in bytes of the "Property value count" field within an ANSI E1.31-2018 data packet DMP layer as per
/// The length in bytes of the Vector field in the Universe Discovery Layer of an ANSI E1.31-2018 Universe Discovery Packet.
/// The length in bytes of the Page field in the Universe Discovery Layer of an ANSI E1.31-2018 Universe Discovery Packet.
/// The length in bytes of the Last Page field in the Universe Discovery Layer of an ANSI E1.31-2018 Universe Discovery Packet.
/// The value of the "Address Type and Data Type" field within an ANSI E1.31-2018 data packet DMP layer as per ANSI E1.31-2018
/// The value of the "First Property Address" field within an ANSI E1.31-2018 data packet DMP layer as per ANSI E1.31-2018
/// The value of the "Address Increment" field within an ANSI E1.31-2018 data packet DMP layer as per ANSI E1.31-2018
/// The size of the ACN root layer preamble, must be 0x0010 bytes as per ANSI E1.31-2018 Section 5.1.
/// Often treated as a usize for comparison or use with arrays however stored as u16 as this represents its field size
/// within a packet and converting u16 -> usize is always safe as len(usize) is always greater than len(u16), usize -> u16 is unsafe.
/// The size of the ACN root layer postamble, must be 0x0 bytes as per ANSI E1.31-2018 Section 5.2.
/// The E131 ACN packet identifier field value. Must be 0x41 0x53 0x43 0x2d 0x45 0x31 0x2e 0x31 0x37 0x00 0x00 0x00 as per
// The exclusive end index of the CID field. Calculated based on previous values defined in ANSI E1.31-2018 Section 4 Table 4-1, 4-2, 4-3.
/// The length of the Source Name field in bytes in an ANSI E1.31-2018 packet as per ANSI E1.31-2018 Section 4, Table 4-1, 4-2, 4-3.
/// The source name field is 64 bytes and must be null-terminated, which leaves 63 bytes for the name itself.
/// The length of the Synchronisation Address field in bytes in an ANSI E1.31-2018 packet as per ANSI E1.31-2018 Section 4, Table 4-1, 4-2, 4-3.
/// The length in bytes of the sequence number field within the framing layer of an E1.31 synchronisation packet.
/// The length in bytes of the reserved field within the framing layer of an E1.31 synchronisation packet.
// The length in bytes of the reserve field in the universe discovery framing layer of an ANSI E1.31-2018 Universe Discovery Packet.
/// The vector field value used to identify the packet as an ANSI E1.31 universe discovery or synchronisation packet.
/// The E1.31 packet vector field value used to identify the E1.31 packet as a synchronisation packet.
/// This is used at the E1.31 layer and shouldn't be confused with the VECTOR values used for the ACN layer (i.e. `VECTOR_ROOT_E131_DATA` and `VECTOR_ROOT_E131_EXTENDED`).
/// The E1.31 packet vector field value used to identify the E1.31 packet as a universe discovery packet.
/// This is used at the E1.31 layer and shouldn't be confused with the VECTOR values used for the ACN layer (i.e. `VECTOR_ROOT_E131_DATA` and `VECTOR_ROOT_E131_EXTENDED`).
/// This VECTOR value is shared by E1.31 data packets, distinguished by the value of the ACN `ROOT_VECTOR`.
/// This is used at the E1.31 layer and shouldn't be confused with the VECTOR values used for the ACN layer (i.e. `VECTOR_ROOT_E131_DATA` and `VECTOR_ROOT_E131_EXTENDED`).
/// This VECTOR value is shared by E1.31 universe discovery packets, distinguished by the value of the ACN `ROOT_VECTOR`.
/// Used at the DMP layer in E1.31 data packets to identify the packet as a set property message.
/// Used at the universe discovery packet universe discovery layer to identify the packet as a universe discovery list of universes.
/// The payload capacity for a sacn packet, for DMX data this would translate to 512 frames + a startcode byte.
/// The synchronisation universe/address of packets which do not require synchronisation as specified in section 6.2.4.1 of ANSI E1.31-2018.
/// The timeout before data loss is assumed for an E131 source, as defined in Appendix A of ANSI E1.31-2018.
/// Sources send universe discovery packets every `E131_UNIVERSE_DISCOVERY_INTERVAL` (10 seconds, ANSI E1.31-2016 Appendix A),
/// so this must be longer than that interval or discovered sources expire between adverts. The standard doesn't define a
/// receiver timeout, so two intervals are used: a source is only treated as lost after missing a whole advert.
/// Converts the given ANSI E1.31-2018 universe into an Ipv4 multicast address with the port set to the acn multicast port as defined
/// `IllegalUniverse`: Returned if the given universe is outwith the allowed range of universes,
/// Converts the given ANSI E1.31-2018 universe into an Ipv6 multicast address with the port set to the acn multicast port as defined
/// `IllegalUniverse`: Returned if the given universe is outwith the allowed range of universes,
/// Checks if the given universe is a valid universe to send on or listen to (within allowed range).
/// As per ANSI E1.31-2016 Section 6.2.7 data universes are limited to the range 1 to 63999, so unlike
/// [`is_universe_in_range`] this excludes `E131_DISCOVERY_UNIVERSE` (64214), which is reserved for universe discovery.
/// `IllegalUniverse`: Returned if the universe is outwith [`E131_MIN_MULTICAST_UNIVERSE`, `E131_MAX_MULTICAST_UNIVERSE`].
/// `SourceNameNotNullTerminated`: Returned if the source name is not null terminated as required by ANSI E1.31-2018 Section 6.2.2
/// Represents the data contained with the `PduInfo` section that appears at the start of a layer in an sACN packet.
/// Takes the given byte buffer and parses the flags, length and vector fields into a `PduInfo` struct.
/// `ParseInsufficientData`: If the length of the buffer is less than the flag, length and vector fields (`E131_PDU_LENGTH_FLAGS_LENGTH` + `vector_length`).
/// `ParsePduInvalidFlags`: If the flags parsed don't match the flags expected for an ANSI E1.31-2018 packet as per ANSI E1.31-2018 Section 4 Table 4-1, 4-2, 4-3.
let length = (NetworkEndian::read_u16(&buf[0..E131_PDU_LENGTH_FLAGS_LENGTH]) & 0x0fff) as usize;
// Calculate the indexes of the fields within the buffer based on the size of the fields previous.
// Constants are replaced inline so this increases readability by removing magic numbers without affecting runtime performance.
// Theses indexes are only valid within the scope of this part of the protocol (DataPacketFramingLayer).
const SOURCE_NAME_INDEX: usize = E131_PDU_LENGTH_FLAGS_LENGTH + E131_FRAMING_LAYER_VECTOR_LENGTH;
return Err(SacnError::SacnParsePackError(ParsePacketError::ParseInsufficientData("Buffer contains insufficient data based on data packet framing layer pdu length field".to_string())));
let synchronization_address = NetworkEndian::read_u16(&buf[SYNC_ADDR_INDEX..SEQ_NUM_INDEX]);
// Source Name, padded with 0's up to the required 64 byte length, always leaving room for the null terminator.
// Options, zero out all the bits to start including bits 0-4 as per ANSI E1.31-2018 Section 6.2.6.
// Calculate the indexes of the fields within the buffer based on the size of the fields previous.
// Constants are replaced inline so this increases readability by removing magic numbers without affecting runtime performance.
// Theses indexes are only valid within the scope of this part of the protocol (DataPacketDmpLayer).
PROPERTY_VALUE_COUNT_FIELD_INDEX + E131_DATA_PACKET_DMP_LAYER_PROPERTY_VALUE_COUNT_FIELD_LENGTH;
return Err(SacnError::SacnParsePackError(ParsePacketError::ParseInsufficientData("Buffer contains insufficient data based on data packet dmp layer pdu length field".to_string())));
if NetworkEndian::read_u16(&buf[FIRST_PRIORITY_FIELD_INDEX..ADDRESS_INCREMENT_FIELD_INDEX])
// Check that the property value count matches the expected count based on the pdu length given previously.
format!("Invalid data packet dmp layer property value count, pdu length indicates {} property values, property value count field indicates {} property values",
// The property value length is only of the property values and not the headers so start counting at the index that the property values start.
buf[PROPERTY_VALUES_FIELD_INDEX..PROPERTY_VALUES_FIELD_INDEX + self.property_values.len()]
// Calculate the indexes of the fields within the buffer based on the size of the fields previous.
// Constants are replaced inline so this increases readability by removing magic numbers without affecting runtime performance.
// Theses indexes are only valid within the scope of this part of the protocol (SynchronisationPacketFramingLayer).
return Err(SacnError::SacnParsePackError(ParsePacketError::ParseInsufficientData("Buffer contains insufficient data based on synchronisation packet framing layer pdu length field".to_string())));
// Reserved fields (2 bytes right immediately after the synchronisation address) should be ignored by receivers as per
// Calculate the indexes of the fields within the buffer based on the size of the fields previous.
// Constants are replaced inline so this increases readability by removing magic numbers without affecting runtime performance.
// Theses indexes are only valid within the scope of this part of the protocol (UniverseDiscoveryPacketFramingLayer).
return Err(SacnError::SacnParsePackError(ParsePacketError::ParseInsufficientData("Buffer contains insufficient data based on universe discovery packet framing layer pdu length field".to_string())));
// Calculate the indexes of the fields within the buffer based on the size of the fields previous.
// Constants are replaced inline so this increases readability by removing magic numbers without affecting runtime performance.
// Theses indexes are only valid within the scope of this part of the protocol (UniverseDiscoveryPacketUniverseDiscoveryLayer).
format!("Buffer contains incorrect amount of data ({} bytes) based on universe discovery packet universe discovery layer pdu length field ({} bytes)"
// The number of universes, calculated by dividing the remaining space in the packet by the size of a single universe.
/// Takes the given buffer representing the "List of Universe" field in an ANSI E1.31-2018 discovery packet and parses it into the universe values.
/// This enforces the requirement from ANSI E1.31-2018 Section 8.5 that the universes must be numerically sorted.
/// `ParseInvalidUniverseOrder`: If the universes are not sorted in ascending order with no duplicates.
/// `ParseInsufficientData`: If the buffer doesn't contain sufficient bytes and so cannot be parsed into the specified number of u16 universes.
// Last_universe starts as a placeholder value that is guaranteed to be less than the lowest possible advertised universe.
// Cannot use 0 even though under ANSI E1.31-2018 it cannot be used for data or as a sync_address as it is reserved for future use
/// The `universe_to` tests below check that the conversion from a universe to an IPv6 or IPv4 multicast address is done as
/// per ANSI E1.31-2018 Section 9.3.1 Table 9-10 (IPv4) and ANSI E1.31-2018 Section 9.3.2 Table 9-11 + Table 9-12.
/// Verifies that the parameters are set correctly as per ANSI E1.31-2018 Appendix A: Defined Parameters (Normative).
/// This test is particularly useful at the maintenance stage as it will flag up if any protocol defined constant is changed.