// This file was created as part of a University of St Andrews Computer Science BSC Senior Honours Dissertation Project.
// Report point: There is no guarantees made by the protocol that different sources will have different names.
// As names are used to match universe discovery packets this means that if 2 sources have the same name it won't
// Report point: partially discovered sources are only marked as discovered when a full set of discovery packets has been
// received, if a discovery packet is received but there are more pages the source won't be discovered until all the pages are received.
// If a page is lost this therefore means the source update / discovery in its entirety will be lost - implementation detail.
/// Mass import as a very large amount of packet is used here (upwards of 20 items) and this is much cleaner.
/// The uuid crate is used for working with/generating UUIDs which sACN uses as part of the cid field in the protocol.
/// The libc constants required are not available on many windows environments and therefore are hard-coded.
/// Defined as per <https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-socket>
/// Defined as per <https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-socket>
/// 1143 bytes is biggest packet required as per Section 8 of ANSI E1.31-2018, aligned to 64 bit that is 1144 bytes.
/// Defaults to false based on the assumption that often receivers won't have any immediate response/checks to do on a source
/// announcing itself (every source does this approximately every 10 seconds as per the `E131_DISCOVERY_INTERVAL`).
/// Defaults to false based on the assumption that often receivers will want to ignore termination from a source based on there
/// If a packet for a universe is waiting to be synchronised and then another packet is received with the same universe and synchronisation address
/// this situation must be handled. By default the implementation discards the lowest priority packet and if equal priority it discards the oldest
/// This can be changed by providing a new function to handle the situation of the user implementing a custom merge/arbitration algorithm as per
/// The actual universe data, if less than 512 values in length then implies trailing 0's to pad to a full-universe of data.
/// The universe the data is (or was if now acted upon) waiting for a synchronisation packet from.
/// The priority of the data, this may be useful for receivers which want to implement their own implementing merge algorithms.
/// The unique id of the source of the data, this may be useful for receivers which want to implement their own merge algorithms
/// A value of None indicates that there is no clear source, for example if a merge algorithm has merged data from 2 or more sources together.
/// Indicates if the data is marked as 'preview' data indicating it is for use by visualisers etc. as per ANSI E1.31-2018 Section 6.2.6.
/// // Example showing creation of a receiver and receiving some data, as there is no sender this receiver then handles the timeout.
/// const TIMEOUT: Option<Duration> = Some(Duration::from_secs(1)); // A timeout of None means blocking behaviour, some indicates the actual timeout.
/// The `SacnNetworkReceiver` used for handling communication with UDP / Network / Transport layer.
/// Key is the data universe and the start code (the first property value). A receiver may not have more than one packet
/// waiting per `data_universe` and start code, so that e.g. level data (start code 0x00) and per-address priority data
/// (start code 0xDD) held for the same synchronisation are both released rather than one replacing the other.
/// `Data_universe` used as key as oppose to sync universe because multiple packets might be waiting on the same sync universe
/// and adding data by data universe is at least as common as retrieving data by sync address because in a normal setup
/// The merge function used by this receiver if `DMXData` for the same universe and synchronisation universe is received while there
/// Sacn sources that have been partially discovered by only some of their universes being discovered so far with more pages to go.
/// A new source after this limit will cause a `SourcesExceededError` as per ANSI E1.31-2018 Section 6.2.3.3.
/// The sequence numbers being tracked by this receiver for each packet type, source and universe.
/// Returned data contains a flag to indicate if it is `preview_data` which can be used by the implementer to use/discard as required.
/// Flag which indicates if a `SourceDiscovered` error should be thrown when receiving data and a source is discovered.
/// Flag which indicates if a `StreamTerminated` error should be thrown if a receiver receives a stream terminated packet.
/// Flag which indicates if an `UniverseTimeout` error should be thrown if it is detected that a source has timed out.
/// Synchronisation universes that received data packets have named, with the time each was last named.
/// The receiver joins the multicast group of each so that it receives their synchronisation packets, without adding
/// them to `universes`: data sent on a synchronisation universe is only passed up if the user listens to it. Entries
/// that haven't been named for `E131_NETWORK_DATA_LOSS_TIMEOUT` are removed and their group left, unless the user
/// Used to tell if synchronisation on an address has been lost, as per ANSI E1.31-2016 Section 11.1.2.
/// Represents an sACN source/sender on the network that has been discovered by this sACN receiver by receiving universe discovery packets.
/// The name of the source, no protocol guarantee this will be unique but if it isn't then universe discovery may not work correctly.
/// The time at which the discovered source was last updated / a discovery packet was received by the source.
/// The pages that have been sent so far by this source when enumerating the universes it is currently sending on.
/// This flag is set when the receiver is created as not all environments currently support IP multicast.
/// Universe discovery packets are broken down into pages to allow sending a large list of universes, each page contains a list of universes and
/// which page it is. The receiver then puts the pages together to get the complete list of universes that the discovered source is sending on.
/// The concept of pages is intentionally hidden from the end-user of the library as they are a way of fragmenting large discovery
/// universe lists so that they can work over the network and don't play any part out-side of the protocol.
/// The universes that the source is transmitting that are on this page, this may or may-not be a complete list of all universes being sent
/// `SacnReceiverInternal` is used for actually receiving the sACN data but is wrapped in `SacnReceiver` to allow the update thread to handle
/// By default for an IPv6 address this will only receive IPv6 data but IPv4 can also be enabled by calling `set_ipv6_only(false)`.
/// IPv6 multicast is unsupported on Windows in Rust. This is due to the underlying library (Socket2) not providing support.
/// Since `UniverseDiscovery` is primarily based around multicast to receive the `UniverseDiscovery` packets this mechanism is expected
/// to have limited usage when running in an Ipv6 Windows environment. The `is_multicast_enabled` method can be used to see if multicast
/// ip: The address of the interface for this receiver to join, by default this address should use the `ACN_SDT_MULTICAST_PORT` as defined in
/// ANSI E1.31-2018 Appendix A: Defined Parameters (Normative) however another address might be used in some situations.
/// `source_limit`: The limit to the number of sources, past this limit a new source will cause a `SourcesExceededError` as per ANSI E1.31-2018 Section 6.2.3.3.
/// Will return an `InvalidInput` error if the `source_limit` has a value of Some(0) which would indicate this receiver can never receive from any source.
/// Will return an error if the created `SacnReceiver` fails to listen to the `E1.31_DISCOVERY_UNIVERSE`.
/// This method does not attempt to leave multicast groups already joined through previous `listen_universe` calls.
/// Will return an `OsOperationUnsupported` error if attempting to set the flag to true in an environment that multicast
/// This flag is set when the receiver is created as not all environments currently support IP multicast.
/// If you want to wipe data awaiting synchronisation then see [`clear_all_waiting_data`](Self::clear_all_waiting_data).
/// Deletes all data currently waiting to be passed up - e.g. waiting for a synchronisation packet.
/// This allows clearing all data awaiting synchronisation but without forgetting sequence numbers. To wipe sequence numbers
/// To clear only a specific universe of waiting data see [`clear_waiting_data`](Self::clear_waiting_data).
/// Clears data (if any) waiting to be passed up for the specific universe, whatever its start code.
/// Returns true if data was removed and false if there wasn't any data to remove for this universe.
/// This merge function is called if data is waiting for a universe e.g. for synchronisation and then further data for that universe with the same
/// This merge function MUST return a `DmxMergeError` if there is a problem merging. This error can optionally encapsulate further errors using the Error-chain system
/// func: The merge function to use. Should take 2 `DMXData` references as arguments and return a `Result<DMXData>`.
pub fn set_merge_fn(&mut self, func: fn(&DMXData, &DMXData) -> Result<DMXData>) -> Result<()> {
/// Allows receiving from the given universe and starts listening to the multicast addresses which corresponds to the given universe.
/// Note that if the `is_multicast_enabled` flag is set to false then this method will only register the universe to listen to and won't
/// If 1 or more universes in the list are already being listened to this method will have no effect for those universes only.
/// Returns an `SacnError::IllegalUniverse` error if the given universe is outwith the allowed range of universes,
/// Returns an `SacnError::IllegalUniverse` error if the given universe is outwith the allowed range of universes,
// Still needed for synchronisation packets; the group is left once it is no longer used for that.
/// This flag indicates if this receiver should process packets marked as `preview_data` or should ignore them.
/// A receiver is 'listening' to a universe if it allows that universe to be received without filtering it out.
/// This does not mean that the multicast address for that universe is or isn't being listened to.
/// Any data returned will be ready to act on immediately i.e. waiting e.g. for universe synchronisation
/// This method will return a `WouldBlock` (unix) or `TimedOut` (windows) error if there is no data ready within the given timeout.
/// A timeout of duration 0 will do timeout checks but otherwise will return a WouldBlock/TimedOut error without checking for data.
/// Will return `SacnError::SourceDiscovered` error if the `announce_source_discovery` flag is set and a universe discovery
/// packet is received and a source fully discovered. This happens once when the source is first discovered, and again
/// Will return a `UniverseNotRegistered` error if this method is called with an infinite timeout, no
/// registered data universes and the `announce_discovered_sources` flag set to off. This is to protect the user from
/// The method may also return an error if there is an issue setting a timeout on the receiver. See
/// The method may also return an error if there is an issue handling the data as either a Data, Synchronisation or Discovery packet.
/// See the `SacnReceiver::handle_data_packet`, `SacnReceiver::handle_sync_packet` and `SacnReceiver::handle_universe_discovery_packet` methods
/// If the `announce_timeout` flag is set then the recv will return a `UniverseTimeout` error if a source fails to send on a universe within the timeout
/// specified by `E131_NETWORK_DATA_LOSS_TIMEOUT` (ANSI E1.31-2018 Appendix A). This may not be detected immediately unless data is received for the timed-out
/// universe from the source. If it isn't detected immediately it will be detected within an interval of `E131_NETWORK_DATA_LOSS_TIMEOUT` (assuming code
// This means that having no timeout may lead to no data ever being received and so this method blocking forever
// Forces the actual timeout used for receiving from the underlying network to never exceed E131_NETWORK_DATA_LOSS_TIMEOUT.
// This means that the timeouts for the sequence numbers will be checked at least every E131_NETWORK_DATA_LOSS_TIMEOUT even if
self.receiver.set_timeout(Some(actual_timeout))?; // "Failed to set a timeout value for the receiver"
// Zero out the buffer before receiving. This may be redundant since recv should pack the whole buffer.
"Received sACN data packet from {}: universe {}, sequence {}, priority {}, sync address {}, {} bytes",
/// See [`set_announce_source_discovery`](Self::set_announce_source_discovery) for an explanation of the flag.
/// As the sources may be timed out `get_discovered_sources` is the preferred method but this is included
/// to allow receivers to disable universe discovery source timeouts which may be useful in very high latency networks.
/// Returns a list of the sources that have been discovered on the network by this receiver through the E1.31 universe discovery mechanism.
/// By default this flag is false which indicates that when receiving data discovered sources through universe discovery
/// won't be announced by the recv method and the receivers list of discovered universes will be updated silently.
/// If set to true then it means that a `SourceDiscovered` error will be thrown whenever a source is discovered through a
/// complete universe discovery packet. A source that keeps advertising the same universes is announced once, and again
/// By default this flag is false which means that if a universe for a source times out due to data not being sent then
/// If set to true then a `UniverseTimeout` error will be thrown when attempting to receive if it is detected that a source universe has
/// See [`set_announce_stream_termination`](Self::set_announce_stream_termination) for an explanation of the flag.
/// By default this flag is false. This indicates that if a source sends a stream termination packet it will be handled silently by the receiver.
/// If set to true then a `UniverseTermination` error will be thrown when attempting to receive if a termination packet is received as per
/// If the returned value is None it indicates that the data was received successfully but isn't ready to act on.
/// Returns an `OutOfSequence` error if a packet is received out of order as detected by the different between
/// the packets sequence number and the expected sequence number as specified in ANSI E1.31-2018 Section 6.7.2 Sequence Numbering.
/// Returns a `UniversesTerminated` error if a packet is received with the `stream_terminated` flag set indicating that the source is no longer
/// Will return an `DmxMergeError` if there is an issue merging or replacing new and existing waiting data.
// Termination is handled before the preview filter: as per ANSI E1.31-2016 Section 6.2.6 a packet with Stream_Terminated set
// ends the stream whatever its other options are, so a terminating source that also marks its data as preview still terminates.
// Only Null START Code data keeps a source alive. Sources must send Null START Code keep-alives at least every second
// (ANSI E1.31-2016 Section 6.6.2) while alternate START Codes such as 0xDD per-address priority carry no levels, so a
let null_start_code = data_pkt.data.property_values.first() == Some(&E131_NULL_START_CODE);
// As per ANSI E1.31-2016 Section 11.1.1 a receiver begins synchronising on receipt of the first synchronisation packet,
// so until one has been received on this packet's synchronisation address the data is processed immediately.
// Once synchronisation has started and is then lost, Section 6.2.6 and 11.1.2 apply: with the Force_Synchronization
// option set the data doesn't have to wait for a synchronisation packet, and without it the data is held until
// As per ANSI E1.31-2018 Appendix B.2 the receiver should listen at the synchronisation address when a data packet is received with a non-zero
/// Removes the given universe from the discovered sACN source with the given name, also stops tracking
/// Note this is just a record keeping operation, it doesn't actually effect the real sACN sender it
/// If the `src_cid/source_name/universe` isn't currently registered then this method has no effect.
/// This is intentional as it allows calling this function multiple times without worrying about failure because
/// E.g. when a source terminates it sends 3 termination packets but a receiver should only terminate once.
// Will only return an error if the source/universe wasn't found which is acceptable because as it
/// Note that a receiver will only store a single packet of data per `data_universe` and start code at once.
/// If there is waiting data for the same universe and start code as the data then it will be merged as per the
/// `merge_func` which by default keeps the highest priority data, if the data has the same priority
/// Will return an `DmxMergeError` if there is an issue merging or replacing new and existing waiting data.
/// E1.31 Synchronization Packets occur on specific universes. Upon receipt, they indicate that any data advertising that universe as its Synchronization Address must be acted upon.
/// In an E1.31 Data Packet, a value of 0 in the Synchronization Address indicates that the universe data is not synchronized. If a receiver is presented with an E1.31 Data Packet
/// containing a Synchronization Address of 0, it shall discard any data waiting to be processed and immediately act on that Data Packet.
/// If the Synchronization Address field is not 0, and the receiver is receiving an active synchronization stream for that Synchronization Address,
/// it shall hold that E1.31 Data Packet until the arrival of the appropriate E1.31 Synchronization Packet before acting on it.
/// Returns an `OutOfSequence` error if a packet is received out of order as detected by the different between
/// the packets sequence number and the expected sequence number as specified in ANSI E1.31-2018 Section 6.7.2 Sequence Numbering.
/// Retrieves and removes the DMX data of all waiting data with a synchronisation address matching the one provided.
// Get the universes (used as keys) to remove and then move the corresponding data out of the waiting data and into the result.
/// Returns true if the source is new, or if its name or universe list differs from the previous record. Sources
/// re-advertise every `E131_UNIVERSE_DISCOVERY_INTERVAL`, so an unchanged advert returns false.
/// This universe discovery packet might be the whole thing or may be just one page of a discovery packet.
/// This method puts the pages to produce the `DiscoveredSacnSource` which is stored in the receiver.
/// Returns the source name if a source was fully discovered and is either new or has changed its name or universe list
/// since its last advert. Returns None if the source was only partially discovered, or if the advert repeats what is
// See if some pages that belong to the source that this page belongs to have already been received.
// The source's universe list has changed size since the earlier pages were sent, so they are stale.
"Discarding {} sACN universe discovery pages from {cid}: its page count changed from {} to {last_page}",
// A page can arrive again in the next discovery interval, for example if another page was lost.
// Replace the earlier copy rather than storing it twice, which would stop has_all_pages() ever succeeding.
/// Records that a received data packet named `sync_uni` as its synchronisation address, joining that universe's
/// multicast group if it isn't joined already so that the synchronisation packets are received.
/// Returns an error if the multicast group cannot be joined. The universe isn't recorded in that case, so joining is
/// Stops tracking synchronisation universes that no data packet has named for `E131_NETWORK_DATA_LOSS_TIMEOUT`,
/// Returns true if a synchronisation packet has ever been received on the given synchronisation address, meaning
/// Returns true if a synchronisation packet has been received on the given synchronisation address within
/// `E131_NETWORK_DATA_LOSS_TIMEOUT`, meaning synchronisation on that address is active as per ANSI E1.31-2016 Section 11.1.
/// Goes through all the waiting data and removes any which has timed out as a sync-packet for it hasn't been received within the `E131_NETWORK_DATA_LOSS_TIMEOUT`
"Discarding sACN data held for universe {uni} (start code {start_code:#04x}): no sync packet arrived on sync address {}",
/// By implementing the Drop trait for `SacnNetworkReceiver` it means that the user doesn't have to explicitly clean up the receiver
// Leave the groups joined only for synchronisation first; mute_universe would otherwise skip them.
"sACN receiver failed to leave the multicast group of sync address {u} while being dropped: {e:?}"
// Cannot return an error or pass it onto the user because drop might be called during a panic.
// Notify using stdout might pollute the application using the library so would require a flag to enable/disable but the function of this
// A panic might be unnecessary or pollute another in-progress panic hiding the true problem. It would also prevent muting the other
// The error is therefore ignored as it can't be fixed eitherway as the SacnReceiver has gone out of scope and won't lead to memory un-safety.
/// Searches for the discovered source with the given name in the given vector of discovered sources and
/// Only the bytes actually received are parsed, so a truncated datagram is rejected by the length checks
/// in the parser rather than being padded out with whatever is left in the rest of the buffer.
/// In general the lower level transport layer is handled by `SacnNetworkReceiver` (which itself wraps a Socket).
/// If the given address is an IPv4 address then communication will only work between IPv4 devices, if the given address is IPv6 then communication
/// will only work between IPv6 devices by default but IPv4 receiving can be enabled using `set_ipv6_only(false)`.
/// Connects this `SacnNetworkReceiver` to the multicast address which corresponds to the given universe to allow receiving packets for that universe.
/// Will return an Error if the given universe cannot be converted to an Ipv4 or Ipv6 `multicast_addr` depending on if the Receiver is bound to an
/// IPv4 or IPv6 address. See `packet::universe_to_ipv4_multicast_addr` and `packet::universe_to_ipv6_multicast_addr`.
/// Will return an Io error if cannot join the universes corresponding multicast group address.
universe_to_ipv4_multicast_addr(universe)? // "Failed to convert universe to IPv4 multicast addr"
universe_to_ipv6_multicast_addr(universe)? // "Failed to convert universe to IPv6 multicast addr"
/// Removes this `SacnNetworkReceiver` from the multicast group which corresponds to the given universe.
/// Will return an Error if the given universe cannot be converted to an Ipv4 or Ipv6 `multicast_addr` depending on if the Receiver is bound to an
/// IPv4 or IPv6 address. See `packet::universe_to_ipv4_multicast_addr` and `packet::universe_to_ipv6_multicast_addr`.
universe_to_ipv4_multicast_addr(universe)? // "Failed to convert universe to IPv4 multicast addr"
universe_to_ipv6_multicast_addr(universe)? // "Failed to convert universe to IPv6 multicast addr"
/// This method does not attempt to leave multicast groups already joined through previous `listen_universe` calls.
/// Will return an `OsOperationUnsupported` error if attempting to set the flag to true in an environment that multicast
/// This flag is set when the receiver is created as not all environments currently support IP multicast.
/// If set to true then only receive over IPv6. If false then receiving will be over both IPv4 and IPv6.
/// This will return an error if the `SacnReceiver` wasn't created using an IPv6 address to bind to.
/// Will only block if `set_timeout` was called with a timeout of None so otherwise (and by default) it won't
/// An explicit lifetime is given to the `AcnRootLayerProtocol` which comes from the lifetime of the given buffer.
/// The compiler will prevent usage of the returned `AcnRootLayerProtocol` after the buffer is dropped normally but may not in the case
/// buf: The buffer to use for storing the received data into. This buffer shouldn't be accessed or used directly as the data
/// is returned formatted properly in the `AcnRootLayerProtocol`. This buffer is used as memory space for the returned `AcnRootLayerProtocol`.
/// May return an error if there is an issue receiving data from the underlying socket, see (recv)[fn.recv.Socket].
/// May return an error if there is an issue parsing the data from the underlying socket, see (parse)[`fn.AcnRootLayerProtocol::parse.packet`].
/// timeout: The new timeout for the receive operation, a value of None means the recv operation will become blocking.
/// A timeout with Duration 0 will cause an error. See (`set_read_timeout`)[`fn.set_read_timeout.Socket`].
/// If the given address is an IPv4 address then communication will only work between IPv4 devices, if the given address is IPv6 then communication
/// will only work between IPv6 devices by default but IPv4 receiving can be enabled using `set_ipv6_only(false)`.
/// Connects this `SacnNetworkReceiver` to the multicast address which corresponds to the given universe to allow receiving packets for that universe.
/// Will return an Error if the given universe cannot be converted to an IPv4 or IPv6 `multicast_addr` depending on if the Receiver is bound to an
/// IPv4 or IPv6 address. See `packet::universe_to_ipv4_multicast_addr` and `packet::universe_to_ipv6_multicast_addr`.
/// Will return an Io error if cannot join the universes corresponding multicast group address.
universe_to_ipv4_multicast_addr(universe)? // "Failed to convert universe to IPv4 multicast addr"
universe_to_ipv6_multicast_addr(universe)? // "Failed to convert universe to IPv6 multicast addr"
/// Removes this `SacnNetworkReceiver` from the multicast group which corresponds to the given universe.
/// Will return an Error if the given universe cannot be converted to an Ipv4 or Ipv6 `multicast_addr` depending on if the Receiver is bound to an
/// IPv4 or IPv6 address. See `packet::universe_to_ipv4_multicast_addr` and `packet::universe_to_ipv6_multicast_addr`.
/// This method does not attempt to leave multicast groups already joined through previous `listen_universe` calls.
/// Will return an `OsOperationUnsupported` error if attempting to set the flag to true in an environment that multicast
/// This flag is set when the receiver is created as not all environments currently support IP multicast.
/// If set to true then only receive over IPv6. If false then receiving will be over both IPv4 and IPv6.
/// This will return an error if the `SacnReceiver` wasn't created using an IPv6 address to bind to.
/// Will only block if `set_timeout` was called with a timeout of None so otherwise (and by default) it won't
/// An explicit lifetime is given to the `AcnRootLayerProtocol` which comes from the lifetime of the given buffer.
/// The compiler will prevent usage of the returned `AcnRootLayerProtocol` after the buffer is dropped.
/// buf: The buffer to use for storing the received data into. This buffer shouldn't be accessed or used directly as the data
/// is returned formatted properly in the `AcnRootLayerProtocol`. This buffer is used as memory space for the returned `AcnRootLayerProtocol`.
/// May return an error if there is an issue receiving data from the underlying socket, see (recv)[fn.recv.Socket].
/// May return an error if there is an issue parsing the data from the underlying socket, see (parse)[`fn.AcnRootLayerProtocol::parse.packet`].
/// timeout: The new timeout for the receive operation, a value of None means the recv operation will become blocking.
/// A timeout with Duration 0 will cause an error. See (`set_read_timeout`)[`fn.set_read_timeout.Socket`].
let new_vals = self.values.clone(); // https://stackoverflow.com/questions/21369876/what-is-the-idiomatic-rust-way-to-copy-clone-a-vector-in-a-parameterized-functio (26/12/2019)
/// `DMXData` has a total ordering based on the universe, then sync-universe and finally values.
/// This is based on each page containing a last-page value which indicates the number of the last page expected.
/// Returns all the universes being send by this `SacnSource` as discovered through the universe discovery mechanism.
/// Intentionally abstracts over the underlying concept of pages as this is purely an E1.31 Universe Discovery concept and is otherwise transparent.
/// Removes the given universe from the list of universes being sent by this discovered source.
/// Will return an error if the socket cannot be bound to the given address, see (bind)[fn.bind.Socket2].
// Multiple different processes might want to listen to the sACN stream so therefore need to allow re-using the ACN port.
// FreeRTOS on ESP32 doesn't support SO_REUSEPORT and so this allows the library to be used on the platform without issue.
// Multiple different processes might want to listen to the sACN stream so therefore need to allow re-using the ACN port.
/// Will return an error if the given socket cannot be joined to the given multicast group address.
/// See `join_multicast_v4`[`fn.join_multicast_v4.Socket`] and `join_multicast_v6`[`fn.join_multicast_v6.Socket`]
fn join_unix_multicast(socket: &Socket, addr: SockAddr, interface_addr: IpAddr) -> Result<()> {
// Cast required because AF_INET is defined in libc in terms of a c_int (i32) but addr.family returns using u16.
return Err(SacnError::UnsupportedIpVersion("IP version recognised as AF_INET but not actually usable as AF_INET so must be unknown type".to_string()));
return Err(SacnError::UnsupportedIpVersion("IP version recognised as AF_INET6 but not actually usable as AF_INET6 so must be unknown type".to_string()));
return Err(SacnError::UnsupportedIpVersion(format!("IP version not recognised as AF_INET (Ipv4) or AF_INET6 (Ipv6) - family value (as i32): {}", x).to_string()));
/// See `leave_multicast_v4`[`fn.leave_multicast_v4.Socket`] and `leave_multicast_v6`[`fn.leave_multicast_v6.Socket`]
fn leave_unix_multicast(socket: &Socket, addr: SockAddr, interface_addr: IpAddr) -> Result<()> {
// Cast required because AF_INET is defined in libc in terms of a c_int (i32) but addr.family returns using u16.
return Err(SacnError::UnsupportedIpVersion("IP version recognised as AF_INET but not actually usable as AF_INET so must be unknown type".to_string()));
return Err(SacnError::UnsupportedIpVersion("IP version recognised as AF_INET6 but not actually usable as AF_INET6 so must be unknown type".to_string()));
return Err(SacnError::UnsupportedIpVersion(format!("IP version not recognised as AF_INET (Ipv4) or AF_INET6 (Ipv6) - family value (as i32): {}", x).to_string()));
/// Will return an error if the socket cannot be bound to the given address, see (bind)[fn.bind.Socket].
/// Joins the multicast group with the given address using the given socket on the windows operating system.
/// Will return an error if the given socket cannot be joined to the given multicast group address.
/// See `join_multicast_v4`[`fn.join_multicast_v4.Socket`] and `join_multicast_v6`[`fn.join_multicast_v6.Socket`]
/// Will return `OsOperationUnsupported` error if attempt to leave an Ipv6 multicast group as all Ipv6 multicast operations are currently unsupported in Rust on Windows.
// Cast required because AF_INET is defined in libc in terms of a c_int (i32) but addr.family returns using u16.
return Err(SacnError::UnsupportedIpVersion("IP version recognised as AF_INET but not actually usable as AF_INET so must be unknown type".to_string()));
return Err(SacnError::UnsupportedIpVersion("IP version recognised as AF_INET6 but not actually usable as AF_INET6 so must be unknown type".to_string()));
/// See `leave_multicast_v4`[`fn.leave_multicast_v4.Socket`] and `leave_multicast_v6`[`fn.leave_multicast_v6.Socket`]
/// Will return `OsOperationUnsupported` error if attempt to leave an Ipv6 multicast group as all Ipv6 multicast operations are currently unsupported in Rust on Windows.
// Cast required because AF_INET is defined in libc in terms of a c_int (i32) but addr.family returns using u16.
return Err(SacnError::UnsupportedIpVersion("IP version recognised as AF_INET but not actually usable as AF_INET so must be unknown type".to_string()));
return Err(SacnError::UnsupportedIpVersion("IP version recognised as AF_INET6 but not actually usable as AF_INET6 so must be unknown type".to_string()));
/// Used internally within `SequenceNumbering` for tracking the last received timestamps of each packet-type, source, universe combination.
/// This is then used to workout timeouts to trigger network data loss as per ANSI E1.31-2018 Section 6.7.1.
/// Stores information about the current expected sequence numbers for each source, universe and packet type.
/// The sequence numbers used for data packets, keeps a reference of the last sequence number received for each universe.
/// Each type of packet is tracked differently with respect to sequence numbers as per ANSI E1.31-2018 Section 6.7.2 Sequence Numbering.
/// The sequence numbers used for synchronisation packets, keeps a reference of the last sequence number received for each universe.
/// Each type of packet is tracked differently with respect to sequence numbers as per ANSI E1.31-2018 Section 6.7.2 Sequence Numbering.
/// Creates a new `SequenceNumbering` for tracking sequence numbers for the various types of packets.
/// This implementation uses `HashMaps` internally to allow O(1) checking and updating of sequence numbers.
/// Clears the sequence number records completely removing all sources/universes for all types of packet.
/// Checks the timeouts for all packet types, sources and universes with sequence numbers registed.
/// Removes any universes for which the `last_recv` time was at least the given timeout amount of time ago.
/// `announce_timeout`: A flag, if true it indicates than a `UniverseTimeout` error should be thrown if a universe times out on a source.
/// Checks the sequence number is correct for a data packet with the given `sequence_number` and universe from the given source with given cid.
/// `source_limit`: The limit on the number of sources which are allowed, None indicates no limit, if there is a limit then a `SourcesExceededError` may be returned.
/// Returns an `OutOfSequence` error if a packet is received out of order as detected by the different between
/// the packets sequence number and the expected sequence number as specified in ANSI E1.31-2018 Section 6.7.2 Sequence Numbering.
/// Return a `SourcesExceededError` if the cid of the source is new and would cause the number of sources to exceed the given `source_limit`.
/// Checks the sequence number is correct for a sync packet with the given `sequence_number` and universe from the given source with given cid.
/// `source_limit`: The limit on the number of sources which are allowed, None indicates no limit, if there is a limit then a `SourcesExceededError` may be returned.
/// Returns an `OutOfSequence` error if a packet is received out of order as detected by the different between
/// the packets sequence number and the expected sequence number as specified in ANSI E1.31-2018 Section 6.7.2 Sequence Numbering.
/// Return a `SourcesExceededError` if the cid of the source is new and would cause the number of sources to exceed the given `source_limit`.
/// Checks the given sequence number for the given universe against the given expected sequence numbers.
/// `src_sequences`: A mutable hashmap which relates sources identified by Uuid to another hashmap which itself relates universes to sequence numbers. The given hashmap of
/// sequences should be for the specific packet-type being checked as different packet-types have their own sequence numbers even from the same source.
/// `source_limit`: The limit on the number of sources which are allowed, None indicates no limit, if there is a limit then a `SourcesExceededError` may be returned.
/// universe: The universe of the packet (this is the data universe for data packets and the sync universe for synchronisation packets).
/// `refresh_timeout`: True if the packet keeps the source / universe alive (Null START Code data and synchronisation packets). Otherwise
/// (alternate START Code data) the sequence number is still checked and updated, but the data loss timer of a live
/// source / universe isn't reset. A new or timed out source / universe is tracked as usual, so a source sending only
/// Returns an `OutOfSequence` error if a packet is received out of order as detected by the different between
/// the packets sequence number and the expected sequence number as specified in ANSI E1.31-2018 Section 6.7.2 Sequence Numbering.
/// Return a `SourcesExceededError` if the cid of the source is new and would cause the number of sources to exceed the given `source_limit`.
// This is done for all sources/universes rather than just the source that sent the packet because a completely dead (no packets being sent) universe
// would not be removed otherwise and would continue to take up space. This comes at the cost of increased processing time complexity as each
// When timeouts are announced they are reported by `SacnReceiver::recv` before each read instead. Reporting them from here would return an error
// in place of this (valid) packet, so the packet would be lost because a different source had timed out.
// Indicates that this is the first time (or the first time since it timed out) the universe has been received from this source.
// A timed out entry that hasn't been removed yet (because timeouts are being announced) is treated the same way.
// Previously checked that cid is present (and added if not), if None is returned now it indicates that between that check and this
// function the cid key value has been removed. This can only happen if there is a memory corruption/thread-interleaving or similar external
// The rust typing system forces this possibility to be acknowledged when in some languages this possibility would still exist but it would be hidden
// While a panic!() call here isn't ideal it shows the strength in the explictness of the rust system and points to an area of
// potential later improvement within the code by not hiding the problem. As normal if the panic must be caught then rust allows this later on by utilising
// Another possibility here could be to retry the method but this could end with an infinite loop.
// Returning an error could also be done but that could confuse error handling as this should not occur and the receiver would be in an inconsistent
// Replace the old sequence number with the new and reset the timeout, unless this packet doesn't keep the
// universe alive in which case a live universe keeps its timer (a new or timed out universe starts one).
/// Removes any universes for which the `last_recv` time was at least the given timeout amount of time ago.
/// If the time elapsed since the last received data that is equal to or great than the timeout then the source is said to have timed out.
/// Removes the sequence number entry from the given sequences for the given source cid and universe.
/// Returns a `SourceNotFound` error if the given `src_cid` isn't in the given collection of sources/sequence-numbers.
/// Returns a `UniverseNotFound` error if the given universe isn't registered to the given source and so cannot be removed.
/// This discarding of the old data is the default action for compliance as specified in ANSI E1.31-2018, Section 11.2.1.
/// This can be changed if required as part of the mechanism described in ANSI E1.31-2018, Section 6.2.3.4 Requirements for Merging and Arbitrating.
/// This function is only valid if both inputs have the same universe, sync addr, `start_code` and the data contains at least the first value (the start code).
/// Note this merge is done within the explicit priority, if i or n has an explicitly higher priority it will always take precedence before this HTP merge is attempted.
/// This function is only valid if both inputs have the same universe, sync addr, `start_code` and the data contains at least the first value (the start code).
preview: i.preview || n.preview, // If either data is preview then mark the result as preview.
/// A valid data packet whose DMX data was cut short in transit must be rejected rather than parsed with
/// With `announce_timeout` set, a universe that has timed out must be reported whichever source it belongs to, not only if
/// Sources only advertise every `E131_UNIVERSE_DISCOVERY_INTERVAL`, so a discovered source must not expire before its next advert.
/// If a page is lost, the next discovery interval resends the pages already received. Those repeats must not stop the
/// Sources re-advertise every `E131_UNIVERSE_DISCOVERY_INTERVAL`. Only the first advert, and adverts that change the
/// With `Force_Synchronization` set and no synchronisation packet ever received on the address, data isn't held.
// The receiver still listens on the synchronisation address so synchronisation can start, without passing up data
/// While synchronisation is active, data is held until the synchronisation packet even with `Force_Synchronization` set.
/// Once synchronisation is lost, `Force_Synchronization` set means data is processed without waiting, and unset means the
/// Level data (start code 0x00) and per-address priority data (start code 0xDD) for the same universe held for the
/// same synchronisation are both released by the synchronisation packet, rather than one replacing the other, and
/// As per ANSI E1.31-2016 Section 11.1.1, synchronisation begins with the first synchronisation packet. Until then data
/// naming a synchronisation address is passed up straight away, whatever its `Force_Synchronization` option.
// The first synchronisation packet starts synchronisation; there is nothing waiting for it to release.
/// Synchronisation started on one address doesn't hold data naming a different address that has never had a
assert!(res.is_none()); // Should be none because first packet isn't complete as its only the first page.
assert!(res2.is_some()); // Source should be discovered because the second and last page is now received.
dmx_rcv.store_waiting_data(dmx_data2).unwrap(); // Won't be added as lower priority than already waiting data.
/// Generates a data packet framing layer with arbitrary values except for the sequence number which is set to the given value.
/// This is used for tests targeted at checking sequence number behaviour that don't care about other fields.
/// Test data with a Null START Code, so that it keeps its source alive like ordinary DMX levels.
/// Generates a sync packet framing layer with arbitrary values except for the sequence number which is set to the given value.
/// This is used for tests targeted at checking sequence number behaviour that don't care about other fields.
/// Creates a receiver and then makes it handle 2 data packets with sequence numbers 0 and 1 respectively.
/// The receiver is then given a data packet with sequence number 0 which is the lower than the expected value of 2 so should be rejected.
/// This shows that sequence numbers are correctly evaluated and packets rejected if the sequence number is too low for data packets.
let data_packet3 = generate_data_packet_framing_layer_seq_num(UNIVERSE1, 0); // This data packet has a sequence number lower than the expected value of 2 so should be rejected.
// Not interested in specific return values from this test, just assert the data is processed successfully.
// Check that the third data packet with the low sequence number is rejected correctly with the expected OutOfSequence error.
/// Creates a receiver and then makes it handle 2 data packets with sequence numbers 0 and 1 respectively meaning the next expected sequence number should be 2.
/// This exhaustively checks that only sequence numbers outwith the reject range as specified by ANSI E1.31-2018 Section 6.7.2 are accepted for
// The inclusive lower limit used for the sequence numbers tried. Chosen as the minimum value that can fit in an unsigned byte.
// The inclusive upper limit used for the sequence numbers tried. Chosen as the maximum value that can fit in an unsigned byte.
// Reject range set as per ANSI E1.31-2018 Section 6.7.2 "Having first received a packet with sequence number A, a second packet with sequence number B
// arrives. If, using signed 8-bit binary arithmetic, B - A is less than or equal to 0, but greater than -20, then
// The inclusive upper bound on the diff values (new_packet_seq_num - last_packet_seq_num) that will be rejected.
// The exclusive lower bound on the diff values (new_packet_seq_num - last_packet_seq_num) that will be rejected.
// Not interested in specific return values from this test, just assert the data is processed successfully.
// The receiver is now setup correctly ready for the test with a known start state that expects the next data packet sequence number
// Cannot do straight 8 bit arithmetic that relies on underflows/overflows as this is undefined behaviour in rust forbidden by the compiler.
/// Exactly the same as `test_data_packet_sequence_number_exhaustive` but using synchronisation packets.
/// This exhaustively checks that only sequence numbers outwith the reject range as specified by ANSI E1.31-2018 Section 6.7.2 are accepted for
/// As shown by `test_sequence_number_packet_type_independence` sequence numbers are treated independently for data and synchronisation packets so
/// therefore appropriate to test separately. Could have been combined with the data packet variant of this test but by keeping them separate
/// it more clearly shows that data and sync packet sequence numbers should be treated independently and it report errors independently.
// The inclusive lower limit used for the sequence numbers tried. Chosen as the minimum value that can fit in an unsigned byte.
// The inclusive upper limit used for the sequence numbers tried. Chosen as the maximum value that can fit in an unsigned byte.
// Reject range set as per ANSI E1.31-2018 Section 6.7.2 "Having first received a packet with sequence number A, a second packet with sequence number B
// arrives. If, using signed 8-bit binary arithmetic, B - A is less than or equal to 0, but greater than -20, then
// The inclusive upper bound on the diff values (new_packet_seq_num - last_packet_seq_num) that will be rejected.
// The exclusive lower bound on the diff values (new_packet_seq_num - last_packet_seq_num) that will be rejected.
// Not interested in specific return values from this test, just assert the sync packet is processed successfully.
// The receiver is now setup correctly ready for the test with a known start state that expects the next sync packet sequence number
// Cannot do straight 8 bit arithmetic that relies on underflows/overflows as this is undefined behaviour in rust forbidden by the compiler.
/// Creates a receiver and then makes it handle 2 sync packets with sequence numbers 0 and 1 respectively.
/// The receiver is then given a sync packet with sequence number 0 which is the lower than the expected value of 2 so should be rejected.
/// This shows that sequence numbers are correctly evaluated and packets rejected if the sequence number is too low for synchronisation packets.
let sync_packet3 = generate_sync_packet_framing_layer_seq_num(UNIVERSE1, 0); // This sync packet has a sequence number lower than the expected value of 2 so should be rejected.
// Not interested in specific return values from this test, just assert the packets are processed successfully.
// Check that the third sync packet with the low sequence number is rejected correctly with the expected OutOfSequence error.
/// Creates a receiver and then makes it handle 2 sync packets with sequence numbers 0 and 1 respectively.
/// The receiver then resets the sequence number counters and then handles a sync packet with sequence number 0. This would normally be rejected
/// as per `test_sync_packet_sequence_number_below_expected` but because of the reset it shouldn't be.
let sync_packet3 = generate_sync_packet_framing_layer_seq_num(UNIVERSE1, 0); // This sync packet has a sequence number lower than the expected value of 2 so should be rejected.
// Not interested in specific return values from this test, just assert the packets are processed successfully.
/// Creates a receiver and then makes it handle 2 data packets with sequence numbers 0 and 1 respectively.
/// The receiver then resets the sequence number counters and then handles a data packet with sequence number 0. This would normally be rejected
/// as per `test_data_packet_sequence_number_below_expected` but because of the reset it shouldn't be.
let data_packet3 = generate_data_packet_framing_layer_seq_num(UNIVERSE1, 0); // This data packet has a sequence number lower than the expected value of 2 so should be rejected.
// Not interested in specific return values from this test, just assert the data is processed successfully.
/// The receiver is then passed a sync packet with sequence number 0 which shouldn't be rejected as it is a different packet type.
/// Shows sequence numbers are evaluated separately for each packet type as per ANSI E1.31-2018 Section 6.7.2.
// Not interested in specific return values from this test, just assert the data is processed successfully.
// If this isn't rejected it shows that the receiver correctly treats different packet types individually.
/// Creates a receiver and then makes it handle 2 data packets for the same universe with sequence numbers 0 and 1.
/// This then means the receiver will reject another data packet for that universe with sequence number 0.
/// The receiver is then passed a data packet with sequence number 0 for a different universe which shouldn't be rejected as it is for a different universe.
/// Shows sequence numbers are evaluated separately for each universe as per ANSI E1.31-2018 Section 6.7.2.
// Not interested in specific return values from this test, just assert the data is processed successfully.
// At this point the receiver will (as shown by test_data_packet_sequence_number_below_expected) reject a data packet to UNIVERSE1 with sequence number 0
/// Creates a receiver and then makes it handle 2 sync packets for the same synchronisation address with sequence numbers 0 and 1.
/// This then means the receiver will reject another sync packet for that universe with sequence number 0.
/// The receiver is then passed a sync packet with sequence number 0 for a different synchronisation address which shouldn't be rejected as it is for
/// Shows sequence numbers are evaluated separately for each synchronisation address individually as per ANSI E1.31-2018 Section 6.7.2.
// Not interested in specific return values from this test, just assert the data is processed successfully.
// At this point the receiver will (as shown by test_sync_packet_sequence_number_below_expected) reject a sync packet for SYNC_ADDR_1 with sequence number 0
/// Tests handling a sync packet for a synchronisation address which isn't currently being listened to.
"Sync packet produced output when should have been ignored as for an address that isn't being listened to"
/// Tests the equivalence of 2 `DMXDatas` which are only similar in the aspects used for checking equivalence.
// The timed out source is left in place so that the timeout check `recv` runs can still report it.
/// A source that comes back after timing out starts a new sequence, even if the timed out entry
fn sync_data_packet<'a>(universe: u16, sync_uni: u16, seq: u8) -> DataPacketFramingLayer<'a> {
/// A synchronisation address named by a data packet is joined for its sync packets, but data sent on that universe
/// A synchronisation universe nobody has named for the data loss timeout is forgotten, so its sync packets are
/// Listening to, then muting, a universe that is also in use for synchronisation must not join its group twice or
// Joining the same group twice fails on Linux (EADDRINUSE), so this would error if it re-joined.
// Still joined: the group can be left once, when the sync universe expires. Leaving a group that isn't joined
/// A data packet like `generate_data_packet_framing_layer_seq_num` but with the given START code.
/// A termination packet that is also marked as preview data still terminates the stream when preview data is ignored.
/// Alternate START Code data updates the sequence number of a live stream but doesn't reset its data loss timer.
/// Alternate START Code data from a new or timed out source starts a data loss timer, so that it can time out.
/// A source sending only 0xDD per-address priority data times out even though its packets keep arriving.