use std::sync::Arc;
use num_enum::{IntoPrimitive, TryFromPrimitive};
use crate::{
channel::HidppChannel,
event::EventEmitter,
feature::{CreatableFeature, EmittingFeature, Feature},
nibble,
protocol::v20,
};
pub struct WirelessDeviceStatusFeatureV0 {
chan: Arc<HidppChannel>,
emitter: Arc<EventEmitter<WirelessDeviceStatusEvent>>,
msg_listener_hdl: u32,
}
impl CreatableFeature for WirelessDeviceStatusFeatureV0 {
const ID: u16 = 0x1d4b;
const STARTING_VERSION: u8 = 0;
fn new(chan: Arc<HidppChannel>, device_index: u8, feature_index: u8) -> Self {
let emitter = Arc::new(EventEmitter::new());
let hdl = chan.add_msg_listener({
let emitter = Arc::clone(&emitter);
move |raw, matched| {
if matched {
return;
}
let msg = v20::Message::from(raw);
let header = msg.header();
if header.device_index != device_index
|| header.feature_index != feature_index
|| nibble::combine(header.software_id, header.function_id) != 0
{
return;
}
let payload = msg.extend_payload();
let Ok(status) = WirelessDeviceStatus::try_from(payload[0]) else {
return;
};
let Ok(request) = WirelessDeviceStatusRequest::try_from(payload[1]) else {
return;
};
let Ok(reason) = WirelessDeviceStatusReason::try_from(payload[2]) else {
return;
};
emitter.emit(WirelessDeviceStatusEvent::StatusBroadcast(
WirelessDeviceStatusBroadcast {
status,
request,
reason,
},
));
}
});
Self {
chan,
emitter,
msg_listener_hdl: hdl,
}
}
}
impl Feature for WirelessDeviceStatusFeatureV0 {
}
impl EmittingFeature<WirelessDeviceStatusEvent> for WirelessDeviceStatusFeatureV0 {
fn listen(&self) -> async_channel::Receiver<WirelessDeviceStatusEvent> {
self.emitter.create_receiver()
}
}
impl Drop for WirelessDeviceStatusFeatureV0 {
fn drop(&mut self) {
self.chan.remove_msg_listener(self.msg_listener_hdl);
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum WirelessDeviceStatusEvent {
StatusBroadcast(WirelessDeviceStatusBroadcast),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct WirelessDeviceStatusBroadcast {
pub status: WirelessDeviceStatus,
pub request: WirelessDeviceStatusRequest,
pub reason: WirelessDeviceStatusReason,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, IntoPrimitive, TryFromPrimitive)]
#[non_exhaustive]
#[repr(u8)]
pub enum WirelessDeviceStatus {
Unknown = 0x00,
Reconnection = 0x01,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, IntoPrimitive, TryFromPrimitive)]
#[non_exhaustive]
#[repr(u8)]
pub enum WirelessDeviceStatusRequest {
NoRequest = 0x00,
SoftwareReconfigurationNeeded = 0x01,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, IntoPrimitive, TryFromPrimitive)]
#[non_exhaustive]
#[repr(u8)]
pub enum WirelessDeviceStatusReason {
Unknown = 0x00,
PowerSwitchActivated = 0x01,
}