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: FnOnce() -> 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: FnOnce() -> 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 new(id: String, types:Types,name:String) -> Self {
60        Self {
61            id,
62            vid:"".to_string(),
63            pid:"".to_string(),
64            manufacturer:"".to_string(),
65            name,
66            count:0,
67            types,
68            value: JsonValue::from("".to_string()),
69        }
70    }
71    pub fn json(&mut self) -> JsonValue {
72        object! {
73            "id": self.id.clone(),
74            "name": self.name.clone(),
75            "vid": self.vid.clone(),
76            "pid": self.pid.clone(),
77            "manufacturer": self.manufacturer.clone(),
78            "types": self.types.str(),
79        }
80    }
81}
82
83#[derive(Clone, Debug)]
84pub enum Types {
85    /// 键盘
86    Keyboard,
87    /// 鼠标
88    Mouse,
89    None,
90}
91impl Types {
92    fn str(&mut self) -> &'static str {
93        match self {
94            Types::Keyboard => "keyboard",
95            Types::Mouse => "mouse",
96            Types::None => "",
97        }
98    }
99    #[allow(dead_code)]
100    fn from(name: &str) -> Self {
101        match name {
102            "keyboard" => Types::Keyboard,
103            "mouse" => Types::Mouse,
104            _ => Types::None,
105        }
106    }
107}