BtlePlug is a Bluetooth Low Energy (BLE) central module library for Rust. It
currently supports Windows 10, macOS (and possibly iOS), Linux (using BlueZ
sockets instead of D-Bus). Android support is coming in a future update.
An example of how to use the library to control some BLE smart lights:
extern crate btleplug;
extern crate rand;
use std::thread;
use std::time::Duration;
use rand::{Rng, thread_rng};
#[cfg(target_os = "linux")]
use btleplug::bluez::{adapter::ConnectedAdapter, manager::Manager};
#[cfg(target_os = "windows")]
use btleplug::winrtble::{adapter::Adapter, manager::Manager};
#[cfg(target_os = "macos")]
use btleplug::corebluetooth::{adapter::Adapter, manager::Manager};
use btleplug::api::{UUID, Central, Peripheral};
#[cfg(any(target_os = "windows", target_os = "macos"))]
fn get_central(manager: &Manager) -> Adapter {
let adapters = manager.adapters().unwrap();
adapters.into_iter().nth(0).unwrap()
}
#[cfg(target_os = "linux")]
fn get_central(manager: &Manager) -> ConnectedAdapter {
let adapters = manager.adapters().unwrap();
let adapter = adapters.into_iter().nth(0).unwrap();
adapter.connect().unwrap()
}
pub fn main() {
let manager = Manager::new().unwrap();
let central = get_central(&manager);
central.start_scan().unwrap();
thread::sleep(Duration::from_secs(2));
let light = central.peripherals().into_iter()
.find(|p| p.properties().local_name.iter()
.any(|name| name.contains("LEDBlue"))).unwrap();
light.connect().unwrap();
light.discover_characteristics().unwrap();
let chars = light.characteristics();
let cmd_char = chars.iter().find(|c| c.uuid == UUID::B16(0xFFE9)).unwrap();
let mut rng = thread_rng();
for _ in 0..20 {
let color_cmd = vec![0x56, rng.gen(), rng.gen(), rng.gen(), 0x00, 0xF0, 0xAA];
light.command(&cmd_char, &color_cmd).unwrap();
thread::sleep(Duration::from_millis(200));
}
}