bikeshedder / sunspec

Rust crate for accessing SunSpec compliant devices in a safe and convenient way.
Apache License 2.0
4 stars 3 forks source link
rust sunspec

SunSpec Rust Implementation

Latest Version Unsafe forbidden

This Rust crate contains code for accessing SunSpec compliant devices in a safe and convenient way.

Highlights

Nested and repeating groups are not supported, yet.

Features

Feature Description Extra dependencies Default
tokio Enable tokio_modbus support tokio-modbus, tokio/time yes
serde Enable serde support serde, bitflags/serde yes

Examples

The examples directory in the code repository contains the unabridged code.

Example code for accessing data from a three phase inverter using the model 103

use std::{error::Error, net::SocketAddr, time::Duration};

use clap::Parser;
use itertools::Itertools;
use sunspec::{
    tokio_modbus::{discover_models, read_model},
    Config,
};
use tokio::time::sleep;
use tokio_modbus::{client::tcp::connect_slave, Slave};

#[derive(Parser)]
struct Args {
    addr: SocketAddr,
    device_id: u8,
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let args = Args::parse();
    let mut ctx = connect_slave(args.addr, Slave(args.device_id)).await?;

    let cfg = Config::default();
    let models = discover_models(&mut ctx, &cfg).await?.models;
    let m1 = read_model(&mut ctx, models.m1, &cfg).await?;

    println!("Manufacturer: {}", m1.mn);
    println!("Model: {}", m1.md);
    println!("Version: {}", m1.vr.as_deref().unwrap_or("(unspecified)"));
    println!("Serial Number: {}", m1.sn);

    println!(
        "Supported models: {}",
        models
            .supported_model_ids()
            .iter()
            .map(|id| id.to_string())
            .join(", ")
    );

    loop {
        let m103 = read_model(&mut ctx, models.m103, &cfg).await?;
        let w = m103.w as f32 * 10f32.powf(m103.w_sf.into());
        let wh = m103.wh as f32 * 10f32.powf(m103.wh_sf.into());
        println!("{:12.3} kWh {:9.3} kW", wh / 1000.0, w / 1000.0,);
        sleep(Duration::from_secs(1)).await;
    }
}

FAQ

How does this crate differ from crates like tokio-sunspec, sunspec-models, sunspec_rs?

License

Licensed under either of

at your option.