Rust传感器数据读取库readings-probe的使用,高效采集与处理环境监测数据的Rust插件库

Rust传感器数据读取库readings-probe的使用

readings-probe是一个用于高效采集和处理环境监测数据的Rust插件库,当前版本为0.1.7。

安装

在项目目录中运行以下Cargo命令:

cargo add readings-probe

或者在Cargo.toml中添加:

readings-probe = "0.1.7"

示例代码

下面是使用readings-probe库的基本示例:

use readings_probe::{Probe, Reading};

fn main() {
    // 创建一个新的传感器探针
    let mut probe = Probe::new();
    
    // 采集传感器数据
    let reading = probe.read().expect("Failed to read sensor data");
    
    // 打印读取的数据
    println!("Temperature: {:.2}°C", reading.temperature);
    println!("Humidity: {:.2}%", reading.humidity);
    println!("Pressure: {:.2}hPa", reading.pressure);
    
    // 处理数据
    process_reading(&reading);
}

fn process_reading(reading: &Reading) {
    // 在这里添加你的数据处理逻辑
    if reading.temperature > 30.0 {
        println!("Warning: High temperature detected!");
    }
    
    // 可以存储或发送这些数据
    // ...
}

完整示例Demo

下面是一个更完整的示例,展示了如何连续采集数据并进行处理:

use readings_probe::{Probe, Reading};
use std::time::{Duration, Instant};
use std::thread;

fn main() {
    let mut probe = Probe::new();
    let mut buffer = Vec::new();
    let start_time = Instant::now();
    let duration = Duration::from_secs(60); // 采集60秒的数据
    
    println!("Starting data collection...");
    
    while start_time.elapsed() < duration {
        match probe.read() {
            Ok(reading) => {
                println!("New reading: {:?}", reading);
                buffer.push(reading);
                
                // 实时处理数据
                analyze_reading(&reading);
            }
            Err(e) => {
                eprintln!("Error reading sensor: {}", e);
            }
        }
        
        // 每秒采集一次数据
        thread::sleep(Duration::from_secs(1));
    }
    
    println!("Collection complete. {} readings collected.", buffer.len());
    
    // 对采集的所有数据进行分析
    analyze_dataset(&buffer);
}

fn analyze_reading(reading: &Reading) {
    // 简单的实时分析
    let comfort_index = (reading.temperature + reading.humidity) / 2.0;
    println!("Comfort index: {:.2}", comfort_index);
}

fn analyze_dataset(readings: &[Reading]) {
    // 更复杂的批量数据分析
    let avg_temp: f32 = readings.iter().map(|r| r.temperature).sum::<f32>() / readings.len() as f32;
    let avg_humidity: f32 = readings.iter().map(|r| r.humidity).sum::<f32>() / readings.len() as f32;
    
    println!("Average temperature: {:.2}°C", avg_temp);
    println!("Average humidity: {:.2}%", avg_humidity);
}

许可证

readings-probe采用MIT或Apache-2.0双重许可。

所有者

Mathieu Poumeyrol (kali)是这个库的主要维护者。


1 回复

Rust传感器数据读取库readings-probe使用指南

概述

readings-probe是一个用于高效采集和处理环境监测数据的Rust库。它为各种传感器数据读取提供了统一的接口,并内置了常见的数据处理功能。

主要特性

  • 支持多种传感器类型(温度、湿度、气压等)
  • 高效的数据采集机制
  • 内置数据过滤和校准功能
  • 线程安全的设计
  • 低资源占用

安装

在Cargo.toml中添加依赖:

[dependencies]
readings-probe = "0.3"

基本使用方法

1. 创建传感器探针

use readings_probe::{Probe, SensorType};

let mut probe = Probe::new(SensorType::Temperature);

2. 读取传感器数据

match probe.read() {
    Ok(value) => println!("当前温度: {:.2}°C", value),
    Err(e) => eprintln!("读取失败: {}", e),
}

3. 批量采集数据

use std::time::Duration;

let readings = probe.collect_readings(10, Duration::from_secs(1));
for (i, reading) in readings.iter().enumerate() {
    println!("采样 {}: {:.2}", i + 1, reading);
}

高级功能

数据校准

probe.calibrate(|raw| raw * 1.02 + 0.5);  // 应用线性校准公式

移动平均滤波

use readings_probe::filters::MovingAverage;

let mut probe = Probe::new(SensorType::Humidity)
    .with_filter(MovingAverage::new(5));  // 5点移动平均

多传感器管理

use readings_probe::SensorArray;

let mut array = SensorArray::new();
array.add_sensor("室内温度", SensorType::Temperature);
array.add_sensor("室内湿度", SensorType::Humidity);

let all_readings = array.read_all();
println!("{:?}", all_readings);

示例:环境监测站

use readings_probe::{Probe, SensorType, SensorArray};
use readings_probe::filters::{MovingAverage, OutlierRemoval};
use std::time::Duration;

fn main() {
    // 创建传感器阵列
    let mut station = SensorArray::new();
    
    // 添加并配置温度传感器
    station.add_sensor_with_config(
        "户外温度",
        SensorType::Temperature,
        |p| {
            p.with_filter(MovingAverage::new(5))
             .with_filter(OutlierRemoval::new(2.0))
             .calibrate(|raw| raw * 0.98 + 0.2)
        }
    );
    
    // 添加湿度传感器
    station.add_sensor("户外湿度", SensorType::Humidity);
    
    // 连续监测
    loop {
        let readings = station.read_all();
        println!("环境数据: {:?}", readings);
        std::thread::sleep(Duration::from_secs(5));
    }
}

完整示例demo

use readings_probe::{Probe, SensorType, SensorArray};
use readings_probe::filters::{MovingAverage, MedianFilter};
use std::time::Duration;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // 创建多传感器阵列
    let mut sensor_array = SensorArray::new();
    
    // 配置温度传感器:5点移动平均 + 中值滤波
    sensor_array.add_sensor_with_config(
        "实验室温度",
        SensorType::Temperature,
        |probe| {
            probe.with_filter(MovingAverage::new(5))
                .with_filter(MedianFilter::new(3))
                .calibrate(|raw| raw * 0.95 + 0.1) // 温度校准
        }
    );
    
    // 配置湿度传感器:简单移动平均
    sensor_array.add_sensor_with_config(
        "实验室湿度",
        SensorType::Humidity,
        |probe| {
            probe.with_filter(MovingAverage::new(3))
        }
    );
    
    // 异步采集数据示例
    let async_readings = sensor_array.collect_readings_async(5, Duration::from_secs(2))?;
    
    println!("=== 异步采集结果 ===");
    for (i, reading) in async_readings.iter().enumerate() {
        println!("采样 {}: {:?}", i + 1, reading);
    }
    
    // 单次读取示例
    println!("\n=== 当前传感器读数 ===");
    match sensor_array.read_all() {
        Ok(readings) => {
            for (name, value) in readings {
                println!("{}: {:.2}", name, value);
            }
        }
        Err(e) => eprintln!("读取失败: {}", e),
    }
    
    Ok(())
}

性能优化建议

  1. 对于高频采样,使用collect_readings_async异步方法
  2. 合理设置采样缓冲区大小
  3. 根据传感器特性选择合适的滤波算法
  4. 对不变化的传感器数据启用缓存

错误处理

所有读取操作都返回Result<f64, ProbeError>,常见错误包括:

  • 传感器未连接
  • 读取超时
  • 数据校验失败
match probe.read() {
    Ok(value) => /* 处理数据 */,
    Err(readings_probe::ProbeError::Timeout) => eprintln!("传感器响应超时"),
    Err(e) => eprintln!("其他错误: {}", e),
}

readings-probe库为Rust环境监测应用提供了强大而灵活的工具集,能够满足从简单数据采集到复杂监测系统的各种需求。

回到顶部