[][src]Struct toio::Cube

pub struct Cube { /* fields omitted */ }

The cube.

Provides API to control the cube. The API has two types:

  • High-level API
  • Low-level API

The high-level API provides easy-to-use basic feature to control the cube such as moving, turning on/off the light, and playing sound.

The low-level API provides the API for more fine-grained control and configuration. The API allows to send/receive all the raw protocol messages, which allows to use all the features of toio cube defined in the specification.

This is the example of the high-level API:

use std::time::Duration;
use toio::Cube;
use tokio::time::delay_for;

#[tokio::main]
async fn main() {
    // Search for the nearest cube.
    let mut cube = Cube::search().nearest().await.unwrap();

    // Connect.
    cube.connect().await.unwrap();

    // Print status.
    println!("version   : {}", cube.version().await.unwrap());
    println!("battery   : {}%", cube.battery().await.unwrap());
    println!("button    : {}", cube.button().await.unwrap());

    // Move forward.
    cube.go(10, 10, None).await.unwrap();

    delay_for(Duration::from_secs(3)).await;

    // Spin for 2 seconds.
    cube.go(100, 5, Some(Duration::from_secs(2))).await.unwrap();

    delay_for(Duration::from_secs(3)).await;
}

Implementations

impl Cube[src]

pub fn search() -> Searcher[src]

Returns Searcher instance to search for cubes.

To find the nearest cube,

use toio::Cube;

#[tokio::main]
async fn main() {
    let mut cube = Cube::search().nearest().await.unwrap();

    cube.connect().await.unwrap();
}

To find all cubes,

use toio::Cube;

#[tokio::main]
async fn main() {
    let mut cubes = Cube::search().all().await.unwrap();

    for mut cube in cubes {
        cube.connect().await.unwrap();
    }
}

By default, the search timeout is 3 seconds. Use [Cube::search_timeout][] to set custom timeout.

pub fn id(&self) -> &str[src]

Gets the device id.

pub fn rssi(&self) -> i32[src]

Gets the signal strength.

pub async fn version<'_>(&'_ mut self) -> Result<String>[src]

Gets the BLE protocol version.

pub async fn battery<'_>(&'_ mut self) -> Result<usize>[src]

Gets the battery status.

Returns the percentage of the remaining battery.

pub async fn collision<'_>(&'_ mut self) -> Result<bool>[src]

Gets the collision status.

Returns true if the cube is in collision.

pub async fn slope<'_>(&'_ mut self) -> Result<bool>[src]

Gets the slope status.

Returns true if the cube slopes.

pub async fn button<'_>(&'_ mut self) -> Result<bool>[src]

Gets the button status.

Returns true if the button is pressed.

pub async fn position<'_>(&'_ mut self) -> Result<Option<Position>>[src]

Gets the position information.

Returns the position information which is read by the sensor. Returns None if no position information is available.

pub async fn std_id<'_>(&'_ mut self) -> Result<Option<StdId>>[src]

Gets the standard id.

Returns the standard id which is read by the sensor. Returns None if no id is available.

pub async fn go<'_>(
    &'_ mut self,
    left: isize,
    right: isize,
    duration: Option<Duration>
) -> Result<()>
[src]

Moves the cube.

left and right are the rotation speed of each wheel. The value must be in the range from -100 to 100. The negative number rotates backward, while the positive rotates forward. If specified, the wheels rotate for the given duration. If the duration is None, wheels rotate forever. The duration must be in the range from 1 to 2559 milliseconds.

use std::time::Duration;
use toio::Cube;

#[tokio::main]
async fn main() {
    let mut cube = Cube::search().nearest().await.unwrap();
    cube.connect().await.unwrap();

    // Move forward.
    cube.go(10, 10, None).await.unwrap();

    // Move backward.
    cube.go(-10, -10, None).await.unwrap();

    // Spin counterclockwise.
    cube.go(5, 50, None).await.unwrap();

    // Spin clockwise for 1 second.
    cube.go(50, 5, Some(Duration::from_secs(1))).await.unwrap();
}

pub async fn stop<'_>(&'_ mut self) -> Result<()>[src]

Stops the cube.

Both wheels stop rotating.

use std::time::Duration;
use tokio::time::delay_for;
use toio::Cube;

#[tokio::main]
async fn main() {
    let mut cube = Cube::search().nearest().await.unwrap();
    cube.connect().await.unwrap();

    // Move forward.
    cube.go(10, 10, None).await.unwrap();

    delay_for(Duration::from_secs(3)).await;

    // Stop the cube.
    cube.stop().await.unwrap();
}

pub async fn play_preset<'_>(&'_ mut self, id: SoundPresetId) -> Result<()>[src]

Plays sound preset.

use toio::{Cube, SoundPresetId};

#[tokio::main]
async fn main() {
    let mut cube = toio::Cube::search().nearest().await.unwrap();
    cube.connect().await.unwrap();

    cube.play_preset(SoundPresetId::Enter).await.unwrap();
}

pub async fn play<'_>(
    &'_ mut self,
    repeat: usize,
    ops: Vec<SoundOp>
) -> Result<()>
[src]

Plays sound.

Play sound in accordance with the list of sound operations. The number of sound operations must be less than 60. The duration for each sound must be in the range from 1 to 2559 milliseconds. The repeat count must be less than 256.

use std::time::Duration;
use toio::{Cube, SoundOp, Note};

#[tokio::main]
async fn main() {
    let mut cube = toio::Cube::search().nearest().await.unwrap();
    cube.connect().await.unwrap();

    cube.play(
        // Repeats three times.
        3,
        // Plays two sound for 500 milliseconds for each.
        vec![
            SoundOp::new(Note::C5, Duration::from_millis(500)),
            SoundOp::new(Note::A6, Duration::from_millis(500)),
        ],
    ).await.unwrap();
}

pub async fn stop_sound<'_>(&'_ mut self) -> Result<()>[src]

Stops playing sound.

use std::time::Duration;
use tokio::time::delay_for;
use toio::{Cube, SoundOp, Note};

#[tokio::main]
async fn main() {
    let mut cube = toio::Cube::search().nearest().await.unwrap();
    cube.connect().await.unwrap();

    // Starts playing sound.
    cube.play(1, vec![SoundOp::new(Note::C5, Duration::from_secs(2))]).await.unwrap();

    delay_for(Duration::from_secs(1)).await;

    // Stops the sound.
    cube.stop_sound().await.unwrap();
}

pub async fn light<'_>(
    &'_ mut self,
    repeat: usize,
    ops: Vec<LightOp>
) -> Result<()>
[src]

Turns on the light as programmed.

The light color is set by RGB value, each of which must be in range 0 to 255. The number of light operations must be less than 30. The repeat count must be less than 256. The duration of each light operation must be less than 2560 milliseconds.

use std::time::Duration;
use toio::{Cube, LightOp};

#[tokio::main]
async fn main() {
    let mut cube = toio::Cube::search().nearest().await.unwrap();
    cube.connect().await.unwrap();

    cube.light(
        // Repeats 10 times.
        10,
        // Turns on the red, green, blue light for 100 milliseconds for each.
        vec![
            LightOp::new(255, 0, 0, Some(Duration::from_millis(100))),
            LightOp::new(0, 255, 0, Some(Duration::from_millis(100))),
            LightOp::new(0, 0, 255, Some(Duration::from_millis(100))),
        ],
    ).await.unwrap();
}

pub async fn light_on<'_>(
    &'_ mut self,
    red: u8,
    green: u8,
    blue: u8,
    duration: Option<Duration>
) -> Result<()>
[src]

Turns on the light.

The light color is set by RGB value, each of which must be in range 0 to 255. The duration must be less than 2560 milliseconds.

use toio::Cube;

#[tokio::main]
async fn main() {
    let mut cube = toio::Cube::search().nearest().await.unwrap();
    cube.connect().await.unwrap();

    // Turns on the green light.
    cube.light_on(0, 255, 0, None).await.unwrap();
}

pub async fn light_off<'_>(&'_ mut self) -> Result<()>[src]

Turns off the light.

use std::time::Duration;
use tokio::time::delay_for;
use toio::Cube;

#[tokio::main]
async fn main() {
    let mut cube = toio::Cube::search().nearest().await.unwrap();
    cube.connect().await.unwrap();

    // Turns on the light.
    cube.light_on(255, 255, 255, None).await.unwrap();

    delay_for(Duration::from_secs(3)).await;

    // Turns off the light.
    cube.light_off().await.unwrap();
}

pub async fn connect<'_>(&'_ mut self) -> Result<()>[src]

Connects to the cube.

This must be called first before operating on the cube.

use toio::Cube;

#[tokio::main]
async fn main() {
    let mut cube = Cube::search().nearest().await.unwrap();

    // Connects to the cube.
    cube.connect().await.unwrap();
}

pub async fn events<'_>(&'_ mut self) -> Result<EventStream>[src]

Subscribes to events.

use futures::prelude::*;
use toio::{Cube, Event};

#[tokio::main]
async fn main() {
    let mut cube = Cube::search().nearest().await.unwrap();
    cube.connect().await.unwrap();

    let mut events = cube.events().await.unwrap();
    while let Some(event) = events.next().await {
        match event {
            Event::Collision(collided) => println!("collided: {}", collided),
            Event::Battery(remain) => println!("battery: {}%", remain),
            _ => {},
        }
    }
}

pub async fn write_msg<'_>(
    &'_ mut self,
    msg: Message,
    with_resp: bool
) -> Result<()>
[src]

Writes a raw message to the device.

This is the low-level API that allows to directly write the protocol data structures defined in proto to the cube device. Some data triggers events which can be retrieved by Cube::raw_msgs or Cube::events.

use toio::{Cube, proto::*};

#[tokio::main]
async fn main() {
    let mut cube = Cube::search().nearest().await.unwrap();
    cube.connect().await.unwrap();

    // Move forward.
    cube.write_msg(
        Message::Motor(Motor::Simple(MotorSimple::new(
            MotorId::Left,
            MotorDir::Forward,
            30,
            MotorId::Right,
            MotorDir::Forward,
            30,
        ))),
        false,
    ).await.unwrap();
}

pub async fn read_msg<'_, '_>(&'_ mut self, uuid: &'_ Uuid) -> Result<()>[src]

Sends a read request to the device.

This is the low-level API to request to read values in the device. This usually triggers events which can be retrieved by Cube::raw_msgs or Cube::events.

use futures::prelude::*;
use toio::{Cube, proto::*};

#[tokio::main]
async fn main() {
    let mut cube = Cube::search().nearest().await.unwrap();
    cube.connect().await.unwrap();

    // Subscribe to raw messages.
    let mut msgs = cube.raw_msgs().await.unwrap();

    // Send a read request for motor state to the cube.
    cube.read_msg(&UUID_MOTION).await.unwrap();

    // Receive the motor state, which is sent as response to the read request.
    while let Some(msg) = msgs.next().await {
        match msg {
            Message::Motion(Motion::Detect(d)) => {
                println!("{:?}", d);
                break;
            }
            _ => {}
        }
    }
}

pub async fn raw_msgs<'_>(&'_ mut self) -> Result<BoxStream<'static, Message>>[src]

Subscribe to raw messages.

This is the low-level API to subscribe to raw protocol messages from the cube device.

use futures::prelude::*;
use toio::{Cube, proto::*};

#[tokio::main]
async fn main() {
    let mut cube = Cube::search().nearest().await.unwrap();
    cube.connect().await.unwrap();

    // Subscribe to raw messages.
    let mut msgs = cube.raw_msgs().await.unwrap();

    // Receive raw messages.
    while let Some(msg) = msgs.next().await {
        match msg {
            Message::Motion(Motion::Detect(d)) => {
            }
            _ => {}
        }
    }
}

Trait Implementations

impl Debug for Cube[src]

impl Drop for Cube[src]

Auto Trait Implementations

impl !RefUnwindSafe for Cube

impl Send for Cube

impl !Sync for Cube

impl Unpin for Cube

impl !UnwindSafe for Cube

Blanket Implementations

impl<T> Any for T where
    T: 'static + ?Sized
[src]

impl<T> Borrow<T> for T where
    T: ?Sized
[src]

impl<T> BorrowMut<T> for T where
    T: ?Sized
[src]

impl<T> From<T> for T[src]

impl<T, U> Into<U> for T where
    U: From<T>, 
[src]

impl<T, U> TryFrom<U> for T where
    U: Into<T>, 
[src]

type Error = Infallible

The type returned in the event of a conversion error.

impl<T, U> TryInto<U> for T where
    U: TryFrom<T>, 
[src]

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.