#cbor #no-std #sen-ml

无std senml-deser

基于SenML规范的序列化和反序列化库

1个不稳定版本

0.2.1 2024年2月16日

#1617嵌入式开发

OLFL-1.3

56KB
1K SLoC

SenML DeSer

SenML 反序列化和序列化 [无std]

传感器测量列表(SenML)实现(不需要 std 也不需要 alloc)。有关SenML的详细信息,请参阅 REF8428

目前,唯一支持的序列化格式是 CBOR

使用方法

使用 Record 结构和可以持有多个 Record 实例的 Pack 来进行序列化。为了成功序列化,请确保已设置 base_namename 字段。

use senml_deser::{
    content::{record::Record, record::Values, pack::Pack},
    deser::ser::Encoder,
    Cbor
};

fn main() {
    // creating the pack
    let mut pack = Pack::<Cbor>::new();

    // Create a common Record that can hold any SenML fields
    let record = Record::<Cbor>{
        base_name: Some("device/instance0/"),
        name: Some("manufacturer"),
        value: Some(Values::StringValue("Fraunhofer-IML")),
        ..Default::default()
    };

    pack.add_record(record).unwrap();

    // Use convenience function to directly add common name/value records
    pack.add_string_value_record("version", "1.0").unwrap();
    pack.add_value_record("battery_level", 42_f64).unwrap();

    // Crate the encoder and encode the pack
    let mut buf = [0_u8; 1024];
    let mut encoder = Encoder::new(&mut buf);

    // Get the encoded bytes
    if let Ok(encoded_data) = encoder.cbor_encode(pack) {
        println!(
            "encoded:\n{:02x?}\nlength: {}\n",
            encoded_data,
            encoded_data.len()
        );
    }
}

反序列化工作方式类似

use senml_deser::{content::pack::Pack, deser::de::Decoder};

fn main() {
    // Have the encoded data
    let encoded_data: &[u8] = &[
        0x83, 0xa3, 0x21, 0x71, 0x64, 0x65, 0x76, 0x69, 0x63, 0x65, 0x2f, 0x69, 0x6e, 0x73, 0x74,
        0x61, 0x6e, 0x63, 0x65, 0x30, 0x2f, 0x00, 0x6c, 0x6d, 0x61, 0x6e, 0x75, 0x66, 0x61, 0x63,
        0x74, 0x75, 0x72, 0x65, 0x72, 0x03, 0x6e, 0x46, 0x72, 0x61, 0x75, 0x6e, 0x68, 0x6f, 0x66,
        0x65, 0x72, 0x2d, 0x49, 0x4d, 0x4c, 0xa2, 0x00, 0x67, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f,
        0x6e, 0x03, 0x63, 0x31, 0x2e, 0x30, 0xa2, 0x00, 0x6d, 0x62, 0x61, 0x74, 0x74, 0x65, 0x72,
        0x79, 0x5f, 0x6c, 0x65, 0x76, 0x65, 0x6c, 0x02, 0x18, 0x2a,
    ];
    // Create the Decoder
    let mut decoder = Decoder::new();
    // We need to provide a scratch array for the decoder
    let mut scratch = [0_u8; 1024];
    // Deserialize the data
    let decoded_record_list= decoder.decode_cbor(encoded_data, &mut scratch).unwrap();
    // The Package supplies a EntryIterator to iterate over the decoded entries
    for record in decoded_record_list.records_iter() {
        // Note that the decoded entries will always have the full path/name (base_name + name)
        println!("{record:?}");
    }
}

许可证

开放物流基金会许可证版本1.3,2023年1月

请参阅顶级目录中的 LICENSE 文件。

联系方式

弗劳恩霍费尔IML嵌入式Rust小组 - [email protected]

依赖项

~1.4–2MB
~45K SLoC