Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
<!-- markdownlint-disable MD024 -->
# Changelog

All notable changes to this project will be documented in this file.
Expand All @@ -7,6 +8,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Added

- Add support for nested and repeating groups
- Add `examples/model712` showing how to read model 712 from a device

### Changed

- Update `strum` to version `0.27`
Expand Down
11 changes: 11 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 6 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -29,4 +29,9 @@ tokio-modbus = { version = "0.16", optional = true }
serde_json = "1.0.114"

[workspace]
members = ["sunspec-gen", "examples/readme", "examples/model103"]
members = [
"sunspec-gen",
"examples/readme",
"examples/model103",
"examples/model712",
]
16 changes: 7 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,23 +16,21 @@ in a safe and convenient way.
- [x] All communication is abstracted via traits making it runtime agnostic
- [x] Supports Modbus TCP and RTU (via [tokio-modbus](https://crates.io/crates/tokio-modbus)).
- [x] Implements "Device Information Model Discovery" as
defined in the SunSpec specification.
defined in the SunSpec specification.
- [x] Fully typed models generated from the JSON files contained in the
[SunSpec models repository](https://github.com/sunspec/models/)
[SunSpec models repository](https://github.com/sunspec/models/)
- [x] Fully typed enums
- [x] Fully typed bitfields
- [x] Fully documented. Even the generated models.
- [x] Reading of complete models in a single request.

| ⚠️ Nested and repeating groups are not supported, yet. |
| ---- |
- [x] Supports nested and repeating groups.

## Features

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

## Examples

Expand Down
14 changes: 14 additions & 0 deletions examples/model712/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
[package]
name = "sunspec-example-model712"
version = "0.1.0"
edition = "2021"
publish = false

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
tokio = { version = "1.33.0", features = ["rt-multi-thread", "macros", "time"] }
tokio-modbus = { version = "0.16", features = ["tcp"] }
sunspec = { path = "../../" }
clap = { version = "4.4.7", features = ["derive"] }
itertools = "0.14.0"
10 changes: 10 additions & 0 deletions examples/model712/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# Model 712 example

This code connects to a device that supports sunspec via modbus TCP and
outputs the contents of model 1 and then proceeds reading model 712.

Usage example:

```
$ cargo run 192.168.178.38:1502 1
```
71 changes: 71 additions & 0 deletions examples/model712/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
use std::{error::Error, net::SocketAddr, time::Duration};

use clap::Parser;
use itertools::Itertools;
use sunspec::{
client::{AsyncClient, Config},
models::{model1::Model1, model712::Model712},
DEFAULT_DISCOVERY_ADDRESSES,
};
use tokio_modbus::{client::tcp::connect_slave, Slave};

#[derive(Parser)]
struct Args {
addr: SocketAddr,
device_id: u8,
#[arg(
long,
short='d',
help = "Discovery addresses",
name = "ADDRESS",
default_values_t = DEFAULT_DISCOVERY_ADDRESSES
)]
discovery_addresses: Vec<u16>,
#[arg(
long,
short = 't',
help = "Read timeout in seconds",
name = "SECONDS",
default_value_t = 1.0
)]
read_timeout: f32,
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let args = Args::parse();

let client = AsyncClient::new(
connect_slave(args.addr, Slave(args.device_id)).await?,
Config {
discovery_addresses: args.discovery_addresses,
read_timeout: (args.read_timeout != 0.0)
.then(|| Duration::from_secs_f32(args.read_timeout)),
..Default::default()
},
);

let device = client.device(args.device_id).await?;

let m1: Model1 = device.read_model().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: {}",
device
.models
.supported_model_ids()
.iter()
.map(|id| id.to_string())
.join(", ")
);

let m712: Model712 = device.read_model().await?;
println!("{:?}", m712);

Ok(())
}
2 changes: 1 addition & 1 deletion src/client/async.rs
Original file line number Diff line number Diff line change
Expand Up @@ -289,7 +289,7 @@ async fn read_model<M: Model>(
}
data
};
Ok(M::from_data(&data)?)
Ok(M::parse(&data)?)
}

/// Read data for a single point. Please note that
Expand Down
5 changes: 5 additions & 0 deletions src/group.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
/// Every group and model implements this trait.
pub trait Group: Sized {
/// Group length (without nested and repeating groups)
const LEN: u16;
}
2 changes: 2 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
)]

pub use constants::{DEFAULT_DISCOVERY_ADDRESSES, SUNS_IDENTIFIER};
pub use group::Group;
pub use model::{Model, ModelAddr};
pub use models::Models;
pub use point::Point;
Expand All @@ -29,6 +30,7 @@ pub use value::{DecodeError, FixedSize, Value};
/// This module contains all client specific code.
pub mod client;
mod constants;
mod group;
mod model;
/// This module contains all the genererated SunSpec models.
pub mod models;
Expand Down
10 changes: 5 additions & 5 deletions src/model.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
use std::marker::PhantomData;

use crate::{DecodeError, Models};
use crate::{DecodeError, Group, Models};

/// Every model implements this trait which contains methods
/// for accessing
pub trait Model: Sized {
/// for accessing the address and parsing the model.
pub trait Model: Sized + Group {
/// Model ID
const ID: u16;
/// Parse model points from a given u16 slice
fn from_data(data: &[u16]) -> Result<Self, DecodeError>;
/// Get model address from discovered models struct
fn addr(models: &Models) -> ModelAddr<Self>;
/// Parse model data from a given u16 slice
fn parse(data: &[u16]) -> Result<Self, DecodeError>;
}

/// This structure is used to store the address of
Expand Down
41 changes: 28 additions & 13 deletions src/models/model1.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
//! Common
/// Type alias for [`Common`].
pub type Model1 = Common;
/// Common
///
/// All SunSpec compliant devices must include this as the first model
#[derive(Debug)]
#[cfg_attr(feature = "serde", derive(::serde::Serialize, ::serde::Deserialize))]
pub struct Model1 {
pub struct Common {
/// Manufacturer
///
/// Well known value registered with SunSpec for compliance
Expand Down Expand Up @@ -33,27 +35,40 @@ pub struct Model1 {
pub da: Option<u16>,
}
#[allow(missing_docs)]
impl Model1 {
impl Common {
pub const MN: crate::Point<Self, String> = crate::Point::new(0, 16, false);
pub const MD: crate::Point<Self, String> = crate::Point::new(16, 16, false);
pub const OPT: crate::Point<Self, Option<String>> = crate::Point::new(32, 8, false);
pub const VR: crate::Point<Self, Option<String>> = crate::Point::new(40, 8, false);
pub const SN: crate::Point<Self, String> = crate::Point::new(48, 16, false);
pub const DA: crate::Point<Self, Option<u16>> = crate::Point::new(64, 1, true);
}
impl crate::Model for Model1 {
const ID: u16 = 1;
fn from_data(data: &[u16]) -> Result<Self, crate::DecodeError> {
Ok(Self {
mn: Self::MN.from_data(data)?,
md: Self::MD.from_data(data)?,
opt: Self::OPT.from_data(data)?,
vr: Self::VR.from_data(data)?,
sn: Self::SN.from_data(data)?,
da: Self::DA.from_data(data)?,
})
impl crate::Group for Common {
const LEN: u16 = 66;
}
impl Common {
fn parse_group(data: &[u16]) -> Result<(&[u16], Self), crate::DecodeError> {
let nested_data = &data[usize::from(<Self as crate::Group>::LEN)..];
Ok((
nested_data,
Self {
mn: Self::MN.from_data(data)?,
md: Self::MD.from_data(data)?,
opt: Self::OPT.from_data(data)?,
vr: Self::VR.from_data(data)?,
sn: Self::SN.from_data(data)?,
da: Self::DA.from_data(data)?,
},
))
}
}
impl crate::Model for Common {
const ID: u16 = 1;
fn addr(models: &crate::Models) -> crate::ModelAddr<Self> {
models.m1
}
fn parse(data: &[u16]) -> Result<Self, crate::DecodeError> {
let (_, model) = Self::parse_group(data)?;
Ok(model)
}
}
35 changes: 24 additions & 11 deletions src/models/model10.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,17 +24,20 @@ impl Model10 {
pub const CTL: crate::Point<Self, Option<u16>> = crate::Point::new(1, 1, true);
pub const TYP: crate::Point<Self, Option<Typ>> = crate::Point::new(2, 1, false);
}
impl crate::Model for Model10 {
const ID: u16 = 10;
fn from_data(data: &[u16]) -> Result<Self, crate::DecodeError> {
Ok(Self {
st: Self::ST.from_data(data)?,
ctl: Self::CTL.from_data(data)?,
typ: Self::TYP.from_data(data)?,
})
}
fn addr(models: &crate::Models) -> crate::ModelAddr<Self> {
models.m10
impl crate::Group for Model10 {
const LEN: u16 = 4;
}
impl Model10 {
fn parse_group(data: &[u16]) -> Result<(&[u16], Self), crate::DecodeError> {
let nested_data = &data[usize::from(<Self as crate::Group>::LEN)..];
Ok((
nested_data,
Self {
st: Self::ST.from_data(data)?,
ctl: Self::CTL.from_data(data)?,
typ: Self::TYP.from_data(data)?,
},
))
}
}
/// Interface Status
Expand Down Expand Up @@ -125,3 +128,13 @@ impl crate::Value for Option<Typ> {
}
}
}
impl crate::Model for Model10 {
const ID: u16 = 10;
fn addr(models: &crate::Models) -> crate::ModelAddr<Self> {
models.m10
}
fn parse(data: &[u16]) -> Result<Self, crate::DecodeError> {
let (_, model) = Self::parse_group(data)?;
Ok(model)
}
}
Loading
Loading