example/
example.rs

1use bluetooth_serial_port::{BtProtocol, BtSocket};
2use mio::{Poll, PollOpt, Ready, Token};
3use std::{
4    io::{Read, Write},
5    time,
6};
7
8fn main() {
9    // scan for devices
10    let devices = bluetooth_serial_port::scan_devices(time::Duration::from_secs(20)).unwrap();
11    if devices.len() == 0 {
12        panic!("No devices found");
13    }
14
15    println!("Found bluetooth devices {:?}", devices);
16
17    // "device.addr" is the MAC address of the device
18    let device = &devices[0];
19    println!(
20        "Connecting to `{}` ({})",
21        device.name,
22        device.addr.to_string()
23    );
24
25    // create and connect the RFCOMM socket
26    let mut socket = BtSocket::new(BtProtocol::RFCOMM).unwrap();
27    socket.connect(device.addr).unwrap();
28
29    // BtSocket implements the `Read` and `Write` traits (they're blocking)
30    let mut buffer = [0; 10];
31    let num_bytes_read = socket.read(&mut buffer[..]).unwrap();
32    let num_bytes_written = socket.write(&buffer[0..num_bytes_read]).unwrap();
33    println!(
34        "Read `{}` bytes, wrote `{}` bytes",
35        num_bytes_read, num_bytes_written
36    );
37
38    // BtSocket also implements `mio::Evented` for async IO
39    let poll = Poll::new().unwrap();
40    poll.register(
41        &socket,
42        Token(0),
43        Ready::readable() | Ready::writable(),
44        PollOpt::edge() | PollOpt::oneshot(),
45    )
46    .unwrap();
47    // loop { ... poll events and wait for socket to be readable/writable ... }
48}