summary refs log tree commit diff
path: root/src/main.rs
blob: 75ebcbd8640935997740727f636a9257b9854c68 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
use std::{collections::HashSet, pin::pin, time::Duration};

use bluer::{
    Adapter, AdapterEvent, Device, DeviceEvent, DeviceProperty, DiscoveryFilter,
    DiscoveryTransport, Session, Uuid, gatt::remote::Characteristic,
};
use evdev::{
    AbsInfo, AbsoluteAxisCode, AttributeSet, EventType, InputEvent, KeyCode, PropType,
    SynchronizationCode, UinputAbsSetup, uinput::VirtualDevice,
};
use tokio::{select, time::interval};
use tokio_stream::StreamExt;

const HID_SERVICE: Result<Uuid, uuid::Error> =
    Uuid::try_parse("00001812-0000-1000-8000-00805f9b34fb");

const REPORT_REF: Result<Uuid, uuid::Error> =
    Uuid::try_parse("00002908-0000-1000-8000-00805f9b34fb");

// const MAGIC_REPORT: u8 = 240;
const BUTTON_REPORT: u8 = 251;
const TOUCH_REPORT: u8 = 252;

struct RemoteCharateristics {
    touch: Characteristic,
    button: Characteristic,
}

impl RemoteCharateristics {
    async fn get(device: &Device) -> bluer::Result<Self> {
        let mut touch = None;
        let mut button = None;

        for service in device.services().await? {
            if service.uuid().await? == HID_SERVICE.unwrap() {
                for characteristic in service.characteristics().await? {
                    for descriptor in characteristic.descriptors().await? {
                        if descriptor.uuid().await? == REPORT_REF.unwrap() {
                            let resp = descriptor.read().await?;
                            match resp[0] {
                                // MAGIC_REPORT => characteristic.write(&[0xf0, 0x00]).await?,
                                TOUCH_REPORT => touch = Some(characteristic.clone()),
                                BUTTON_REPORT => button = Some(characteristic.clone()),
                                _ => {}
                            }
                        }
                    }
                }
            }
        }

        Ok(Self {
            touch: touch.expect("did not find touch characteristic"),
            button: button.expect("did not find button characteristic"),
        })
    }
}

async fn find_remote(adapter: &Adapter, rssi_thresh: i16) -> bluer::Result<Device> {
    let mut uuids = HashSet::new();
    uuids.insert(HID_SERVICE.unwrap());

    adapter
        .set_discovery_filter(DiscoveryFilter {
            transport: DiscoveryTransport::Le,
            rssi: Some(rssi_thresh),
            uuids,
            ..Default::default()
        })
        .await?;
    let mut discover = pin!(adapter.discover_devices().await?);
    while let Some(evt) = discover.next().await {
        if let AdapterEvent::DeviceAdded(mac) = evt {
            let device = adapter.device(mac)?;
            if let Some(data) = device.manufacturer_data().await? {
                if data.contains_key(&0x4c) {
                    return Ok(device);
                }
            }
        }
    }
    panic!("discovery ended");
}

async fn run(adapter: &Adapter) -> bluer::Result<()> {
    eprintln!("DBG searching");
    let remote = find_remote(&adapter, -25).await?;

    if !remote.is_paired().await? {
        eprintln!("DBG pairing");
        remote.pair().await?;
    }

    eprintln!("DBG connecting");
    remote.connect().await?;

    let mut remote_events = pin!(remote.events().await?);

    let chars = RemoteCharateristics::get(&remote).await?;
    let mut touch_stream = pin!(chars.touch.notify().await?);
    let mut button_stream = pin!(chars.button.notify().await?);

    eprintln!("DBG starting");
    let mut keys = AttributeSet::new();
    keys.insert(KeyCode::BTN_TOUCH);
    keys.insert(KeyCode::BTN_TOOL_FINGER);
    keys.insert(KeyCode::BTN_LEFT);

    let mut props = AttributeSet::new();
    props.insert(PropType::POINTER);

    let mut uinput = VirtualDevice::builder()
        .unwrap()
        .name("Siri Remote")
        .with_properties(&props)
        .unwrap()
        .with_keys(&keys)
        .unwrap()
        .with_absolute_axis(&UinputAbsSetup::new(
            AbsoluteAxisCode::ABS_X,
            AbsInfo::new(0, -2048, 2048, 32, 0, 16),
        ))
        .unwrap()
        .with_absolute_axis(&UinputAbsSetup::new(
            AbsoluteAxisCode::ABS_Y,
            AbsInfo::new(0, -2048, 2048, 32, 0, 16),
        ))
        .unwrap()
        .build()
        .unwrap();

    let mut timer = interval(Duration::from_millis(1));
    let mut x = 0f32;
    let mut y = 0f32;
    let mut tx = 0f32;
    let mut ty = 0f32;
    let mut touch = 0;

    'main: loop {
        select! {
            ev = remote_events.next() => {
                if let Some(DeviceEvent::PropertyChanged(DeviceProperty::Connected(false))) = ev {
                    break 'main;
                }
            }
            ev = touch_stream.next() => {
                let ev = ev.unwrap();
                let touch_next = if ev[3] > 0 { 1 } else { 0 };
                if touch_next > 0 {
                    tx = ((((ev[5] & 15) as u16) << 8) + ev[4] as u16) as f32;
                    ty = ((((ev[5] & !15) as u16) >> 4) + ((ev[6] as u16) << 4)) as f32;
                    if tx >= 2048.0 {
                        tx -= 4096.0;
                    }
                    if ty >= 2048.0 {
                        ty -= 4096.0;
                    }
                    if touch == 0 {
                        x = tx;
                        y = ty;
                    }
                }
                touch = touch_next;
                // ts = (((ev[2] as u16) << 8) + (ev[1] as u16)) as i32;
            },
            ev = button_stream.next() => {
                let ev = ev.unwrap();
                match (ev[0], ev[1]) {
                    (8, 0) => {
                        uinput
                            .emit(&[
                                InputEvent::new(EventType::KEY.0, KeyCode::BTN_LEFT.0, 1),
                                InputEvent::new(
                                    EventType::SYNCHRONIZATION.0,
                                    SynchronizationCode::SYN_REPORT.0,
                                    0,
                                ),
                            ])
                            .unwrap();
                    },
                    (0, 0) => {
                        uinput
                            .emit(&[
                                InputEvent::new(EventType::KEY.0, KeyCode::BTN_LEFT.0, 0),
                                InputEvent::new(
                                    EventType::SYNCHRONIZATION.0,
                                    SynchronizationCode::SYN_REPORT.0,
                                    0,
                                ),
                            ])
                            .unwrap();
                    },
                    (_, _) => (),
                }
            }
            _ = timer.tick() => {
                x = 0.95 * x + 0.05 * tx;
                y = 0.95 * y + 0.05 * ty;

                uinput
                    .emit(&[
                        InputEvent::new(EventType::KEY.0, KeyCode::BTN_TOUCH.0, touch),
                        InputEvent::new(EventType::KEY.0, KeyCode::BTN_TOOL_FINGER.0, touch),
                        InputEvent::new(EventType::ABSOLUTE.0, AbsoluteAxisCode::ABS_X.0, x as i32),
                        InputEvent::new(EventType::ABSOLUTE.0, AbsoluteAxisCode::ABS_Y.0, -y as i32),
                        InputEvent::new(
                            EventType::SYNCHRONIZATION.0,
                            SynchronizationCode::SYN_REPORT.0,
                            0,
                        ),
                    ])
                    .unwrap();
            },
        };
    }

    Ok(())
}

#[tokio::main(flavor = "current_thread")]
async fn main() -> bluer::Result<()> {
    let session = Session::new().await?;
    let adapter = session.default_adapter().await?;

    loop {
        if let Err(e) = run(&adapter).await {
            eprintln!("ERR {e}");
        }
    }
}