br_hid/
lib.rs

1use json::{object, JsonValue};
2
3mod utils;
4
5#[cfg(target_os = "windows")]
6pub mod win;
7#[cfg(target_os = "windows")]
8use win::Win;
9
10#[cfg(target_os = "macos")]
11pub mod mac;
12#[cfg(target_os = "macos")]
13use mac::Mac;
14
15pub fn run<F>(factory: F)
16where
17    F: Fn() -> Box<dyn Handler>,
18{
19    #[cfg(target_os = "windows")]
20    Win::new().run(factory);
21    #[cfg(target_os = "macos")]
22    Mac::new().run(factory)
23}
24pub fn connect<F>(id: String, factory: F)
25where
26    F: Fn() -> Box<dyn Handler>,
27{
28    #[cfg(target_os = "windows")]
29    Win::new().connect(id, factory);
30    #[cfg(target_os = "macos")]
31    Mac::new().connect(id, factory)
32}
33pub trait Handler {
34    fn on_discover(&mut self, device: Device);
35    fn on_data(&mut self, id: String, value: JsonValue);
36    fn on_is_close(&mut self, id: String) -> bool;
37    fn on_disconnected(&mut self, id: String, error: String);
38    fn on_connect(&mut self, id: String);
39}
40
41/// 蓝牙HID设备
42#[derive(Clone)]
43pub struct Device {
44    /// 设备唯一id
45    pub id: String,
46    pub vid: String,
47    pub pid: String,
48    pub types: Types,
49    /// 制造商
50    pub manufacturer: String,
51    /// 设备名称
52    pub name: String,
53    /// 计数
54    pub count: u8,
55    /// 值
56    pub value: JsonValue,
57}
58impl Device {
59    pub fn json(&mut self) -> JsonValue {
60        object! {
61            "id": self.id.clone(),
62            "name": self.name.clone(),
63            "vid": self.vid.clone(),
64            "pid": self.pid.clone(),
65            "manufacturer": self.manufacturer.clone(),
66            "types": self.types.str(),
67        }
68    }
69}
70
71#[derive(Clone, Debug)]
72pub enum Types {
73    /// 键盘
74    Keyboard,
75    /// 鼠标
76    Mouse,
77    None,
78}
79impl Types {
80    fn str(&mut self) -> &'static str {
81        match self {
82            Types::Keyboard => "keyboard",
83            Types::Mouse => "mouse",
84            Types::None => "",
85        }
86    }
87    #[allow(dead_code)]
88    fn from(name: &str) -> Self {
89        match name {
90            "keyboard" => Types::Keyboard,
91            "mouse" => Types::Mouse,
92            _ => Types::None,
93        }
94    }
95}