use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
use std::net::Ipv4Addr;
use std::time::{Duration, Instant};
use prolink_proto::djl::{self, Body};
use prolink_proto::{DeviceKind, DeviceName, DeviceNumber, MacAddress};
pub const STALE_AFTER: Duration = djl::DEVICE_TIMEOUT;
pub const FORGET_AFTER: Duration = Duration::from_mins(1);
#[derive(Clone, PartialEq, Eq)]
pub struct Device {
pub mac: MacAddress,
pub ip: Ipv4Addr,
pub name: DeviceName,
pub number: DeviceNumber,
pub kind: DeviceKind,
pub peer_count: u8,
pub generation: u8,
pub first_seen: Instant,
pub last_seen: Instant,
pub keep_alives: u64,
pub offline: bool,
}
impl Device {
pub fn generation_name(&self) -> &'static str {
match self.generation {
0x00 => "nexus or earlier",
0x01 => "0x01 (documented, never observed)",
0x20 => "Stagehand",
0x64 => "CDJ-3000",
_ => "unknown",
}
}
pub fn silence(&self, now: Instant) -> Duration {
now.saturating_duration_since(self.last_seen)
}
}
impl fmt::Display for Device {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{:>2} {:<20} {:<15} {} {}",
self.number,
self.name,
self.ip,
self.mac,
self.generation_name()
)?;
if self.offline {
f.write_str(" (offline)")?;
}
Ok(())
}
}
impl fmt::Debug for Device {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Device")
.field("number", &self.number)
.field("name", &self.name)
.field("ip", &self.ip)
.field("mac", &self.mac)
.field("kind", &self.kind)
.field("offline", &self.offline)
.finish_non_exhaustive()
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum DeviceEvent {
Found(Device),
Updated(Device),
WentOffline(Device),
CameBack(Device),
Forgotten(Device),
}
impl DeviceEvent {
pub fn device(&self) -> &Device {
match self {
Self::Found(device)
| Self::Updated(device)
| Self::WentOffline(device)
| Self::CameBack(device)
| Self::Forgotten(device) => device,
}
}
}
#[derive(Debug)]
pub struct DeviceTable {
devices: BTreeMap<[u8; 6], Device>,
numbers_seen: BTreeSet<u8>,
ignored: BTreeSet<[u8; 6]>,
stale_after: Duration,
forget_after: Duration,
}
impl Default for DeviceTable {
fn default() -> Self {
Self::new()
}
}
impl DeviceTable {
pub fn new() -> Self {
Self {
devices: BTreeMap::new(),
numbers_seen: BTreeSet::new(),
ignored: BTreeSet::new(),
stale_after: STALE_AFTER,
forget_after: FORGET_AFTER,
}
}
pub fn ignore(&mut self, mac: MacAddress) {
self.ignored.insert(mac.0);
}
pub fn observe(&mut self, packet: &djl::Packet, now: Instant) -> Option<DeviceEvent> {
if packet
.body
.mac()
.is_some_and(|mac| self.ignored.contains(&mac.0))
{
return None;
}
let Body::KeepAlive {
device_number,
mac,
ip,
peer_count,
trailing,
..
} = packet.body
else {
if let Some(number) = packet.body.device_number().filter(|&number| number != 0) {
self.numbers_seen.insert(number);
}
return None;
};
self.numbers_seen.insert(device_number);
let number = DeviceNumber::new(device_number)?;
match self.devices.get_mut(&mac.0) {
None => {
let device = Device {
mac,
ip,
name: packet.name,
number,
kind: packet.device_kind,
peer_count,
generation: trailing,
first_seen: now,
last_seen: now,
keep_alives: 1,
offline: false,
};
self.devices.insert(mac.0, device.clone());
Some(DeviceEvent::Found(device))
}
Some(existing) => {
let was_offline = existing.offline;
let changed =
existing.number != number || existing.ip != ip || existing.name != packet.name;
existing.last_seen = now;
existing.keep_alives = existing.keep_alives.saturating_add(1);
existing.number = number;
existing.ip = ip;
existing.name = packet.name;
existing.kind = packet.device_kind;
existing.peer_count = peer_count;
existing.generation = trailing;
existing.offline = false;
if was_offline {
Some(DeviceEvent::CameBack(existing.clone()))
} else if changed {
Some(DeviceEvent::Updated(existing.clone()))
} else {
None
}
}
}
}
pub fn reap(&mut self, now: Instant) -> Vec<DeviceEvent> {
let mut events = Vec::new();
self.devices.retain(|_, device| {
let silence = device.silence(now);
if silence > self.stale_after + self.forget_after {
events.push(DeviceEvent::Forgotten(device.clone()));
false
} else {
if silence > self.stale_after && !device.offline {
device.offline = true;
events.push(DeviceEvent::WentOffline(device.clone()));
}
true
}
});
events
}
pub fn forget_offline(&mut self) -> Vec<DeviceEvent> {
let mut events = Vec::new();
self.devices.retain(|_, device| {
if device.offline {
events.push(DeviceEvent::Forgotten(device.clone()));
false
} else {
true
}
});
events
}
pub fn all(&self) -> Vec<Device> {
let mut devices: Vec<Device> = self.devices.values().cloned().collect();
devices.sort_by_key(|device| (device.number, device.ip));
devices
}
pub fn online(&self) -> Vec<Device> {
self.all()
.into_iter()
.filter(|device| !device.offline)
.collect()
}
pub fn by_number(&self, number: DeviceNumber) -> Option<Device> {
self.devices
.values()
.find(|device| device.number == number)
.cloned()
}
pub fn by_ip(&self, ip: Ipv4Addr) -> Option<Device> {
self.devices
.values()
.find(|device| device.ip == ip)
.cloned()
}
pub fn numbers_seen(&self) -> &BTreeSet<u8> {
&self.numbers_seen
}
pub fn len(&self) -> usize {
self.devices.len()
}
pub fn is_empty(&self) -> bool {
self.devices.is_empty()
}
}
#[cfg(test)]
mod tests {
use super::*;
fn keep_alive(number: u8, mac: [u8; 6], ip: [u8; 4]) -> djl::Packet {
djl::Packet::new(
DeviceName::new("CDJ-2000nexus"),
DeviceKind::CDJ,
Body::KeepAlive {
device_number: number,
was_first_on_network: 0x02,
mac: MacAddress(mac),
ip: Ipv4Addr::from(ip),
peer_count: 1,
pad_31: [0; 3],
flags: 0x01,
trailing: 0x00,
},
)
}
#[test]
fn a_keep_alive_creates_a_device() {
let mut table = DeviceTable::new();
let event = table.observe(
&keep_alive(2, [1, 2, 3, 4, 5, 6], [169, 254, 1, 2]),
Instant::now(),
);
assert!(matches!(event, Some(DeviceEvent::Found(_))));
assert_eq!(table.len(), 1);
}
#[test]
fn a_claim_contributes_its_number_without_creating_a_device() {
let mut table = DeviceTable::new();
let claim = djl::Packet::new(
DeviceName::default(),
DeviceKind::CDJ,
Body::ClaimNumber {
device_number: 3,
iteration: 1,
},
);
assert!(table.observe(&claim, Instant::now()).is_none());
assert!(table.is_empty());
assert!(
table.numbers_seen().contains(&3),
"but the number is remembered"
);
}
#[test]
fn renumbering_is_an_update_not_a_new_device() {
let mut table = DeviceTable::new();
let now = Instant::now();
table.observe(&keep_alive(2, [1, 2, 3, 4, 5, 6], [169, 254, 1, 2]), now);
let event = table.observe(&keep_alive(4, [1, 2, 3, 4, 5, 6], [169, 254, 1, 2]), now);
assert!(matches!(event, Some(DeviceEvent::Updated(_))));
assert_eq!(table.len(), 1, "keyed by MAC, so this is the same device");
}
#[test]
fn readdressing_is_an_update_not_a_new_device() {
let mut table = DeviceTable::new();
let now = Instant::now();
table.observe(&keep_alive(2, [1, 2, 3, 4, 5, 6], [192, 168, 1, 5]), now);
let event = table.observe(&keep_alive(2, [1, 2, 3, 4, 5, 6], [169, 254, 1, 2]), now);
assert!(matches!(event, Some(DeviceEvent::Updated(_))));
assert_eq!(table.len(), 1);
}
#[test]
fn a_repeated_keep_alive_is_not_an_event() {
let mut table = DeviceTable::new();
let now = Instant::now();
let packet = keep_alive(2, [1, 2, 3, 4, 5, 6], [169, 254, 1, 2]);
table.observe(&packet, now);
assert!(table.observe(&packet, now).is_none(), "nothing changed");
}
#[test]
fn silence_makes_a_device_offline_before_it_is_forgotten() {
let mut table = DeviceTable::new();
let start = Instant::now();
table.observe(&keep_alive(2, [1, 2, 3, 4, 5, 6], [169, 254, 1, 2]), start);
assert!(
table.reap(start + Duration::from_secs(5)).is_empty(),
"still fresh"
);
let events = table.reap(start + STALE_AFTER + Duration::from_secs(1));
assert!(matches!(events.as_slice(), [DeviceEvent::WentOffline(_)]));
assert_eq!(table.len(), 1, "kept, so a blip does not tear down state");
assert!(table.online().is_empty());
let events = table.reap(start + STALE_AFTER + FORGET_AFTER + Duration::from_secs(1));
assert!(matches!(events.as_slice(), [DeviceEvent::Forgotten(_)]));
assert!(table.is_empty());
}
#[test]
fn a_device_that_comes_back_is_not_a_new_device() {
let mut table = DeviceTable::new();
let start = Instant::now();
let packet = keep_alive(2, [1, 2, 3, 4, 5, 6], [169, 254, 1, 2]);
table.observe(&packet, start);
table.reap(start + STALE_AFTER + Duration::from_secs(1));
let event = table.observe(&packet, start + STALE_AFTER + Duration::from_secs(2));
assert!(matches!(event, Some(DeviceEvent::CameBack(_))));
assert_eq!(table.online().len(), 1);
}
#[test]
fn a_forgotten_devices_number_is_still_remembered() {
let mut table = DeviceTable::new();
let start = Instant::now();
table.observe(&keep_alive(2, [1, 2, 3, 4, 5, 6], [169, 254, 1, 2]), start);
table.reap(start + STALE_AFTER + FORGET_AFTER + Duration::from_secs(1));
assert!(table.is_empty());
assert!(table.numbers_seen().contains(&2));
}
#[test]
fn our_own_broadcasts_are_not_peers() {
let mut table = DeviceTable::new();
table.ignore(MacAddress([1, 2, 3, 4, 5, 6]));
let event = table.observe(
&keep_alive(2, [1, 2, 3, 4, 5, 6], [169, 254, 1, 2]),
Instant::now(),
);
assert!(event.is_none());
assert!(table.is_empty());
}
}