Rust和设备交互通讯,将设备的数据写入数据库里面
use serialport::{DataBits, Parity, StopBits, SerialPortSettings, Error};
use rusqlite::{params, Connection, Result};
use std::io::prelude::*;
fn main() -> Result<(), Box<dyn std::error::Error>> {
// 连接到数据库
let conn = Connection::open("data.db")?;
conn.execute(
"CREATE TABLE IF NOT EXISTS device_data (
id INTEGER PRIMARY KEY,
data TEXT
)",
params![],
)?;
// 配置串口参数
let mut settings = SerialPortSettings::default();
settings.baud_rate = 9600;
settings.data_bits = DataBits::Eight;
settings.parity = Parity::None;
settings.stop_bits = StopBits::One;
// 打开串口
let port = serialport::open("/dev/ttyUSB0")?;
port.set_timeout(std::time::Duration::from_millis(1000))?;
port.configure(&settings)?;
// 读取设备数据并写入数据库
let mut buffer: Vec<u8> = vec![0; 1024];
loop {
match port.read(buffer.as_mut_slice()) {
Ok(t) => {
if t > 0 {
let data = String::from_utf8_lossy(&buffer[..t]);
println!("Received data: {}", data);
// 将数据写入数据库
conn.execute(
"INSERT INTO device_data (data) VALUES (?1)",
params![data],
)?;
}
}
Err(ref e) if e.kind() == ErrorKind::Timeout => (),
Err(e) => eprintln!("{:?}", e),
}
}
}