plug_and_play/
plug_and_play.rs

1// This example shows how to connect to the hub and activate the motor
2//
3//
4// 
5
6use std::{
7    str::FromStr, 
8    time::Duration
9};
10
11use tokio::time;
12
13use anyhow::Result;
14use btleplug::api::BDAddr;
15
16use rust_powered_lego::{
17    connection_manager::ConnectionManager, 
18    HubType,
19    MotorType,
20    lego::message_parameters::{
21        StartupAndCompletionInfo,
22    },
23    lego::{
24        consts::{
25            TechnicHubPorts,
26            EndState, 
27            Profile,
28        },
29    },
30};
31
32
33#[tokio::main]
34async fn main() -> Result<()> {
35    // Hub "MAC" address can be found in several ways. 
36    // Connect it to a computer and continue from there...
37    let hub_mac_address = "90:84:2b:4e:5b:96";
38    let port_id = TechnicHubPorts::B;
39
40    // Converting the MAC string to btleplug::api::BDAddr type
41    let address = BDAddr::from_str(hub_mac_address)?;
42
43    // The ConnectionManager connects stuff - so ask it for the hub...
44    let cm = ConnectionManager::new();
45
46    // It is possible to use the name of the hub or its MAC address. That's why it's Option<>
47    // Here, only address is implemented
48    let hub = cm.get_hub(None, Some(address), 5).await?;
49
50    // Ask to get the motor object (pay attention to the port_id)
51    let motor = hub.get_motor(port_id as u8).await?;
52
53    // Initiate the motor with power
54    _ = motor.start_power(100, StartupAndCompletionInfo::ExecuteImmediatelyAndNoAction).await?;
55
56    // Let it hang there for 3 seconds
57    time::sleep(Duration::from_secs(3)).await;
58
59    // And stop
60    _ = motor.stop_motor(EndState::FLOAT, Profile::AccDec, StartupAndCompletionInfo::ExecuteImmediatelyAndNoAction).await?;
61
62    Ok(())
63}