lego-powered-up 0.4.0

Control Lego PoweredUp hubs and devices
Documentation
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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
pub use btleplug;
use btleplug::api::{
    Central, CentralEvent, Manager as _, Peripheral as _, PeripheralProperties,
    ScanFilter, ValueNotification,
};
use btleplug::platform::{Adapter, Manager, PeripheralId};
use tokio_util::sync::CancellationToken;

// std
use core::time::Duration;
pub use futures;
use futures::{stream::StreamExt, Stream};
use hubs::HubNotification;
use std::sync::Arc;
use tokio::sync::broadcast;
use tokio::sync::Mutex;
#[macro_use]
extern crate log;

// nostd
use core::fmt::Debug;
use core::pin::Pin;
use num_traits::FromPrimitive;

// Crate
pub mod consts;
pub mod error;
pub mod hubs;
pub mod iodevice;
pub mod notifications;
pub mod setup;

pub use crate::consts::IoTypeId;
pub use crate::iodevice::IoDevice;
pub use hubs::Hub;

use consts::{BLEManufacturerData, HubType};
pub use error::{Error, OptionContext, Result};
use notifications::{
    NetworkCommand, PortOutputCommandFeedbackFormat, PortValueCombinedFormat,
    PortValueSingleFormat,
};

pub type HubMutex = Arc<Mutex<Box<dyn Hub>>>;
type NotificationStream = Pin<Box<dyn Stream<Item = ValueNotification> + Send>>;

pub struct PoweredUp {
    adapter: Adapter,
}

impl PoweredUp {
    pub async fn adapters() -> Result<Vec<Adapter>> {
        let manager = Manager::new().await?;
        Ok(manager.adapters().await?)
    }

    pub async fn init() -> Result<Self> {
        let manager = Manager::new().await?;
        let adapter = manager
            .adapters()
            .await?
            .into_iter()
            .next()
            .context("No adapter found")?;
        Self::with_adapter(adapter).await
    }

    pub async fn with_device_index(index: usize) -> Result<Self> {
        let manager = Manager::new().await?;
        let adapter = manager
            .adapters()
            .await?
            .into_iter()
            .nth(index)
            .context("No adapter found")?;
        Self::with_adapter(adapter).await
    }

    pub async fn with_adapter(adapter: Adapter) -> Result<Self> {
        Ok(Self { adapter })
    }

    pub async fn run(&mut self) -> Result<()> {
        self.adapter.start_scan(ScanFilter::default()).await?;
        Ok(())
    }

    pub async fn find_hub(&mut self) -> Result<Option<DiscoveredHub>> {
        let hubs = self.list_discovered_hubs().await?;
        Ok(hubs.into_iter().next())
    }

    pub async fn list_discovered_hubs(&mut self) -> Result<Vec<DiscoveredHub>> {
        let peripherals = self.adapter.peripherals().await?;
        let mut hubs = Vec::new();
        for peripheral in peripherals {
            let Some(props) = peripheral.properties().await? else {
                continue;
            };
            if let Some(hub_type) = identify_hub(&props).await? {
                hubs.push(DiscoveredHub {
                    hub_type,
                    addr: peripheral.id(),
                    name: props
                        .local_name
                        .unwrap_or_else(|| "unknown".to_string()),
                });
            }
        }
        Ok(hubs)
    }

    pub async fn wait_for_hub(&mut self) -> Result<DiscoveredHub> {
        self.wait_for_hub_filter(HubFilter::Null).await
    }

    pub async fn wait_for_hub_filter(
        &mut self,
        filter: HubFilter,
    ) -> Result<DiscoveredHub> {
        let mut events = self.adapter.events().await?;
        // self.adapter.start_scan(ScanFilter::default()).await?;
        self.adapter.start_scan(scanfilter()).await?;
        while let Some(event) = events.next().await {
            let CentralEvent::DeviceDiscovered(id) = event else {
                continue;
            };
            // get peripheral info
            let peripheral = self.adapter.peripheral(&id).await?;
            // println!("{:?}", peripheral.properties().await?);
            let Some(props) = peripheral.properties().await? else {
                continue;
            };
            if let Some(hub_type) = identify_hub(&props).await? {
                let hub = DiscoveredHub {
                    hub_type,
                    addr: id,
                    name: props
                        .local_name
                        .unwrap_or_else(|| "unknown".to_string()),
                };
                if filter.matches(&hub) {
                    self.adapter.stop_scan().await?;
                    return Ok(hub);
                }
            }
        }
        panic!()
    }

    pub async fn wait_for_hubs_filter(
        &mut self,
        filter: HubFilter,
        count: &u8,
    ) -> Result<Vec<DiscoveredHub>> {
        let mut events = self.adapter.events().await?;
        let mut hubs = Vec::new();
        self.adapter.start_scan(scanfilter()).await?;
        while let Some(event) = events.next().await {
            let CentralEvent::DeviceDiscovered(id) = event else {
                continue;
            };
            // get peripheral info
            let peripheral = self.adapter.peripheral(&id).await?;
            // println!("{:?}", peripheral.properties().await?);
            let Some(props) = peripheral.properties().await? else {
                continue;
            };
            if let Some(hub_type) = identify_hub(&props).await? {
                let hub = DiscoveredHub {
                    hub_type,
                    addr: id,
                    name: props
                        .local_name
                        .unwrap_or_else(|| "unknown".to_string()),
                };
                if filter.matches(&hub) {
                    hubs.push(hub);
                }
                if hubs.len() == *count as usize {
                    self.adapter.stop_scan().await?;
                    return Ok(hubs);
                }
            }
        }
        panic!()
    }

    pub async fn create_hub(
        &mut self,
        hub: &DiscoveredHub,
    ) -> Result<Box<dyn Hub>> {
        info!("Connecting to hub {}...", hub.addr,);

        let peripheral = self.adapter.peripheral(&hub.addr).await?;
        peripheral.connect().await?;
        peripheral.discover_services().await?;
        // tokio::time::sleep(Duration::from_secs(2)).await;
        let chars = peripheral.characteristics();

        // dbg!(&chars);

        let lpf_char = chars
            .iter()
            .find(|c| c.uuid == *consts::blecharacteristic::LPF2_ALL)
            .context("Device does not advertise LPF2_ALL characteristic")?
            .clone();
        let cancel = CancellationToken::new();
        match hub.hub_type {
            // These have had some real life-testing.
            HubType::TechnicMediumHub
            | HubType::MoveHub
            | HubType::RemoteControl => Ok(Box::new(
                hubs::generic_hub::GenericHub::init(
                    peripheral,
                    lpf_char,
                    hub.hub_type,
                    cancel,
                )
                .await?,
            )),
            // These are untested, but if they support the same "Lego Wireless protocol 3.0"
            // then they should probably work?
            HubType::Wedo2SmartHub
            | HubType::Hub
            | HubType::DuploTrainBase
            | HubType::Mario => Ok(Box::new(
                hubs::generic_hub::GenericHub::init(
                    peripheral,
                    lpf_char,
                    hub.hub_type,
                    cancel,
                )
                .await?,
            )),
            // Here is some hub that advertises LPF2_ALL but is not in the known list.
            // Set kind to Unknown and give it a try, why not?
            _ => Ok(Box::new(
                hubs::generic_hub::GenericHub::init(
                    peripheral,
                    lpf_char,
                    HubType::Unknown,
                    cancel,
                )
                .await?,
            )),
        }
    }

    pub async fn scan(
        &mut self,
    ) -> Result<impl Stream<Item = DiscoveredHub> + '_> {
        let events = self.adapter.events().await?;
        // self.adapter.start_scan(ScanFilter::default()).await?;
        self.adapter.start_scan(scanfilter()).await?;
        Ok(events.filter_map(|event| async {
            let CentralEvent::DeviceDiscovered(id) = event else {
                None?
            };
            // get peripheral info
            let peripheral = self.adapter.peripheral(&id).await.ok()?;
            println!("{:?}", peripheral.properties().await.unwrap());
            let Some(props) = peripheral.properties().await.ok()? else {
                None?
            };
            if let Some(hub_type) = identify_hub(&props).await.ok()? {
                let hub = DiscoveredHub {
                    hub_type,
                    addr: id,
                    name: props
                        .local_name
                        .unwrap_or_else(|| "unknown".to_string()),
                };
                Some(hub)
            } else {
                None
            }
        }))
    }

    pub async fn scan2(
        &mut self,
    ) -> Result<Pin<Box<dyn Stream<Item = DiscoveredHub> + Send + '_>>> {
        let events = self.adapter.events().await?;
        self.adapter.start_scan(scanfilter()).await?;
        Ok(Box::pin(events.filter_map(|event| async {
            let CentralEvent::DeviceDiscovered(id) = event else {
                None?
            };
            // get peripheral info
            let peripheral = self.adapter.peripheral(&id).await.ok()?;
            println!("{:?}", peripheral.properties().await.unwrap());
            let Some(props) = peripheral.properties().await.ok()? else {
                None?
            };
            if let Some(hub_type) = identify_hub(&props).await.ok()? {
                let hub = DiscoveredHub {
                    hub_type,
                    addr: id,
                    name: props
                        .local_name
                        .unwrap_or_else(|| "unknown".to_string()),
                };
                Some(hub)
            } else {
                None
            }
        })))
    }
}

fn scanfilter() -> ScanFilter {
    ScanFilter {
        services: vec![
            *consts::bleservice::LPF2_HUB,
            *consts::bleservice::WEDO2_SMART_HUB,
        ],
    }
}

/// Properties by which to filter discovered hubs
#[derive(Debug, PartialEq, Eq)]
pub enum HubFilter {
    /// Hub name must match the provided value
    Name(String),
    /// Hub address must match the provided value
    Addr(String),
    /// Match by type
    Kind(HubType),
    /// Always matches
    Null,
}

impl HubFilter {
    /// Test whether the discovered hub matches the provided filter mode
    pub fn matches(&self, hub: &DiscoveredHub) -> bool {
        use HubFilter::*;
        match self {
            Name(n) => hub.name == *n,
            // Addr(a) => format!("{:?}", hub.addr) == *a,
            Addr(a) => format!("{:?}", hub.addr) == *a,
            Kind(k) => hub.hub_type == *k,
            Null => true,
        }
    }
}

/// Struct describing a discovered hub. This description may be passed
/// to `PoweredUp::create_hub` to initialise a connection.
#[derive(Clone, Debug)]
pub struct DiscoveredHub {
    /// Type of hub, e.g. TechnicMediumHub
    pub hub_type: HubType,
    /// BLE address
    pub addr: PeripheralId,
    /// Friendly name of the hub, as set in the PoweredUp/Control+ apps
    pub name: String,
}

async fn identify_hub(props: &PeripheralProperties) -> Result<Option<HubType>> {
    use HubType::*;

    if props
        .services
        .contains(&consts::bleservice::WEDO2_SMART_HUB)
    {
        return Ok(Some(Wedo2SmartHub));
    } else if props.services.contains(&consts::bleservice::LPF2_HUB) {
        if let Some(manufacturer_id) = props.manufacturer_data.get(&919) {
            // Can't do it with a match because some devices are just manufacturer
            // data while some use other characteristics
            if let Some(m) = BLEManufacturerData::from_u8(manufacturer_id[1]) {
                use BLEManufacturerData::*;
                return Ok(Some(match m {
                    DuploTrainBaseId => DuploTrainBase,
                    HubId => Hub,
                    MarioId => Mario,
                    MoveHubId => MoveHub,
                    RemoteControlId => RemoteControl,
                    TechnicMediumHubId => TechnicMediumHub,
                }));
            }
        }
    }
    Ok(None)
}

pub struct ConnectedHub {
    pub name: String,
    pub mutex: HubMutex,
    pub kind: HubType,
    pub cancel: CancellationToken,
    // pub dropguard: DropGuard,
}
impl ConnectedHub {
    pub async fn setup_hub(created_hub: Box<dyn Hub>) -> Result<ConnectedHub> {
        let connected_hub = ConnectedHub {
            kind: created_hub.kind(),
            name: created_hub.name().await?,
            cancel: created_hub.cancel_token(),
            mutex: Arc::new(Mutex::new(created_hub)),
        };
        // Create forwarding channels and store in hub so we can create receivers on demand
        {
            let lock = &mut connected_hub.mutex.lock().await;
            lock.channels().singlevalue_sender =
                Some(broadcast::channel::<PortValueSingleFormat>(32).0);
            lock.channels().combinedvalue_sender =
                Some(broadcast::channel::<PortValueCombinedFormat>(32).0);
            lock.channels().networkcmd_sender =
                Some(broadcast::channel::<NetworkCommand>(16).0);
            lock.channels().hubnotification_sender =
                Some(broadcast::channel::<HubNotification>(16).0);
            lock.channels().commandfeedback_sender = Some(
                broadcast::channel::<PortOutputCommandFeedbackFormat>(16).0,
            );
        }
        // Set up notification handler
        let hub_mutex = connected_hub.mutex.clone();
        {
            let lock = &mut connected_hub.mutex.lock().await;
            let stream: NotificationStream =
                lock.peripheral().notifications().await?;
            let senders = lock.channels().clone();
            // let senders = (
            //     lock.channels().singlevalue_sender.as_ref().unwrap().clone(),
            //     lock.channels()
            //         .combinedvalue_sender
            //         .as_ref()
            //         .unwrap()
            //         .clone(),
            //     lock.channels().networkcmd_sender.as_ref().unwrap().clone(),
            //     lock.channels()
            //         .hubnotification_sender
            //         .as_ref()
            //         .unwrap()
            //         .clone(),
            //     lock.channels()
            //         .commandfeedback_sender
            //         .as_ref()
            //         .unwrap()
            //         .clone(),
            // );
            let io_handler_cancel = connected_hub.cancel.clone();
            let _io_handler_task = tokio::spawn(async move {
                crate::hubs::io_event::io_event_handler(
                    stream,
                    hub_mutex,
                    senders,
                    io_handler_cancel,
                )
                .await
                .expect("Error setting up main notification handler");
            });
        }

        // Subscribe to btleplug peripheral
        {
            let lock = connected_hub.mutex.lock().await;
            match lock.peripheral().subscribe(&lock.characteristic()).await {
                Ok(()) => (),
                // We got a peri connection but can't subscribe. Can happen if the hub has almost timed out
                // waiting for a connection; it seemingly connects but then turns off. On Windows the error
                // returned was a HRESULT: Operation aborted
                Err(e) => {
                    eprintln!(
                        "Error subscribing to peripheral notifications: {:#?}",
                        e
                    )
                }
            }
        }
        // Wait for devices to be collected. This is set to a very long time because notifications
        // from the hub sometimes lag, and we don't know how many devices to expect.
        tokio::time::sleep(Duration::from_millis(3000)).await;

        Ok(connected_hub)
    }
}