diff --git a/.editorconfig b/.editorconfig index 854d6f3..d9d66d5 100644 --- a/.editorconfig +++ b/.editorconfig @@ -5,7 +5,6 @@ indent_style = space indent_size = 4 charset = utf-8 trim_trailing_whitespace = false -insert_final_newline = false [*.md] trim_trailing_whitespace = false diff --git a/Cargo.lock b/Cargo.lock index 2cb9685..8da7300 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -106,7 +106,7 @@ dependencies = [ "regex", "rustc-hash", "shlex", - "syn 2.0.61", + "syn 2.0.110", "which", ] @@ -134,14 +134,36 @@ dependencies = [ "wyz", ] +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + [[package]] name = "can-dbc" -version = "6.0.0" +version = "8.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cbe0d033ec316c3bb50e2e53d7ef3d8805e65c5f976d49daea65a12f7e0f9ce8" +checksum = "5dbfd754b95a7c0b9d8a1baa8d4e427b49f491686c6e45c3e7b6b5e3bc6bf798" dependencies = [ - "derive-getters", - "nom", + "can-dbc-pest", + "encoding_rs", + "serde", + "thiserror 2.0.17", +] + +[[package]] +name = "can-dbc-pest" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70d4baf7c06ef884041a7fc2fbad73372fd4b7c1b5d1d3c009f0d96b6f0b0f3f" +dependencies = [ + "encoding_rs", + "pest", + "pest_derive", ] [[package]] @@ -238,7 +260,7 @@ dependencies = [ "heck 0.5.0", "proc-macro2", "quote", - "syn 2.0.61", + "syn 2.0.110", ] [[package]] @@ -253,6 +275,25 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b6a852b24ab71dffc585bcb46eaf7959d175cb865a7152e35b348d1b2960422" +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + [[package]] name = "dbc-codegen" version = "0.3.0" @@ -295,7 +336,7 @@ dependencies = [ "proc-macro-error", "proc-macro2", "quote", - "syn 2.0.61", + "syn 2.0.110", ] [[package]] @@ -304,18 +345,17 @@ version = "0.3.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ff4a5fefe330e8d7f31b16a318f9ce81000d8e35e69b93eae154d16d2278f70f" dependencies = [ - "thiserror", + "thiserror 1.0.65", ] [[package]] -name = "derive-getters" -version = "0.3.0" +name = "digest" +version = "0.10.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a2c35ab6e03642397cdda1dd58abbc05d418aef8e36297f336d5aba060fe8df" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ - "proc-macro2", - "quote", - "syn 1.0.109", + "block-buffer", + "crypto-common", ] [[package]] @@ -333,6 +373,15 @@ dependencies = [ "nb", ] +[[package]] +name = "encoding_rs" +version = "0.8.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75030f3c4f45dafd7586dd6780965a8c7e8e285a5ecb86713e63a79c5b2766f3" +dependencies = [ + "cfg-if", +] + [[package]] name = "errno" version = "0.3.9" @@ -355,6 +404,16 @@ version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c" +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + [[package]] name = "glob" version = "0.3.1" @@ -411,9 +470,9 @@ checksum = "830d08ce1d1d941e6b30645f1a0eb5643013d835ce3779a5fc208261dbe10f55" [[package]] name = "libc" -version = "0.2.154" +version = "0.2.177" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae743338b92ff9146ce83992f766a31066a91a8c84a45e0e9f21e7cf6de6d346" +checksum = "2874a2af47a2325c2001a6e6fad9b16a53b802102b528163885171cf92b15976" [[package]] name = "libloading" @@ -480,6 +539,49 @@ version = "1.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3fdb12b2476b595f9358c5161aa467c2438859caa136dec86c26fdd2efe17b92" +[[package]] +name = "pest" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "989e7521a040efde50c3ab6bbadafbe15ab6dc042686926be59ac35d74607df4" +dependencies = [ + "memchr", + "ucd-trie", +] + +[[package]] +name = "pest_derive" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "187da9a3030dbafabbbfb20cb323b976dc7b7ce91fcd84f2f74d6e31d378e2de" +dependencies = [ + "pest", + "pest_generator", +] + +[[package]] +name = "pest_generator" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "49b401d98f5757ebe97a26085998d6c0eecec4995cad6ab7fc30ffdf4b052843" +dependencies = [ + "pest", + "pest_meta", + "proc-macro2", + "quote", + "syn 2.0.110", +] + +[[package]] +name = "pest_meta" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f27a2cfee9f9039c4d86faa5af122a0ac3851441a34865b8a043b46be0065a" +dependencies = [ + "pest", + "sha2", +] + [[package]] name = "prettyplease" version = "0.2.20" @@ -487,7 +589,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5f12335488a2f3b0a83b14edad48dca9879ce89b2edd10e80237e4e852dd645e" dependencies = [ "proc-macro2", - "syn 2.0.61", + "syn 2.0.110", ] [[package]] @@ -516,9 +618,9 @@ dependencies = [ [[package]] name = "proc-macro2" -version = "1.0.82" +version = "1.0.103" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ad3d49ab951a01fbaafe34f2ec74122942fe18a3f9814c3268f1bb72042131b" +checksum = "5ee95bc4ef87b8d5ba32e8b7714ccc834865276eab0aed5c9958d00ec45f49e8" dependencies = [ "unicode-ident", ] @@ -595,6 +697,37 @@ dependencies = [ "windows-sys", ] +[[package]] +name = "serde" +version = "1.0.210" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8e3592472072e6e22e0a54d5904d9febf8508f65fb8552499a1abc7d1078c3a" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.210" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "243902eda00fad750862fc144cea25caca5e20d615af0a81bee94ca738f1df1f" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.110", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + [[package]] name = "shlex" version = "1.3.0" @@ -614,15 +747,14 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" dependencies = [ "proc-macro2", - "quote", "unicode-ident", ] [[package]] name = "syn" -version = "2.0.61" +version = "2.0.110" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c993ed8ccba56ae856363b1845da7266a7cb78e1d146c8a32d54b45a8b831fc9" +checksum = "a99801b5bd34ede4cf3fc688c5919368fea4e4814a4664359503e6015b280aea" dependencies = [ "proc-macro2", "quote", @@ -641,7 +773,16 @@ version = "1.0.65" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5d11abd9594d9b38965ef50805c5e469ca9cc6f197f883f717e0269a3057b3d5" dependencies = [ - "thiserror-impl", + "thiserror-impl 1.0.65", +] + +[[package]] +name = "thiserror" +version = "2.0.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f63587ca0f12b72a0600bcba1d40081f830876000bb46dd2337a3051618f4fc8" +dependencies = [ + "thiserror-impl 2.0.17", ] [[package]] @@ -652,7 +793,18 @@ checksum = "ae71770322cbd277e69d762a16c444af02aa0575ac0d174f0b9562d3b37f8602" dependencies = [ "proc-macro2", "quote", - "syn 2.0.61", + "syn 2.0.110", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ff15c8ecd7de3849db632e14d18d2571fa09dfc5ed93479bc4485c7a517c913" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.110", ] [[package]] @@ -672,9 +824,21 @@ checksum = "1f718dfaf347dcb5b983bfc87608144b0bad87970aebcbea5ce44d2a30c08e63" dependencies = [ "proc-macro2", "quote", - "syn 2.0.61", + "syn 2.0.110", ] +[[package]] +name = "typenum" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "562d481066bde0658276a35467c4af00bdc6ee726305698a55b86e61d7ad82bb" + +[[package]] +name = "ucd-trie" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2896d95c02a80c6d6a5d6e953d479f5ddf2dfdb6a244441010e373ac0fb88971" + [[package]] name = "unicode-ident" version = "1.0.12" diff --git a/Cargo.toml b/Cargo.toml index c651a90..f6d7f2f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,13 +12,13 @@ license = "MIT OR Apache-2.0" readme = "README.md" repository = "https://github.com/technocreatives/dbc-codegen" homepage = "https://github.com/technocreatives/dbc-codegen" -rust-version = "1.78.0" +rust-version = "1.81.0" [features] std = [] [dependencies] -can-dbc = "6.0.0" +can-dbc = "8.0.0" anyhow = "1.0.68" heck = "0.4.0" typed-builder = "0.18.0" diff --git a/dbc-codegen-cli/src/main.rs b/dbc-codegen-cli/src/main.rs index 02d05df..7905248 100644 --- a/dbc-codegen-cli/src/main.rs +++ b/dbc-codegen-cli/src/main.rs @@ -20,7 +20,7 @@ struct Cli { fn main() { let args = Cli::parse(); - let dbc_file = std::fs::read(&args.dbc_path).unwrap_or_else(|e| { + let dbc_file = std::fs::read_to_string(&args.dbc_path).unwrap_or_else(|e| { eprintln!("could not read `{}`: {}", args.dbc_path.display(), e); exit(exitcode::NOINPUT); }); diff --git a/rust-toolchain.toml b/rust-toolchain.toml deleted file mode 100644 index 5198580..0000000 --- a/rust-toolchain.toml +++ /dev/null @@ -1,2 +0,0 @@ -[toolchain] -channel = "1.78.0" diff --git a/src/lib.rs b/src/lib.rs index cb2c37f..dc9fc6f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -14,7 +14,7 @@ //! //! let config = Config::builder() //! .dbc_name("example.dbc") -//! .dbc_content(include_bytes!("../testing/dbc-examples/example.dbc")) +//! .dbc_content(include_str!("../testing/dbc-examples/example.dbc")) //! //.impl_arbitrary(FeatureConfig::Gated("arbitrary")) // optional //! //.impl_debug(FeatureConfig::Always) // optional //! .build(); @@ -27,7 +27,7 @@ #![deny(clippy::arithmetic_side_effects)] use anyhow::{anyhow, ensure, Context, Result}; -use can_dbc::{Message, MultiplexIndicator, Signal, ValDescription, ValueDescription, DBC}; +use can_dbc::{Message, MultiplexIndicator, Signal, ValDescription, ValueDescription, Dbc}; use heck::{ToPascalCase, ToSnakeCase}; use pad::PadAdapter; use std::cmp::{max, min}; @@ -50,7 +50,7 @@ pub struct Config<'a> { pub dbc_name: &'a str, /// Raw bytes of a dbc-file. - pub dbc_content: &'a [u8], + pub dbc_content: &'a str, /// Optional: Print debug info to stdout while generating code. Default: `false`. #[builder(default)] @@ -109,7 +109,7 @@ pub enum FeatureConfig<'a> { /// Write Rust structs matching DBC input description to `out` buffer pub fn codegen(config: Config<'_>, out: impl Write) -> Result<()> { - let dbc = can_dbc::DBC::from_slice(config.dbc_content).map_err(|e| { + let dbc = can_dbc::Dbc::try_from(config.dbc_content).map_err(|e| { let msg = "Could not parse dbc file"; if config.debug_prints { anyhow!("{}: {:#?}", msg, e) @@ -147,7 +147,7 @@ pub fn codegen(config: Config<'_>, out: impl Write) -> Result<()> { config.dbc_name )?; writeln!(&mut w, "//!")?; - writeln!(&mut w, "//! - Version: `{:?}`", dbc.version())?; + writeln!(&mut w, "//! - Version: `{:?}`", dbc.version)?; writeln!(&mut w)?; writeln!(&mut w, "use core::ops::BitOr;")?; writeln!(&mut w, "use bitvec::prelude::*;")?; @@ -177,19 +177,19 @@ pub fn codegen(config: Config<'_>, out: impl Write) -> Result<()> { Ok(()) } -fn render_dbc(mut w: impl Write, config: &Config<'_>, dbc: &DBC) -> Result<()> { +fn render_dbc(mut w: impl Write, config: &Config<'_>, dbc: &Dbc) -> Result<()> { render_root_enum(&mut w, dbc, config)?; for msg in get_relevant_messages(dbc) { render_message(&mut w, config, msg, dbc) - .with_context(|| format!("write message `{}`", msg.message_name()))?; + .with_context(|| format!("write message `{}`", msg.name))?; writeln!(w)?; } Ok(()) } -fn render_root_enum(mut w: impl Write, dbc: &DBC, config: &Config<'_>) -> Result<()> { +fn render_root_enum(mut w: impl Write, dbc: &Dbc, config: &Config<'_>) -> Result<()> { writeln!(w, "/// All messages")?; writeln!(w, "#[derive(Clone)]")?; config.impl_debug.fmt_attr(&mut w, "derive(Debug)")?; @@ -202,8 +202,8 @@ fn render_root_enum(mut w: impl Write, dbc: &DBC, config: &Config<'_>) -> Result { let mut w = PadAdapter::wrap(&mut w); for msg in get_relevant_messages(dbc) { - writeln!(w, "/// {}", msg.message_name())?; - writeln!(w, "{0}({0}),", type_name(msg.message_name()))?; + writeln!(w, "/// {}", &msg.name)?; + writeln!(w, "{0}({0}),", type_name(&msg.name))?; } } writeln!(&mut w, "}}")?; @@ -228,7 +228,7 @@ fn render_root_enum(mut w: impl Write, dbc: &DBC, config: &Config<'_>) -> Result writeln!( w, "{0}::MESSAGE_ID => Messages::{0}({0}::try_from(payload)?),", - type_name(msg.message_name()) + type_name(&msg.name) )?; } writeln!(w, r#"id => return Err(CanError::UnknownMessageId(id)),"#)?; @@ -245,18 +245,18 @@ fn render_root_enum(mut w: impl Write, dbc: &DBC, config: &Config<'_>) -> Result Ok(()) } -fn render_message(mut w: impl Write, config: &Config<'_>, msg: &Message, dbc: &DBC) -> Result<()> { - writeln!(w, "/// {}", msg.message_name())?; +fn render_message(mut w: impl Write, config: &Config<'_>, msg: &Message, dbc: &Dbc) -> Result<()> { + writeln!(w, "/// {}", msg.name)?; writeln!(w, "///")?; - match msg.message_id() { + match msg.id { can_dbc::MessageId::Standard(id) => writeln!(w, "/// - Standard ID: {0} (0x{0:x})", id), can_dbc::MessageId::Extended(id) => writeln!(w, "/// - Extended ID: {0} (0x{0:x})", id), }?; - writeln!(w, "/// - Size: {} bytes", msg.message_size())?; - if let can_dbc::Transmitter::NodeName(transmitter) = msg.transmitter() { + writeln!(w, "/// - Size: {} bytes", msg.size)?; + if let can_dbc::Transmitter::NodeName(transmitter) = &msg.transmitter { writeln!(w, "/// - Transmitter: {}", transmitter)?; } - if let Some(comment) = dbc.message_comment(*msg.message_id()) { + if let Some(comment) = dbc.message_comment(msg.id) { writeln!(w, "///")?; for line in comment.trim().lines() { writeln!(w, "/// {}", line)?; @@ -265,25 +265,25 @@ fn render_message(mut w: impl Write, config: &Config<'_>, msg: &Message, dbc: &D writeln!(w, "#[derive(Clone, Copy)]")?; config.impl_serde.fmt_attr(&mut w, "derive(Serialize)")?; config.impl_serde.fmt_attr(&mut w, "derive(Deserialize)")?; - writeln!(w, "pub struct {} {{", type_name(msg.message_name()))?; + writeln!(w, "pub struct {} {{", type_name(&msg.name))?; { let mut w = PadAdapter::wrap(&mut w); config .impl_serde .fmt_attr(&mut w, "serde(with = \"serde_bytes\")")?; - writeln!(w, "raw: [u8; {}],", msg.message_size())?; + writeln!(w, "raw: [u8; {}],", msg.size)?; } writeln!(w, "}}")?; writeln!(w)?; - writeln!(w, "impl {} {{", type_name(msg.message_name()))?; + writeln!(w, "impl {} {{", type_name(&msg.name))?; { let mut w = PadAdapter::wrap(&mut w); writeln!( &mut w, "pub const MESSAGE_ID: embedded_can::Id = {};", - match msg.message_id() { + match msg.id { // use StandardId::new().unwrap() once const_option is stable can_dbc::MessageId::Standard(id) => format!( "Id::Standard(unsafe {{ StandardId::new_unchecked({0:#x})}})", @@ -298,7 +298,7 @@ fn render_message(mut w: impl Write, config: &Config<'_>, msg: &Message, dbc: &D writeln!(w)?; for signal in msg - .signals() + .signals .iter() .filter(|sig| signal_to_rust_type(sig) != "bool") { @@ -306,7 +306,7 @@ fn render_message(mut w: impl Write, config: &Config<'_>, msg: &Message, dbc: &D writeln!( &mut w, "pub const {sig}_MIN: {typ} = {min}_{typ};", - sig = field_name(signal.name()).to_uppercase(), + sig = field_name(&signal.name).to_uppercase(), typ = typ, min = signal.min, )?; @@ -314,7 +314,7 @@ fn render_message(mut w: impl Write, config: &Config<'_>, msg: &Message, dbc: &D writeln!( &mut w, "pub const {sig}_MAX: {typ} = {max}_{typ};", - sig = field_name(signal.name()).to_uppercase(), + sig = field_name(&signal.name).to_uppercase(), typ = typ, max = signal.max, )?; @@ -324,18 +324,18 @@ fn render_message(mut w: impl Write, config: &Config<'_>, msg: &Message, dbc: &D writeln!( &mut w, "/// Construct new {} from values", - msg.message_name() + msg.name )?; let args: Vec = msg - .signals() + .signals .iter() .filter_map(|signal| { - if *signal.multiplexer_indicator() == MultiplexIndicator::Plain - || *signal.multiplexer_indicator() == MultiplexIndicator::Multiplexor + if signal.multiplexer_indicator == MultiplexIndicator::Plain + || signal.multiplexer_indicator == MultiplexIndicator::Multiplexor { Some(format!( "{}: {}", - field_name(signal.name()), + field_name(&signal.name), signal_to_rust_type(signal) )) } else { @@ -353,16 +353,16 @@ fn render_message(mut w: impl Write, config: &Config<'_>, msg: &Message, dbc: &D writeln!( &mut w, "let {}res = Self {{ raw: [0u8; {}] }};", - if msg.signals().is_empty() { "" } else { "mut " }, - msg.message_size() + if msg.signals.is_empty() { "" } else { "mut " }, + msg.size )?; - for signal in msg.signals().iter() { - if *signal.multiplexer_indicator() == MultiplexIndicator::Plain { - writeln!(&mut w, "res.set_{0}({0})?;", field_name(signal.name()))?; + for signal in msg.signals.iter() { + if signal.multiplexer_indicator == MultiplexIndicator::Plain { + writeln!(&mut w, "res.set_{0}({0})?;", field_name(&signal.name))?; } - if *signal.multiplexer_indicator() == MultiplexIndicator::Multiplexor { - writeln!(&mut w, "res.set_{0}({0})?;", field_name(signal.name()))?; + if signal.multiplexer_indicator == MultiplexIndicator::Multiplexor { + writeln!(&mut w, "res.set_{0}({0})?;", field_name(&signal.name))?; } } writeln!(&mut w, "Ok(res)")?; @@ -374,7 +374,7 @@ fn render_message(mut w: impl Write, config: &Config<'_>, msg: &Message, dbc: &D writeln!( &mut w, "pub fn raw(&self) -> &[u8; {}] {{", - msg.message_size() + msg.size )?; { let mut w = PadAdapter::wrap(&mut w); @@ -383,10 +383,10 @@ fn render_message(mut w: impl Write, config: &Config<'_>, msg: &Message, dbc: &D writeln!(&mut w, "}}")?; writeln!(w)?; - for signal in msg.signals().iter() { - match signal.multiplexer_indicator() { + for signal in msg.signals.iter() { + match signal.multiplexer_indicator { MultiplexIndicator::Plain => render_signal(&mut w, config, signal, dbc, msg) - .with_context(|| format!("write signal impl `{}`", signal.name()))?, + .with_context(|| format!("write signal impl `{}`", signal.name))?, MultiplexIndicator::Multiplexor => { render_multiplexor_signal(&mut w, config, signal, msg)? } @@ -402,7 +402,7 @@ fn render_message(mut w: impl Write, config: &Config<'_>, msg: &Message, dbc: &D writeln!( w, "impl core::convert::TryFrom<&[u8]> for {} {{", - type_name(msg.message_name()) + type_name(&msg.name) )?; { let mut w = PadAdapter::wrap(&mut w); @@ -418,13 +418,13 @@ fn render_message(mut w: impl Write, config: &Config<'_>, msg: &Message, dbc: &D writeln!( &mut w, r#"if payload.len() != {} {{ return Err(CanError::InvalidPayloadSize); }}"#, - msg.message_size() + msg.size )?; - writeln!(&mut w, "let mut raw = [0u8; {}];", msg.message_size())?; + writeln!(&mut w, "let mut raw = [0u8; {}];", msg.size)?; writeln!( &mut w, "raw.copy_from_slice(&payload[..{}]);", - msg.message_size() + msg.size )?; writeln!(&mut w, "Ok(Self {{ raw }})")?; } @@ -441,17 +441,17 @@ fn render_message(mut w: impl Write, config: &Config<'_>, msg: &Message, dbc: &D render_arbitrary(&mut w, config, msg)?; - let enums_for_this_message = dbc.value_descriptions().iter().filter_map(|x| { + let enums_for_this_message = dbc.value_descriptions.iter().filter_map(|x| { if let ValueDescription::Signal { message_id, - signal_name, + name, value_descriptions, } = x { - if message_id != msg.message_id() { + if *message_id != msg.id { return None; } - let signal = dbc.signal_by_name(*message_id, signal_name).unwrap(); + let signal = dbc.signal_by_name(*message_id, name).unwrap(); Some((signal, value_descriptions)) } else { None @@ -462,9 +462,9 @@ fn render_message(mut w: impl Write, config: &Config<'_>, msg: &Message, dbc: &D } let multiplexor_signal = msg - .signals() + .signals .iter() - .find(|s| *s.multiplexer_indicator() == MultiplexIndicator::Multiplexor); + .find(|s| s.multiplexer_indicator == MultiplexIndicator::Multiplexor); if let Some(multiplexor_signal) = multiplexor_signal { render_multiplexor_enums(w, config, dbc, msg, multiplexor_signal)?; @@ -477,11 +477,11 @@ fn render_signal( mut w: impl Write, config: &Config<'_>, signal: &Signal, - dbc: &DBC, + dbc: &Dbc, msg: &Message, ) -> Result<()> { - writeln!(w, "/// {}", signal.name())?; - if let Some(comment) = dbc.signal_comment(*msg.message_id(), signal.name()) { + writeln!(w, "/// {}", signal.name)?; + if let Some(comment) = dbc.signal_comment(msg.id, &signal.name) { writeln!(w, "///")?; for line in comment.trim().lines() { writeln!(w, "/// {}", line)?; @@ -490,16 +490,16 @@ fn render_signal( writeln!(w, "///")?; writeln!(w, "/// - Min: {}", signal.min)?; writeln!(w, "/// - Max: {}", signal.max)?; - writeln!(w, "/// - Unit: {:?}", signal.unit())?; - writeln!(w, "/// - Receivers: {}", signal.receivers().join(", "))?; + writeln!(w, "/// - Unit: {:?}", signal.unit)?; + writeln!(w, "/// - Receivers: {}", signal.receivers.join(", "))?; writeln!(w, "#[inline(always)]")?; - if let Some(variants) = dbc.value_descriptions_for_signal(*msg.message_id(), signal.name()) { + if let Some(variants) = dbc.value_descriptions_for_signal(msg.id, &signal.name) { let type_name = enum_name(msg, signal); writeln!( w, "pub fn {}(&self) -> {} {{", - field_name(signal.name()), + field_name(&signal.name), type_name, )?; { @@ -509,7 +509,7 @@ fn render_signal( _ => |x: f64| format!("{}", x), }; let mut w = PadAdapter::wrap(&mut w); - let read_fn = match signal.byte_order() { + let read_fn = match signal.byte_order { can_dbc::ByteOrder::LittleEndian => { let (start_bit, end_bit) = le_start_end_bit(signal, msg)?; @@ -538,20 +538,20 @@ fn render_signal( { let mut w = PadAdapter::wrap(&mut w); for variant in variants { - let literal = match_on_raw_type(*variant.a()); + let literal = match_on_raw_type(variant.id as f64); writeln!( &mut w, "{} => {}::{},", literal, type_name, - enum_variant_name(variant.b()) + enum_variant_name(&variant.description) )?; } writeln!( &mut w, "_ => {}::_Other(self.{}_raw()),", type_name, - field_name(signal.name()) + field_name(&signal.name) )?; } writeln!(&mut w, "}}")?; @@ -562,30 +562,30 @@ fn render_signal( writeln!( w, "pub fn {}(&self) -> {} {{", - field_name(signal.name()), + field_name(&signal.name), signal_to_rust_type(signal) )?; { let mut w = PadAdapter::wrap(&mut w); - writeln!(&mut w, "self.{}_raw()", field_name(signal.name()))?; + writeln!(&mut w, "self.{}_raw()", field_name(&signal.name))?; } writeln!(&mut w, "}}")?; writeln!(w)?; } - writeln!(w, "/// Get raw value of {}", signal.name())?; + writeln!(w, "/// Get raw value of {}", signal.name)?; writeln!(w, "///")?; writeln!(w, "/// - Start bit: {}", signal.start_bit)?; - writeln!(w, "/// - Signal size: {} bits", signal.signal_size)?; + writeln!(w, "/// - Signal size: {} bits", signal.size)?; writeln!(w, "/// - Factor: {}", signal.factor)?; writeln!(w, "/// - Offset: {}", signal.offset)?; - writeln!(w, "/// - Byte order: {:?}", signal.byte_order())?; - writeln!(w, "/// - Value type: {:?}", signal.value_type())?; + writeln!(w, "/// - Byte order: {:?}", signal.byte_order)?; + writeln!(w, "/// - Value type: {:?}", signal.value_type)?; writeln!(w, "#[inline(always)]")?; writeln!( w, "pub fn {}_raw(&self) -> {} {{", - field_name(signal.name()), + field_name(&signal.name), signal_to_rust_type(signal) )?; { @@ -606,12 +606,12 @@ fn render_set_signal( signal: &Signal, msg: &Message, ) -> Result<()> { - writeln!(&mut w, "/// Set value of {}", signal.name())?; + writeln!(&mut w, "/// Set value of {}", signal.name)?; writeln!(w, "#[inline(always)]")?; // To avoid accidentially changing the multiplexor value without changing // the signals accordingly this fn is kept private for multiplexors. - let visibility = if *signal.multiplexer_indicator() == MultiplexIndicator::Multiplexor { + let visibility = if signal.multiplexer_indicator == MultiplexIndicator::Multiplexor { "" } else { "pub " @@ -621,14 +621,14 @@ fn render_set_signal( w, "{}fn set_{}(&mut self, value: {}) -> Result<(), CanError> {{", visibility, - field_name(signal.name()), + field_name(&signal.name), signal_to_rust_type(signal) )?; { let mut w = PadAdapter::wrap(&mut w); - if signal.signal_size != 1 { + if signal.size != 1 { if let FeatureConfig::Gated(gate) = config.check_ranges { writeln!(w, r##"#[cfg(feature = {gate:?})]"##)?; } @@ -638,15 +638,15 @@ fn render_set_signal( w, r##"if value < {min}_{typ} || {max}_{typ} < value {{"##, typ = signal_to_rust_type(signal), - min = signal.min(), - max = signal.max(), + min = signal.min, + max = signal.max, )?; { let mut w = PadAdapter::wrap(&mut w); writeln!( w, r##"return Err(CanError::ParameterOutOfRange {{ message_id: {}::MESSAGE_ID }});"##, - type_name(msg.message_name()) + type_name(&msg.name) )?; } writeln!(w, r"}}")?; @@ -667,7 +667,7 @@ fn render_set_signal_multiplexer( msg: &Message, switch_index: u64, ) -> Result<()> { - writeln!(&mut w, "/// Set value of {}", multiplexor.name())?; + writeln!(&mut w, "/// Set value of {}", multiplexor.name)?; writeln!(w, "#[inline(always)]")?; writeln!( w, @@ -685,7 +685,7 @@ fn render_set_signal_multiplexer( writeln!( &mut w, "self.set_{}({})?;", - field_name(multiplexor.name()), + field_name(&multiplexor.name), switch_index )?; writeln!(&mut w, "Ok(())",)?; @@ -703,19 +703,19 @@ fn render_multiplexor_signal( signal: &Signal, msg: &Message, ) -> Result<()> { - writeln!(w, "/// Get raw value of {}", signal.name())?; + writeln!(w, "/// Get raw value of {}", signal.name)?; writeln!(w, "///")?; writeln!(w, "/// - Start bit: {}", signal.start_bit)?; - writeln!(w, "/// - Signal size: {} bits", signal.signal_size)?; + writeln!(w, "/// - Signal size: {} bits", signal.size)?; writeln!(w, "/// - Factor: {}", signal.factor)?; writeln!(w, "/// - Offset: {}", signal.offset)?; - writeln!(w, "/// - Byte order: {:?}", signal.byte_order())?; - writeln!(w, "/// - Value type: {:?}", signal.value_type())?; + writeln!(w, "/// - Byte order: {:?}", signal.byte_order)?; + writeln!(w, "/// - Value type: {:?}", signal.value_type)?; writeln!(w, "#[inline(always)]")?; writeln!( w, "pub fn {}_raw(&self) -> {} {{", - field_name(signal.name()), + field_name(&signal.name), signal_to_rust_type(signal) )?; { @@ -728,15 +728,15 @@ fn render_multiplexor_signal( writeln!( w, "pub fn {}(&mut self) -> Result<{}, CanError> {{", - field_name(signal.name()), + field_name(&signal.name), multiplex_enum_name(msg, signal)? )?; let multiplexer_indexes: BTreeSet = msg - .signals() + .signals .iter() .filter_map(|s| { - if let MultiplexIndicator::MultiplexedSignal(index) = s.multiplexer_indicator() { + if let MultiplexIndicator::MultiplexedSignal(index) = &s.multiplexer_indicator { Some(index) } else { None @@ -747,7 +747,7 @@ fn render_multiplexor_signal( { let mut w = PadAdapter::wrap(&mut w); - writeln!(&mut w, "match self.{}_raw() {{", field_name(signal.name()))?; + writeln!(&mut w, "match self.{}_raw() {{", field_name(&signal.name))?; { let mut w = PadAdapter::wrap(&mut w); @@ -765,7 +765,7 @@ fn render_multiplexor_signal( writeln!( &mut w, "multiplexor => Err(CanError::InvalidMultiplexor {{ message_id: {}::MESSAGE_ID, multiplexor: multiplexor.into() }}),", - type_name(msg.message_name()) + type_name(&msg.name) )?; } @@ -776,13 +776,13 @@ fn render_multiplexor_signal( render_set_signal(&mut w, config, signal, msg)?; let mut multiplexed_signals = BTreeMap::new(); - for signal in msg.signals() { - if let MultiplexIndicator::MultiplexedSignal(switch_index) = signal.multiplexer_indicator() + for signal in &msg.signals { + if let MultiplexIndicator::MultiplexedSignal(switch_index) = signal.multiplexer_indicator { multiplexed_signals .entry(switch_index) .and_modify(|v: &mut Vec<&Signal>| v.push(signal)) - .or_insert_with(|| vec![signal]); + .or_insert_with(|| vec![&signal]); } } @@ -804,10 +804,10 @@ fn be_start_end_bit(signal: &Signal, msg: &Message) -> Result<(u64, u64)> { let start_bit = x.checked_add(y).context(err)?; let end_bit = start_bit - .checked_add(signal.signal_size) + .checked_add(signal.size) .context("calculating last bit position")?; - let msg_bits = msg.message_size().checked_mul(8).unwrap(); + let msg_bits = msg.size.checked_mul(8).unwrap(); ensure!( start_bit <= msg_bits, @@ -825,7 +825,7 @@ fn be_start_end_bit(signal: &Signal, msg: &Message) -> Result<(u64, u64)> { } fn le_start_end_bit(signal: &Signal, msg: &Message) -> Result<(u64, u64)> { - let msg_bits = msg.message_size().checked_mul(8).unwrap(); + let msg_bits = msg.size.checked_mul(8).unwrap(); let start_bit = signal.start_bit; ensure!( start_bit <= msg_bits, @@ -836,7 +836,7 @@ fn le_start_end_bit(signal: &Signal, msg: &Message) -> Result<(u64, u64)> { let end_bit = signal .start_bit - .checked_add(signal.signal_size) + .checked_add(signal.size) .context("overflow calculating last bit position")?; ensure!( end_bit <= msg_bits, @@ -848,7 +848,7 @@ fn le_start_end_bit(signal: &Signal, msg: &Message) -> Result<(u64, u64)> { } fn signal_from_payload(mut w: impl Write, signal: &Signal, msg: &Message) -> Result<()> { - let read_fn = match signal.byte_order() { + let read_fn = match signal.byte_order { can_dbc::ByteOrder::LittleEndian => { let (start_bit, end_bit) = le_start_end_bit(signal, msg)?; @@ -874,7 +874,7 @@ fn signal_from_payload(mut w: impl Write, signal: &Signal, msg: &Message) -> Res writeln!(&mut w, r#"let signal = {};"#, read_fn)?; writeln!(&mut w)?; - if signal.signal_size == 1 { + if signal.size == 1 { writeln!(&mut w, "signal == 1")?; } else if signal_is_float_in_rust(signal) { // Scaling is always done on floats @@ -910,7 +910,7 @@ fn signal_from_payload(mut w: impl Write, signal: &Signal, msg: &Message) -> Res } fn signal_to_payload(mut w: impl Write, signal: &Signal, msg: &Message) -> Result<()> { - if signal.signal_size == 1 { + if signal.size == 1 { // Map boolean to byte so we can pack it writeln!(&mut w, "let value = value as u8;")?; } else if signal_is_float_in_rust(signal) { @@ -937,7 +937,7 @@ fn signal_to_payload(mut w: impl Write, signal: &Signal, msg: &Message) -> Resul writeln!( &mut w, " .ok_or(CanError::ParameterOutOfRange {{ message_id: {}::MESSAGE_ID }})?;", - type_name(msg.message_name()) + type_name(&msg.name) )?; writeln!( &mut w, @@ -947,7 +947,7 @@ fn signal_to_payload(mut w: impl Write, signal: &Signal, msg: &Message) -> Resul writeln!(&mut w)?; } - if *signal.value_type() == can_dbc::ValueType::Signed { + if signal.value_type == can_dbc::ValueType::Signed { writeln!( &mut w, "let value = {}::from_ne_bytes(value.to_ne_bytes());", @@ -955,7 +955,7 @@ fn signal_to_payload(mut w: impl Write, signal: &Signal, msg: &Message) -> Resul )?; }; - match signal.byte_order() { + match signal.byte_order { can_dbc::ByteOrder::LittleEndian => { let (start_bit, end_bit) = le_start_end_bit(signal, msg)?; writeln!( @@ -990,7 +990,7 @@ fn write_enum( let type_name = enum_name(msg, signal); let signal_rust_type = signal_to_rust_type(signal); - writeln!(w, "/// Defined values for {}", signal.name())?; + writeln!(w, "/// Defined values for {}", signal.name)?; writeln!(w, "#[derive(Clone, Copy, PartialEq)]")?; config.impl_debug.fmt_attr(&mut w, "derive(Debug)")?; config @@ -1002,7 +1002,7 @@ fn write_enum( { let mut w = PadAdapter::wrap(&mut w); for variant in variants { - writeln!(w, "{},", enum_variant_name(variant.b()))?; + writeln!(w, "{},", enum_variant_name(&variant.description))?; } writeln!(w, "_Other({}),", signal_rust_type)?; } @@ -1026,12 +1026,12 @@ fn write_enum( { let mut w = PadAdapter::wrap(&mut w); for variant in variants { - let literal = match_on_raw_type(*variant.a()); + let literal = match_on_raw_type(variant.id as f64); writeln!( &mut w, "{}::{} => {},", type_name, - enum_variant_name(variant.b()), + enum_variant_name(&variant.description), literal, )?; } @@ -1064,11 +1064,11 @@ fn scaled_signal_to_rust_int(signal: &Signal) -> String { let err = format!( "Signal {} could not be represented as a Rust integer", - &signal.name() + &signal.name ); signal_params_to_rust_int( - *signal.value_type(), - signal.signal_size as u32, + signal.value_type, + signal.size as u32, signal.factor as i64, signal.offset as i64, ) @@ -1176,12 +1176,12 @@ fn range_to_rust_int(low: i128, high: i128) -> String { /// Determine the smallest rust integer that can fit the raw signal values. fn signal_to_rust_int(signal: &Signal) -> String { - let sign = match signal.value_type() { + let sign = match signal.value_type { can_dbc::ValueType::Signed => "i", can_dbc::ValueType::Unsigned => "u", }; - let size = match signal.signal_size() { + let size = match signal.size { ..=8 => "8", ..=16 => "16", ..=32 => "32", @@ -1193,7 +1193,7 @@ fn signal_to_rust_int(signal: &Signal) -> String { /// Determine the smallest unsigned rust integer with no fewer bits than the signal. fn signal_to_rust_uint(signal: &Signal) -> String { - let size = match *signal.signal_size() { + let size = match signal.size { n if n <= 8 => "8", n if n <= 16 => "16", n if n <= 32 => "32", @@ -1209,7 +1209,7 @@ fn signal_is_float_in_rust(signal: &Signal) -> bool { } fn signal_to_rust_type(signal: &Signal) -> String { - if signal.signal_size == 1 { + if signal.size == 1 { String::from("bool") } else if signal_is_float_in_rust(signal) { // If there is any scaling needed, go for float @@ -1238,12 +1238,12 @@ fn field_name(x: &str) -> String { fn enum_name(msg: &Message, signal: &Signal) -> String { // this turns signal `_4DRIVE` into `4drive` let signal_name = signal - .name() + .name .trim_start_matches(|c: char| c.is_ascii_punctuation()); format!( "{}{}", - enum_variant_name(msg.message_name()), + enum_variant_name(&msg.name), signal_name.to_pascal_case() ) } @@ -1263,7 +1263,7 @@ fn multiplexed_enum_variant_wrapper_name(switch_index: u64) -> String { fn multiplex_enum_name(msg: &Message, multiplexor: &Signal) -> Result { ensure!( matches!( - multiplexor.multiplexer_indicator(), + multiplexor.multiplexer_indicator, MultiplexIndicator::Multiplexor ), "signal {:?} is not the multiplexor", @@ -1271,8 +1271,8 @@ fn multiplex_enum_name(msg: &Message, multiplexor: &Signal) -> Result { ); Ok(format!( "{}{}Index", - msg.message_name().to_pascal_case(), - multiplexor.name().to_pascal_case() + msg.name.to_pascal_case(), + multiplexor.name.to_pascal_case() )) } @@ -1283,7 +1283,7 @@ fn multiplexed_enum_variant_name( ) -> Result { ensure!( matches!( - multiplexor.multiplexer_indicator(), + multiplexor.multiplexer_indicator, MultiplexIndicator::Multiplexor ), "signal {:?} is not the multiplexor", @@ -1292,8 +1292,8 @@ fn multiplexed_enum_variant_name( Ok(format!( "{}{}M{}", - msg.message_name().to_pascal_case(), - multiplexor.name().to_pascal_case(), + msg.name.to_pascal_case(), + multiplexor.name.to_pascal_case(), switch_index )) } @@ -1343,7 +1343,7 @@ impl embedded_can::Frame for {0} {{ &self.raw }} }}", - type_name(msg.message_name()) + type_name(&msg.name) ) }) } @@ -1355,7 +1355,7 @@ fn render_debug_impl(mut w: impl Write, config: &Config<'_>, msg: &Message) -> R FeatureConfig::Never => return Ok(()), } - let typ = type_name(msg.message_name()); + let typ = type_name(&msg.name); writeln!(w, r##"impl core::fmt::Debug for {} {{"##, typ)?; { let mut w = PadAdapter::wrap(&mut w); @@ -1371,12 +1371,12 @@ fn render_debug_impl(mut w: impl Write, config: &Config<'_>, msg: &Message) -> R writeln!(w, r#"f.debug_struct("{}")"#, typ)?; { let mut w = PadAdapter::wrap(&mut w); - for signal in msg.signals() { - if *signal.multiplexer_indicator() == MultiplexIndicator::Plain { + for signal in &msg.signals { + if signal.multiplexer_indicator == MultiplexIndicator::Plain { writeln!( w, r#".field("{field_name}", &self.{field_name}())"#, - field_name = field_name(signal.name()), + field_name = field_name(&signal.name), )?; } } @@ -1404,7 +1404,7 @@ fn render_defmt_impl(mut w: impl Write, config: &Config<'_>, msg: &Message) -> R FeatureConfig::Never => return Ok(()), } - let typ = type_name(msg.message_name()); + let typ = type_name(&msg.name); writeln!(w, r##"impl defmt::Format for {} {{"##, typ)?; { let mut w = PadAdapter::wrap(&mut w); @@ -1416,17 +1416,17 @@ fn render_defmt_impl(mut w: impl Write, config: &Config<'_>, msg: &Message) -> R let mut w = PadAdapter::wrap(&mut w); write!(w, r#""{} {{{{"#, typ)?; { - for signal in msg.signals() { - if *signal.multiplexer_indicator() == MultiplexIndicator::Plain { - write!(w, r#" {}={{:?}}"#, signal.name(),)?; + for signal in &msg.signals { + if signal.multiplexer_indicator == MultiplexIndicator::Plain { + write!(w, r#" {}={{:?}}"#, signal.name,)?; } } } writeln!(w, r#" }}}}","#)?; - for signal in msg.signals() { - if *signal.multiplexer_indicator() == MultiplexIndicator::Plain { - writeln!(w, "self.{}(),", field_name(signal.name()))?; + for signal in &msg.signals { + if signal.multiplexer_indicator == MultiplexIndicator::Plain { + writeln!(w, "self.{}(),", field_name(&signal.name))?; } } writeln!(w, r#");"#)?; @@ -1442,31 +1442,31 @@ fn render_defmt_impl(mut w: impl Write, config: &Config<'_>, msg: &Message) -> R fn render_multiplexor_enums( mut w: impl Write, config: &Config<'_>, - dbc: &DBC, + dbc: &Dbc, msg: &Message, multiplexor_signal: &Signal, ) -> Result<()> { ensure!( - *multiplexor_signal.multiplexer_indicator() == MultiplexIndicator::Multiplexor, + multiplexor_signal.multiplexer_indicator == MultiplexIndicator::Multiplexor, "signal {} is not the multiplexor", - multiplexor_signal.name(), + multiplexor_signal.name, ); let mut multiplexed_signals = BTreeMap::new(); - for signal in msg.signals() { - if let MultiplexIndicator::MultiplexedSignal(switch_index) = signal.multiplexer_indicator() + for signal in &msg.signals { + if let MultiplexIndicator::MultiplexedSignal(switch_index) = signal.multiplexer_indicator { multiplexed_signals .entry(switch_index) .and_modify(|v: &mut Vec<&Signal>| v.push(signal)) - .or_insert_with(|| vec![signal]); + .or_insert_with(|| vec![&signal]); } } writeln!( w, "/// Defined values for multiplexed signal {}", - msg.message_name() + msg.name )?; config.impl_debug.fmt_attr(&mut w, "derive(Debug)")?; @@ -1487,9 +1487,9 @@ fn render_multiplexor_enums( writeln!( w, "{multiplexed_wrapper_name}({multiplexed_name}),", - multiplexed_wrapper_name = multiplexed_enum_variant_wrapper_name(**switch_index), + multiplexed_wrapper_name = multiplexed_enum_variant_wrapper_name(*switch_index), multiplexed_name = - multiplexed_enum_variant_name(msg, multiplexor_signal, **switch_index)? + multiplexed_enum_variant_name(msg, multiplexor_signal, *switch_index)? )?; } } @@ -1497,7 +1497,7 @@ fn render_multiplexor_enums( writeln!(w)?; for (switch_index, multiplexed_signals) in multiplexed_signals.iter() { - let struct_name = multiplexed_enum_variant_name(msg, multiplexor_signal, **switch_index)?; + let struct_name = multiplexed_enum_variant_name(msg, multiplexor_signal, *switch_index)?; config.impl_debug.fmt_attr(&mut w, "derive(Debug)")?; config @@ -1510,7 +1510,7 @@ fn render_multiplexor_enums( w, "pub struct {} {{ raw: [u8; {}] }}", struct_name, - msg.message_size() + msg.size )?; writeln!(w)?; @@ -1519,7 +1519,7 @@ fn render_multiplexor_enums( writeln!( w, "pub fn new() -> Self {{ Self {{ raw: [0u8; {}] }} }}", - msg.message_size() + msg.size )?; for signal in multiplexed_signals { @@ -1543,15 +1543,15 @@ fn render_arbitrary(mut w: impl Write, config: &Config<'_>, msg: &Message) -> Re writeln!( w, "impl<'a> Arbitrary<'a> for {typ} {{", - typ = type_name(msg.message_name()) + typ = type_name(&msg.name) )?; { let filtered_signals: Vec<&Signal> = msg - .signals() + .signals .iter() .filter(|signal| { - *signal.multiplexer_indicator() == MultiplexIndicator::Plain - || *signal.multiplexer_indicator() == MultiplexIndicator::Multiplexor + signal.multiplexer_indicator == MultiplexIndicator::Plain + || signal.multiplexer_indicator == MultiplexIndicator::Multiplexor }) .collect(); let mut w = PadAdapter::wrap(&mut w); @@ -1567,20 +1567,20 @@ fn render_arbitrary(mut w: impl Write, config: &Config<'_>, msg: &Message) -> Re writeln!( w, "let {field_name} = {arbitrary_value};", - field_name = field_name(signal.name()), + field_name = field_name(&signal.name), arbitrary_value = signal_to_arbitrary(signal), )?; } let args: Vec = filtered_signals .iter() - .map(|signal| field_name(signal.name())) + .map(|signal| field_name(&signal.name)) .collect(); writeln!( w, "{typ}::new({args}).map_err(|_| arbitrary::Error::IncorrectFormat)", - typ = type_name(msg.message_name()), + typ = type_name(&msg.name), args = args.join(",") )?; } @@ -1635,30 +1635,30 @@ fn render_arbitrary_helpers(mut w: impl Write, config: &Config<'_>) -> io::Resul } fn signal_to_arbitrary(signal: &Signal) -> String { - if signal.signal_size == 1 { + if signal.size == 1 { "u.int_in_range(0..=1)? == 1".to_string() } else if signal_is_float_in_rust(signal) { format!( "u.float_in_range({min}_f32..={max}_f32)?", - min = signal.min(), - max = signal.max() + min = signal.min, + max = signal.max ) } else { format!( "u.int_in_range({min}..={max})?", - min = signal.min(), - max = signal.max() + min = signal.min, + max = signal.max ) } } -fn get_relevant_messages(dbc: &DBC) -> impl Iterator { - dbc.messages().iter().filter(|m| !message_ignored(m)) +fn get_relevant_messages(dbc: &Dbc) -> impl Iterator { + dbc.messages.iter().filter(|m| !message_ignored(m)) } fn message_ignored(message: &Message) -> bool { // DBC internal message containing signals unassigned to any real message - message.message_name() == "VECTOR__INDEPENDENT_SIG_MSG" + message.name == "VECTOR__INDEPENDENT_SIG_MSG" } impl FeatureConfig<'_> { diff --git a/testing/can-embedded/src/messages.rs b/testing/can-embedded/src/messages.rs index fa5fd40..a78d2bd 100644 --- a/testing/can-embedded/src/messages.rs +++ b/testing/can-embedded/src/messages.rs @@ -1 +1,3271 @@ -// This stub will be replaced by testing/can-messages/build.rs +// Generated code! +#![allow(unused_comparisons, unreachable_patterns, unused_imports)] +#![allow(clippy::let_and_return, clippy::eq_op)] +#![allow(clippy::useless_conversion, clippy::unnecessary_cast)] +#![allow( + clippy::excessive_precision, + clippy::manual_range_contains, + clippy::absurd_extreme_comparisons, + clippy::too_many_arguments +)] +#![deny(clippy::arithmetic_side_effects)] + +//! Message definitions from file `"example.dbc"` +//! +//! - Version: `Version("43")` + +#[cfg(feature = "arb")] +use arbitrary::{Arbitrary, Unstructured}; +use bitvec::prelude::*; +use core::ops::BitOr; +use embedded_can::{ExtendedId, Id, StandardId}; + +/// All messages +#[derive(Clone, Debug, defmt::Format)] +pub enum Messages { + /// Foo + Foo(Foo), + /// Bar + Bar(Bar), + /// _4WD + X4wd(X4wd), + /// Amet + Amet(Amet), + /// Dolor + Dolor(Dolor), + /// MultiplexTest + MultiplexTest(MultiplexTest), + /// IntegerFactorOffset + IntegerFactorOffset(IntegerFactorOffset), + /// NegativeFactorTest + NegativeFactorTest(NegativeFactorTest), + /// LargerIntsWithOffsets + LargerIntsWithOffsets(LargerIntsWithOffsets), + /// MsgWithoutSignals + MsgWithoutSignals(MsgWithoutSignals), + /// TruncatedBeSignal + TruncatedBeSignal(TruncatedBeSignal), + /// TruncatedLeSignal + TruncatedLeSignal(TruncatedLeSignal), + /// MsgExtendedId + MsgExtendedId(MsgExtendedId), +} + +impl Messages { + /// Read message from CAN frame + #[inline(never)] + pub fn from_can_message(id: Id, payload: &[u8]) -> Result { + let res = match id { + Foo::MESSAGE_ID => Messages::Foo(Foo::try_from(payload)?), + Bar::MESSAGE_ID => Messages::Bar(Bar::try_from(payload)?), + X4wd::MESSAGE_ID => Messages::X4wd(X4wd::try_from(payload)?), + Amet::MESSAGE_ID => Messages::Amet(Amet::try_from(payload)?), + Dolor::MESSAGE_ID => Messages::Dolor(Dolor::try_from(payload)?), + MultiplexTest::MESSAGE_ID => Messages::MultiplexTest(MultiplexTest::try_from(payload)?), + IntegerFactorOffset::MESSAGE_ID => { + Messages::IntegerFactorOffset(IntegerFactorOffset::try_from(payload)?) + } + NegativeFactorTest::MESSAGE_ID => { + Messages::NegativeFactorTest(NegativeFactorTest::try_from(payload)?) + } + LargerIntsWithOffsets::MESSAGE_ID => { + Messages::LargerIntsWithOffsets(LargerIntsWithOffsets::try_from(payload)?) + } + MsgWithoutSignals::MESSAGE_ID => { + Messages::MsgWithoutSignals(MsgWithoutSignals::try_from(payload)?) + } + TruncatedBeSignal::MESSAGE_ID => { + Messages::TruncatedBeSignal(TruncatedBeSignal::try_from(payload)?) + } + TruncatedLeSignal::MESSAGE_ID => { + Messages::TruncatedLeSignal(TruncatedLeSignal::try_from(payload)?) + } + MsgExtendedId::MESSAGE_ID => Messages::MsgExtendedId(MsgExtendedId::try_from(payload)?), + id => return Err(CanError::UnknownMessageId(id)), + }; + Ok(res) + } +} + +/// Foo +/// +/// - Standard ID: 256 (0x100) +/// - Size: 4 bytes +/// - Transmitter: Lorem +#[derive(Clone, Copy)] +pub struct Foo { + raw: [u8; 4], +} + +impl Foo { + pub const MESSAGE_ID: embedded_can::Id = + Id::Standard(unsafe { StandardId::new_unchecked(0x100) }); + + pub const VOLTAGE_MIN: f32 = 0_f32; + pub const VOLTAGE_MAX: f32 = 63.9990234375_f32; + pub const CURRENT_MIN: f32 = -2048_f32; + pub const CURRENT_MAX: f32 = 2047.9375_f32; + + /// Construct new Foo from values + pub fn new(voltage: f32, current: f32) -> Result { + let mut res = Self { raw: [0u8; 4] }; + res.set_voltage(voltage)?; + res.set_current(current)?; + Ok(res) + } + + /// Access message payload raw value + pub fn raw(&self) -> &[u8; 4] { + &self.raw + } + + /// Voltage + /// + /// - Min: 0 + /// - Max: 63.9990234375 + /// - Unit: "V" + /// - Receivers: Vector__XXX + #[inline(always)] + pub fn voltage(&self) -> f32 { + self.voltage_raw() + } + + /// Get raw value of Voltage + /// + /// - Start bit: 16 + /// - Signal size: 16 bits + /// - Factor: 0.000976562 + /// - Offset: 0 + /// - Byte order: LittleEndian + /// - Value type: Unsigned + #[inline(always)] + pub fn voltage_raw(&self) -> f32 { + let signal = self.raw.view_bits::()[16..32].load_le::(); + + let factor = 0.000976562_f32; + let offset = 0_f32; + (signal as f32) * factor + offset + } + + /// Set value of Voltage + #[inline(always)] + pub fn set_voltage(&mut self, value: f32) -> Result<(), CanError> { + if value < 0_f32 || 63.9990234375_f32 < value { + return Err(CanError::ParameterOutOfRange { + message_id: Foo::MESSAGE_ID, + }); + } + let factor = 0.000976562_f32; + let offset = 0_f32; + let value = ((value - offset) / factor) as u16; + + self.raw.view_bits_mut::()[16..32].store_le(value); + Ok(()) + } + + /// Current + /// + /// - Min: -2048 + /// - Max: 2047.9375 + /// - Unit: "A" + /// - Receivers: Vector__XXX + #[inline(always)] + pub fn current(&self) -> f32 { + self.current_raw() + } + + /// Get raw value of Current + /// + /// - Start bit: 0 + /// - Signal size: 16 bits + /// - Factor: 0.0625 + /// - Offset: 0 + /// - Byte order: LittleEndian + /// - Value type: Signed + #[inline(always)] + pub fn current_raw(&self) -> f32 { + let signal = self.raw.view_bits::()[0..16].load_le::(); + + let factor = 0.0625_f32; + let offset = 0_f32; + (signal as f32) * factor + offset + } + + /// Set value of Current + #[inline(always)] + pub fn set_current(&mut self, value: f32) -> Result<(), CanError> { + if value < -2048_f32 || 2047.9375_f32 < value { + return Err(CanError::ParameterOutOfRange { + message_id: Foo::MESSAGE_ID, + }); + } + let factor = 0.0625_f32; + let offset = 0_f32; + let value = ((value - offset) / factor) as i16; + + let value = u16::from_ne_bytes(value.to_ne_bytes()); + self.raw.view_bits_mut::()[0..16].store_le(value); + Ok(()) + } +} + +impl core::convert::TryFrom<&[u8]> for Foo { + type Error = CanError; + + #[inline(always)] + fn try_from(payload: &[u8]) -> Result { + if payload.len() != 4 { + return Err(CanError::InvalidPayloadSize); + } + let mut raw = [0u8; 4]; + raw.copy_from_slice(&payload[..4]); + Ok(Self { raw }) + } +} + +impl embedded_can::Frame for Foo { + fn new(id: impl Into, data: &[u8]) -> Option { + if id.into() != Self::MESSAGE_ID { + None + } else { + data.try_into().ok() + } + } + + fn new_remote(_id: impl Into, _dlc: usize) -> Option { + unimplemented!() + } + + fn is_extended(&self) -> bool { + match self.id() { + Id::Standard(_) => false, + Id::Extended(_) => true, + } + } + + fn is_remote_frame(&self) -> bool { + false + } + + fn id(&self) -> Id { + Self::MESSAGE_ID + } + + fn dlc(&self) -> usize { + self.raw.len() + } + + fn data(&self) -> &[u8] { + &self.raw + } +} +impl core::fmt::Debug for Foo { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + if f.alternate() { + f.debug_struct("Foo") + .field("voltage", &self.voltage()) + .field("current", &self.current()) + .finish() + } else { + f.debug_tuple("Foo").field(&self.raw).finish() + } + } +} + +impl defmt::Format for Foo { + fn format(&self, f: defmt::Formatter) { + defmt::write!( + f, + "Foo {{ Voltage={:?} Current={:?} }}", + self.voltage(), + self.current(), + ); + } +} + +#[cfg(feature = "arb")] +impl<'a> Arbitrary<'a> for Foo { + fn arbitrary(u: &mut Unstructured<'a>) -> Result { + let voltage = u.float_in_range(0_f32..=63.9990234375_f32)?; + let current = u.float_in_range(-2048_f32..=2047.9375_f32)?; + Foo::new(voltage, current).map_err(|_| arbitrary::Error::IncorrectFormat) + } +} + +/// Bar +/// +/// - Standard ID: 512 (0x200) +/// - Size: 8 bytes +/// - Transmitter: Ipsum +#[derive(Clone, Copy)] +pub struct Bar { + raw: [u8; 8], +} + +impl Bar { + pub const MESSAGE_ID: embedded_can::Id = + Id::Standard(unsafe { StandardId::new_unchecked(0x200) }); + + pub const ONE_MIN: u8 = 0_u8; + pub const ONE_MAX: u8 = 3_u8; + pub const TWO_MIN: f32 = 0_f32; + pub const TWO_MAX: f32 = 100_f32; + pub const THREE_MIN: u8 = 0_u8; + pub const THREE_MAX: u8 = 7_u8; + pub const FOUR_MIN: u8 = 0_u8; + pub const FOUR_MAX: u8 = 3_u8; + + /// Construct new Bar from values + pub fn new(one: u8, two: f32, three: u8, four: u8, xtype: bool) -> Result { + let mut res = Self { raw: [0u8; 8] }; + res.set_one(one)?; + res.set_two(two)?; + res.set_three(three)?; + res.set_four(four)?; + res.set_xtype(xtype)?; + Ok(res) + } + + /// Access message payload raw value + pub fn raw(&self) -> &[u8; 8] { + &self.raw + } + + /// One + /// + /// - Min: 0 + /// - Max: 3 + /// - Unit: "" + /// - Receivers: Dolor + #[inline(always)] + pub fn one(&self) -> u8 { + self.one_raw() + } + + /// Get raw value of One + /// + /// - Start bit: 15 + /// - Signal size: 2 bits + /// - Factor: 1 + /// - Offset: 0 + /// - Byte order: BigEndian + /// - Value type: Unsigned + #[inline(always)] + pub fn one_raw(&self) -> u8 { + let signal = self.raw.view_bits::()[8..10].load_be::(); + + let factor = 1; + u8::from(signal).saturating_mul(factor).saturating_add(0) + } + + /// Set value of One + #[inline(always)] + pub fn set_one(&mut self, value: u8) -> Result<(), CanError> { + if value < 0_u8 || 3_u8 < value { + return Err(CanError::ParameterOutOfRange { + message_id: Bar::MESSAGE_ID, + }); + } + let factor = 1; + let value = value.checked_sub(0).ok_or(CanError::ParameterOutOfRange { + message_id: Bar::MESSAGE_ID, + })?; + let value = (value / factor) as u8; + + self.raw.view_bits_mut::()[8..10].store_be(value); + Ok(()) + } + + /// Two + /// + /// - Min: 0 + /// - Max: 100 + /// - Unit: "%" + /// - Receivers: Dolor + #[inline(always)] + pub fn two(&self) -> f32 { + self.two_raw() + } + + /// Get raw value of Two + /// + /// - Start bit: 7 + /// - Signal size: 8 bits + /// - Factor: 0.39 + /// - Offset: 0 + /// - Byte order: BigEndian + /// - Value type: Unsigned + #[inline(always)] + pub fn two_raw(&self) -> f32 { + let signal = self.raw.view_bits::()[0..8].load_be::(); + + let factor = 0.39_f32; + let offset = 0_f32; + (signal as f32) * factor + offset + } + + /// Set value of Two + #[inline(always)] + pub fn set_two(&mut self, value: f32) -> Result<(), CanError> { + if value < 0_f32 || 100_f32 < value { + return Err(CanError::ParameterOutOfRange { + message_id: Bar::MESSAGE_ID, + }); + } + let factor = 0.39_f32; + let offset = 0_f32; + let value = ((value - offset) / factor) as u8; + + self.raw.view_bits_mut::()[0..8].store_be(value); + Ok(()) + } + + /// Three + /// + /// - Min: 0 + /// - Max: 7 + /// - Unit: "" + /// - Receivers: Dolor + #[inline(always)] + pub fn three(&self) -> BarThree { + let signal = self.raw.view_bits::()[10..13].load_be::(); + + match signal { + 0 => BarThree::Off, + 1 => BarThree::On, + 2 => BarThree::Oner, + 3 => BarThree::Onest, + _ => BarThree::_Other(self.three_raw()), + } + } + + /// Get raw value of Three + /// + /// - Start bit: 13 + /// - Signal size: 3 bits + /// - Factor: 1 + /// - Offset: 0 + /// - Byte order: BigEndian + /// - Value type: Unsigned + #[inline(always)] + pub fn three_raw(&self) -> u8 { + let signal = self.raw.view_bits::()[10..13].load_be::(); + + let factor = 1; + u8::from(signal).saturating_mul(factor).saturating_add(0) + } + + /// Set value of Three + #[inline(always)] + pub fn set_three(&mut self, value: u8) -> Result<(), CanError> { + if value < 0_u8 || 7_u8 < value { + return Err(CanError::ParameterOutOfRange { + message_id: Bar::MESSAGE_ID, + }); + } + let factor = 1; + let value = value.checked_sub(0).ok_or(CanError::ParameterOutOfRange { + message_id: Bar::MESSAGE_ID, + })?; + let value = (value / factor) as u8; + + self.raw.view_bits_mut::()[10..13].store_be(value); + Ok(()) + } + + /// Four + /// + /// - Min: 0 + /// - Max: 3 + /// - Unit: "" + /// - Receivers: Dolor + #[inline(always)] + pub fn four(&self) -> BarFour { + let signal = self.raw.view_bits::()[13..15].load_be::(); + + match signal { + 0 => BarFour::Off, + 1 => BarFour::On, + 2 => BarFour::Oner, + 3 => BarFour::Onest, + _ => BarFour::_Other(self.four_raw()), + } + } + + /// Get raw value of Four + /// + /// - Start bit: 10 + /// - Signal size: 2 bits + /// - Factor: 1 + /// - Offset: 0 + /// - Byte order: BigEndian + /// - Value type: Unsigned + #[inline(always)] + pub fn four_raw(&self) -> u8 { + let signal = self.raw.view_bits::()[13..15].load_be::(); + + let factor = 1; + u8::from(signal).saturating_mul(factor).saturating_add(0) + } + + /// Set value of Four + #[inline(always)] + pub fn set_four(&mut self, value: u8) -> Result<(), CanError> { + if value < 0_u8 || 3_u8 < value { + return Err(CanError::ParameterOutOfRange { + message_id: Bar::MESSAGE_ID, + }); + } + let factor = 1; + let value = value.checked_sub(0).ok_or(CanError::ParameterOutOfRange { + message_id: Bar::MESSAGE_ID, + })?; + let value = (value / factor) as u8; + + self.raw.view_bits_mut::()[13..15].store_be(value); + Ok(()) + } + + /// Type + /// + /// - Min: 0 + /// - Max: 1 + /// - Unit: "boolean" + /// - Receivers: Dolor + #[inline(always)] + pub fn xtype(&self) -> BarType { + let signal = self.raw.view_bits::()[25..26].load_be::(); + + match signal { + 0 => BarType::X0off, + 1 => BarType::X1on, + _ => BarType::_Other(self.xtype_raw()), + } + } + + /// Get raw value of Type + /// + /// - Start bit: 30 + /// - Signal size: 1 bits + /// - Factor: 1 + /// - Offset: 0 + /// - Byte order: BigEndian + /// - Value type: Unsigned + #[inline(always)] + pub fn xtype_raw(&self) -> bool { + let signal = self.raw.view_bits::()[25..26].load_be::(); + + signal == 1 + } + + /// Set value of Type + #[inline(always)] + pub fn set_xtype(&mut self, value: bool) -> Result<(), CanError> { + let value = value as u8; + self.raw.view_bits_mut::()[25..26].store_be(value); + Ok(()) + } +} + +impl core::convert::TryFrom<&[u8]> for Bar { + type Error = CanError; + + #[inline(always)] + fn try_from(payload: &[u8]) -> Result { + if payload.len() != 8 { + return Err(CanError::InvalidPayloadSize); + } + let mut raw = [0u8; 8]; + raw.copy_from_slice(&payload[..8]); + Ok(Self { raw }) + } +} + +impl embedded_can::Frame for Bar { + fn new(id: impl Into, data: &[u8]) -> Option { + if id.into() != Self::MESSAGE_ID { + None + } else { + data.try_into().ok() + } + } + + fn new_remote(_id: impl Into, _dlc: usize) -> Option { + unimplemented!() + } + + fn is_extended(&self) -> bool { + match self.id() { + Id::Standard(_) => false, + Id::Extended(_) => true, + } + } + + fn is_remote_frame(&self) -> bool { + false + } + + fn id(&self) -> Id { + Self::MESSAGE_ID + } + + fn dlc(&self) -> usize { + self.raw.len() + } + + fn data(&self) -> &[u8] { + &self.raw + } +} +impl core::fmt::Debug for Bar { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + if f.alternate() { + f.debug_struct("Bar") + .field("one", &self.one()) + .field("two", &self.two()) + .field("three", &self.three()) + .field("four", &self.four()) + .field("xtype", &self.xtype()) + .finish() + } else { + f.debug_tuple("Bar").field(&self.raw).finish() + } + } +} + +impl defmt::Format for Bar { + fn format(&self, f: defmt::Formatter) { + defmt::write!( + f, + "Bar {{ One={:?} Two={:?} Three={:?} Four={:?} Type={:?} }}", + self.one(), + self.two(), + self.three(), + self.four(), + self.xtype(), + ); + } +} + +#[cfg(feature = "arb")] +impl<'a> Arbitrary<'a> for Bar { + fn arbitrary(u: &mut Unstructured<'a>) -> Result { + let one = u.int_in_range(0..=3)?; + let two = u.float_in_range(0_f32..=100_f32)?; + let three = u.int_in_range(0..=7)?; + let four = u.int_in_range(0..=3)?; + let xtype = u.int_in_range(0..=1)? == 1; + Bar::new(one, two, three, four, xtype).map_err(|_| arbitrary::Error::IncorrectFormat) + } +} +/// Defined values for Three +#[derive(Clone, Copy, PartialEq, Debug, defmt::Format)] +pub enum BarThree { + Off, + On, + Oner, + Onest, + _Other(u8), +} + +impl From for u8 { + fn from(val: BarThree) -> u8 { + match val { + BarThree::Off => 0, + BarThree::On => 1, + BarThree::Oner => 2, + BarThree::Onest => 3, + BarThree::_Other(x) => x, + } + } +} + +/// Defined values for Four +#[derive(Clone, Copy, PartialEq, Debug, defmt::Format)] +pub enum BarFour { + Off, + On, + Oner, + Onest, + _Other(u8), +} + +impl From for u8 { + fn from(val: BarFour) -> u8 { + match val { + BarFour::Off => 0, + BarFour::On => 1, + BarFour::Oner => 2, + BarFour::Onest => 3, + BarFour::_Other(x) => x, + } + } +} + +/// Defined values for Type +#[derive(Clone, Copy, PartialEq, Debug, defmt::Format)] +pub enum BarType { + X0off, + X1on, + _Other(bool), +} + +impl From for bool { + fn from(val: BarType) -> bool { + match val { + BarType::X0off => false, + BarType::X1on => true, + BarType::_Other(x) => x, + } + } +} + +/// _4WD +/// +/// - Standard ID: 768 (0x300) +/// - Size: 8 bytes +/// - Transmitter: Ipsum +#[derive(Clone, Copy)] +pub struct X4wd { + raw: [u8; 8], +} + +impl X4wd { + pub const MESSAGE_ID: embedded_can::Id = + Id::Standard(unsafe { StandardId::new_unchecked(0x300) }); + + pub const X4DRIVE_MIN: u8 = 0_u8; + pub const X4DRIVE_MAX: u8 = 7_u8; + + /// Construct new _4WD from values + pub fn new(x4drive: u8) -> Result { + let mut res = Self { raw: [0u8; 8] }; + res.set_x4drive(x4drive)?; + Ok(res) + } + + /// Access message payload raw value + pub fn raw(&self) -> &[u8; 8] { + &self.raw + } + + /// _4DRIVE + /// + /// - Min: 0 + /// - Max: 7 + /// - Unit: "" + /// - Receivers: Dolor + #[inline(always)] + pub fn x4drive(&self) -> X4wd4drive { + let signal = self.raw.view_bits::()[10..13].load_be::(); + + match signal { + 0 => X4wd4drive::Off, + 1 => X4wd4drive::X2wd, + 2 => X4wd4drive::X4wd, + 3 => X4wd4drive::All, + _ => X4wd4drive::_Other(self.x4drive_raw()), + } + } + + /// Get raw value of _4DRIVE + /// + /// - Start bit: 13 + /// - Signal size: 3 bits + /// - Factor: 1 + /// - Offset: 0 + /// - Byte order: BigEndian + /// - Value type: Unsigned + #[inline(always)] + pub fn x4drive_raw(&self) -> u8 { + let signal = self.raw.view_bits::()[10..13].load_be::(); + + let factor = 1; + u8::from(signal).saturating_mul(factor).saturating_add(0) + } + + /// Set value of _4DRIVE + #[inline(always)] + pub fn set_x4drive(&mut self, value: u8) -> Result<(), CanError> { + if value < 0_u8 || 7_u8 < value { + return Err(CanError::ParameterOutOfRange { + message_id: X4wd::MESSAGE_ID, + }); + } + let factor = 1; + let value = value.checked_sub(0).ok_or(CanError::ParameterOutOfRange { + message_id: X4wd::MESSAGE_ID, + })?; + let value = (value / factor) as u8; + + self.raw.view_bits_mut::()[10..13].store_be(value); + Ok(()) + } +} + +impl core::convert::TryFrom<&[u8]> for X4wd { + type Error = CanError; + + #[inline(always)] + fn try_from(payload: &[u8]) -> Result { + if payload.len() != 8 { + return Err(CanError::InvalidPayloadSize); + } + let mut raw = [0u8; 8]; + raw.copy_from_slice(&payload[..8]); + Ok(Self { raw }) + } +} + +impl embedded_can::Frame for X4wd { + fn new(id: impl Into, data: &[u8]) -> Option { + if id.into() != Self::MESSAGE_ID { + None + } else { + data.try_into().ok() + } + } + + fn new_remote(_id: impl Into, _dlc: usize) -> Option { + unimplemented!() + } + + fn is_extended(&self) -> bool { + match self.id() { + Id::Standard(_) => false, + Id::Extended(_) => true, + } + } + + fn is_remote_frame(&self) -> bool { + false + } + + fn id(&self) -> Id { + Self::MESSAGE_ID + } + + fn dlc(&self) -> usize { + self.raw.len() + } + + fn data(&self) -> &[u8] { + &self.raw + } +} +impl core::fmt::Debug for X4wd { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + if f.alternate() { + f.debug_struct("X4wd") + .field("x4drive", &self.x4drive()) + .finish() + } else { + f.debug_tuple("X4wd").field(&self.raw).finish() + } + } +} + +impl defmt::Format for X4wd { + fn format(&self, f: defmt::Formatter) { + defmt::write!(f, "X4wd {{ _4DRIVE={:?} }}", self.x4drive(),); + } +} + +#[cfg(feature = "arb")] +impl<'a> Arbitrary<'a> for X4wd { + fn arbitrary(u: &mut Unstructured<'a>) -> Result { + let x4drive = u.int_in_range(0..=7)?; + X4wd::new(x4drive).map_err(|_| arbitrary::Error::IncorrectFormat) + } +} +/// Defined values for _4DRIVE +#[derive(Clone, Copy, PartialEq, Debug, defmt::Format)] +pub enum X4wd4drive { + Off, + X2wd, + X4wd, + All, + _Other(u8), +} + +impl From for u8 { + fn from(val: X4wd4drive) -> u8 { + match val { + X4wd4drive::Off => 0, + X4wd4drive::X2wd => 1, + X4wd4drive::X4wd => 2, + X4wd4drive::All => 3, + X4wd4drive::_Other(x) => x, + } + } +} + +/// Amet +/// +/// - Standard ID: 1024 (0x400) +/// - Size: 8 bytes +/// - Transmitter: Sit +#[derive(Clone, Copy)] +pub struct Amet { + raw: [u8; 8], +} + +impl Amet { + pub const MESSAGE_ID: embedded_can::Id = + Id::Standard(unsafe { StandardId::new_unchecked(0x400) }); + + pub const ONE_MIN: u8 = 0_u8; + pub const ONE_MAX: u8 = 3_u8; + pub const TWO_MIN: f32 = 0_f32; + pub const TWO_MAX: f32 = 100_f32; + pub const THREE_MIN: u8 = 0_u8; + pub const THREE_MAX: u8 = 7_u8; + pub const FOUR_MIN: u8 = 0_u8; + pub const FOUR_MAX: u8 = 3_u8; + + /// Construct new Amet from values + pub fn new(one: u8, two: f32, three: u8, four: u8, five: bool) -> Result { + let mut res = Self { raw: [0u8; 8] }; + res.set_one(one)?; + res.set_two(two)?; + res.set_three(three)?; + res.set_four(four)?; + res.set_five(five)?; + Ok(res) + } + + /// Access message payload raw value + pub fn raw(&self) -> &[u8; 8] { + &self.raw + } + + /// One + /// + /// - Min: 0 + /// - Max: 3 + /// - Unit: "" + /// - Receivers: Dolor + #[inline(always)] + pub fn one(&self) -> u8 { + self.one_raw() + } + + /// Get raw value of One + /// + /// - Start bit: 15 + /// - Signal size: 2 bits + /// - Factor: 1 + /// - Offset: 0 + /// - Byte order: BigEndian + /// - Value type: Unsigned + #[inline(always)] + pub fn one_raw(&self) -> u8 { + let signal = self.raw.view_bits::()[8..10].load_be::(); + + let factor = 1; + u8::from(signal).saturating_mul(factor).saturating_add(0) + } + + /// Set value of One + #[inline(always)] + pub fn set_one(&mut self, value: u8) -> Result<(), CanError> { + if value < 0_u8 || 3_u8 < value { + return Err(CanError::ParameterOutOfRange { + message_id: Amet::MESSAGE_ID, + }); + } + let factor = 1; + let value = value.checked_sub(0).ok_or(CanError::ParameterOutOfRange { + message_id: Amet::MESSAGE_ID, + })?; + let value = (value / factor) as u8; + + self.raw.view_bits_mut::()[8..10].store_be(value); + Ok(()) + } + + /// Two + /// + /// - Min: 0 + /// - Max: 100 + /// - Unit: "%" + /// - Receivers: Dolor + #[inline(always)] + pub fn two(&self) -> f32 { + self.two_raw() + } + + /// Get raw value of Two + /// + /// - Start bit: 7 + /// - Signal size: 8 bits + /// - Factor: 0.39 + /// - Offset: 0 + /// - Byte order: BigEndian + /// - Value type: Unsigned + #[inline(always)] + pub fn two_raw(&self) -> f32 { + let signal = self.raw.view_bits::()[0..8].load_be::(); + + let factor = 0.39_f32; + let offset = 0_f32; + (signal as f32) * factor + offset + } + + /// Set value of Two + #[inline(always)] + pub fn set_two(&mut self, value: f32) -> Result<(), CanError> { + if value < 0_f32 || 100_f32 < value { + return Err(CanError::ParameterOutOfRange { + message_id: Amet::MESSAGE_ID, + }); + } + let factor = 0.39_f32; + let offset = 0_f32; + let value = ((value - offset) / factor) as u8; + + self.raw.view_bits_mut::()[0..8].store_be(value); + Ok(()) + } + + /// Three + /// + /// - Min: 0 + /// - Max: 7 + /// - Unit: "" + /// - Receivers: Dolor + #[inline(always)] + pub fn three(&self) -> u8 { + self.three_raw() + } + + /// Get raw value of Three + /// + /// - Start bit: 20 + /// - Signal size: 3 bits + /// - Factor: 1 + /// - Offset: 0 + /// - Byte order: BigEndian + /// - Value type: Unsigned + #[inline(always)] + pub fn three_raw(&self) -> u8 { + let signal = self.raw.view_bits::()[19..22].load_be::(); + + let factor = 1; + u8::from(signal).saturating_mul(factor).saturating_add(0) + } + + /// Set value of Three + #[inline(always)] + pub fn set_three(&mut self, value: u8) -> Result<(), CanError> { + if value < 0_u8 || 7_u8 < value { + return Err(CanError::ParameterOutOfRange { + message_id: Amet::MESSAGE_ID, + }); + } + let factor = 1; + let value = value.checked_sub(0).ok_or(CanError::ParameterOutOfRange { + message_id: Amet::MESSAGE_ID, + })?; + let value = (value / factor) as u8; + + self.raw.view_bits_mut::()[19..22].store_be(value); + Ok(()) + } + + /// Four + /// + /// - Min: 0 + /// - Max: 3 + /// - Unit: "" + /// - Receivers: Dolor + #[inline(always)] + pub fn four(&self) -> u8 { + self.four_raw() + } + + /// Get raw value of Four + /// + /// - Start bit: 30 + /// - Signal size: 2 bits + /// - Factor: 1 + /// - Offset: 0 + /// - Byte order: BigEndian + /// - Value type: Unsigned + #[inline(always)] + pub fn four_raw(&self) -> u8 { + let signal = self.raw.view_bits::()[25..27].load_be::(); + + let factor = 1; + u8::from(signal).saturating_mul(factor).saturating_add(0) + } + + /// Set value of Four + #[inline(always)] + pub fn set_four(&mut self, value: u8) -> Result<(), CanError> { + if value < 0_u8 || 3_u8 < value { + return Err(CanError::ParameterOutOfRange { + message_id: Amet::MESSAGE_ID, + }); + } + let factor = 1; + let value = value.checked_sub(0).ok_or(CanError::ParameterOutOfRange { + message_id: Amet::MESSAGE_ID, + })?; + let value = (value / factor) as u8; + + self.raw.view_bits_mut::()[25..27].store_be(value); + Ok(()) + } + + /// Five + /// + /// - Min: 0 + /// - Max: 1 + /// - Unit: "boolean" + /// - Receivers: Dolor + #[inline(always)] + pub fn five(&self) -> bool { + self.five_raw() + } + + /// Get raw value of Five + /// + /// - Start bit: 40 + /// - Signal size: 1 bits + /// - Factor: 1 + /// - Offset: 0 + /// - Byte order: BigEndian + /// - Value type: Unsigned + #[inline(always)] + pub fn five_raw(&self) -> bool { + let signal = self.raw.view_bits::()[47..48].load_be::(); + + signal == 1 + } + + /// Set value of Five + #[inline(always)] + pub fn set_five(&mut self, value: bool) -> Result<(), CanError> { + let value = value as u8; + self.raw.view_bits_mut::()[47..48].store_be(value); + Ok(()) + } +} + +impl core::convert::TryFrom<&[u8]> for Amet { + type Error = CanError; + + #[inline(always)] + fn try_from(payload: &[u8]) -> Result { + if payload.len() != 8 { + return Err(CanError::InvalidPayloadSize); + } + let mut raw = [0u8; 8]; + raw.copy_from_slice(&payload[..8]); + Ok(Self { raw }) + } +} + +impl embedded_can::Frame for Amet { + fn new(id: impl Into, data: &[u8]) -> Option { + if id.into() != Self::MESSAGE_ID { + None + } else { + data.try_into().ok() + } + } + + fn new_remote(_id: impl Into, _dlc: usize) -> Option { + unimplemented!() + } + + fn is_extended(&self) -> bool { + match self.id() { + Id::Standard(_) => false, + Id::Extended(_) => true, + } + } + + fn is_remote_frame(&self) -> bool { + false + } + + fn id(&self) -> Id { + Self::MESSAGE_ID + } + + fn dlc(&self) -> usize { + self.raw.len() + } + + fn data(&self) -> &[u8] { + &self.raw + } +} +impl core::fmt::Debug for Amet { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + if f.alternate() { + f.debug_struct("Amet") + .field("one", &self.one()) + .field("two", &self.two()) + .field("three", &self.three()) + .field("four", &self.four()) + .field("five", &self.five()) + .finish() + } else { + f.debug_tuple("Amet").field(&self.raw).finish() + } + } +} + +impl defmt::Format for Amet { + fn format(&self, f: defmt::Formatter) { + defmt::write!( + f, + "Amet {{ One={:?} Two={:?} Three={:?} Four={:?} Five={:?} }}", + self.one(), + self.two(), + self.three(), + self.four(), + self.five(), + ); + } +} + +#[cfg(feature = "arb")] +impl<'a> Arbitrary<'a> for Amet { + fn arbitrary(u: &mut Unstructured<'a>) -> Result { + let one = u.int_in_range(0..=3)?; + let two = u.float_in_range(0_f32..=100_f32)?; + let three = u.int_in_range(0..=7)?; + let four = u.int_in_range(0..=3)?; + let five = u.int_in_range(0..=1)? == 1; + Amet::new(one, two, three, four, five).map_err(|_| arbitrary::Error::IncorrectFormat) + } +} + +/// Dolor +/// +/// - Standard ID: 1028 (0x404) +/// - Size: 8 bytes +/// - Transmitter: Sit +#[derive(Clone, Copy)] +pub struct Dolor { + raw: [u8; 8], +} + +impl Dolor { + pub const MESSAGE_ID: embedded_can::Id = + Id::Standard(unsafe { StandardId::new_unchecked(0x404) }); + + pub const ONE_FLOAT_MIN: f32 = 0_f32; + pub const ONE_FLOAT_MAX: f32 = 130_f32; + + /// Construct new Dolor from values + pub fn new(one_float: f32) -> Result { + let mut res = Self { raw: [0u8; 8] }; + res.set_one_float(one_float)?; + Ok(res) + } + + /// Access message payload raw value + pub fn raw(&self) -> &[u8; 8] { + &self.raw + } + + /// OneFloat + /// + /// - Min: 0 + /// - Max: 130 + /// - Unit: "" + /// - Receivers: Vector__XXX + #[inline(always)] + pub fn one_float(&self) -> DolorOneFloat { + let signal = self.raw.view_bits::()[7..19].load_be::(); + + match signal { + 3 => DolorOneFloat::Dolor, + 5 => DolorOneFloat::Other, + _ => DolorOneFloat::_Other(self.one_float_raw()), + } + } + + /// Get raw value of OneFloat + /// + /// - Start bit: 0 + /// - Signal size: 12 bits + /// - Factor: 0.5 + /// - Offset: 0 + /// - Byte order: BigEndian + /// - Value type: Unsigned + #[inline(always)] + pub fn one_float_raw(&self) -> f32 { + let signal = self.raw.view_bits::()[7..19].load_be::(); + + let factor = 0.5_f32; + let offset = 0_f32; + (signal as f32) * factor + offset + } + + /// Set value of OneFloat + #[inline(always)] + pub fn set_one_float(&mut self, value: f32) -> Result<(), CanError> { + if value < 0_f32 || 130_f32 < value { + return Err(CanError::ParameterOutOfRange { + message_id: Dolor::MESSAGE_ID, + }); + } + let factor = 0.5_f32; + let offset = 0_f32; + let value = ((value - offset) / factor) as u16; + + self.raw.view_bits_mut::()[7..19].store_be(value); + Ok(()) + } +} + +impl core::convert::TryFrom<&[u8]> for Dolor { + type Error = CanError; + + #[inline(always)] + fn try_from(payload: &[u8]) -> Result { + if payload.len() != 8 { + return Err(CanError::InvalidPayloadSize); + } + let mut raw = [0u8; 8]; + raw.copy_from_slice(&payload[..8]); + Ok(Self { raw }) + } +} + +impl embedded_can::Frame for Dolor { + fn new(id: impl Into, data: &[u8]) -> Option { + if id.into() != Self::MESSAGE_ID { + None + } else { + data.try_into().ok() + } + } + + fn new_remote(_id: impl Into, _dlc: usize) -> Option { + unimplemented!() + } + + fn is_extended(&self) -> bool { + match self.id() { + Id::Standard(_) => false, + Id::Extended(_) => true, + } + } + + fn is_remote_frame(&self) -> bool { + false + } + + fn id(&self) -> Id { + Self::MESSAGE_ID + } + + fn dlc(&self) -> usize { + self.raw.len() + } + + fn data(&self) -> &[u8] { + &self.raw + } +} +impl core::fmt::Debug for Dolor { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + if f.alternate() { + f.debug_struct("Dolor") + .field("one_float", &self.one_float()) + .finish() + } else { + f.debug_tuple("Dolor").field(&self.raw).finish() + } + } +} + +impl defmt::Format for Dolor { + fn format(&self, f: defmt::Formatter) { + defmt::write!(f, "Dolor {{ OneFloat={:?} }}", self.one_float(),); + } +} + +#[cfg(feature = "arb")] +impl<'a> Arbitrary<'a> for Dolor { + fn arbitrary(u: &mut Unstructured<'a>) -> Result { + let one_float = u.float_in_range(0_f32..=130_f32)?; + Dolor::new(one_float).map_err(|_| arbitrary::Error::IncorrectFormat) + } +} +/// Defined values for OneFloat +#[derive(Clone, Copy, PartialEq, Debug, defmt::Format)] +pub enum DolorOneFloat { + Dolor, + Other, + _Other(f32), +} + +impl From for f32 { + fn from(val: DolorOneFloat) -> f32 { + match val { + DolorOneFloat::Dolor => 3_f32, + DolorOneFloat::Other => 5_f32, + DolorOneFloat::_Other(x) => x, + } + } +} + +/// MultiplexTest +/// +/// - Standard ID: 200 (0xc8) +/// - Size: 8 bytes +/// - Transmitter: SENSOR +#[derive(Clone, Copy)] +pub struct MultiplexTest { + raw: [u8; 8], +} + +impl MultiplexTest { + pub const MESSAGE_ID: embedded_can::Id = + Id::Standard(unsafe { StandardId::new_unchecked(0xc8) }); + + pub const MULTIPLEXOR_MIN: u8 = 0_u8; + pub const MULTIPLEXOR_MAX: u8 = 2_u8; + pub const UNMULTIPLEXED_SIGNAL_MIN: u8 = 0_u8; + pub const UNMULTIPLEXED_SIGNAL_MAX: u8 = 4_u8; + pub const MULTIPLEXED_SIGNAL_ZERO_A_MIN: f32 = 0_f32; + pub const MULTIPLEXED_SIGNAL_ZERO_A_MAX: f32 = 3_f32; + pub const MULTIPLEXED_SIGNAL_ZERO_B_MIN: f32 = 0_f32; + pub const MULTIPLEXED_SIGNAL_ZERO_B_MAX: f32 = 3_f32; + pub const MULTIPLEXED_SIGNAL_ONE_A_MIN: f32 = 0_f32; + pub const MULTIPLEXED_SIGNAL_ONE_A_MAX: f32 = 6_f32; + pub const MULTIPLEXED_SIGNAL_ONE_B_MIN: f32 = 0_f32; + pub const MULTIPLEXED_SIGNAL_ONE_B_MAX: f32 = 6_f32; + + /// Construct new MultiplexTest from values + pub fn new(multiplexor: u8, unmultiplexed_signal: u8) -> Result { + let mut res = Self { raw: [0u8; 8] }; + res.set_multiplexor(multiplexor)?; + res.set_unmultiplexed_signal(unmultiplexed_signal)?; + Ok(res) + } + + /// Access message payload raw value + pub fn raw(&self) -> &[u8; 8] { + &self.raw + } + + /// Get raw value of Multiplexor + /// + /// - Start bit: 0 + /// - Signal size: 4 bits + /// - Factor: 1 + /// - Offset: 0 + /// - Byte order: LittleEndian + /// - Value type: Unsigned + #[inline(always)] + pub fn multiplexor_raw(&self) -> u8 { + let signal = self.raw.view_bits::()[0..4].load_le::(); + + let factor = 1; + u8::from(signal).saturating_mul(factor).saturating_add(0) + } + + pub fn multiplexor(&mut self) -> Result { + match self.multiplexor_raw() { + 0 => Ok(MultiplexTestMultiplexorIndex::M0( + MultiplexTestMultiplexorM0 { raw: self.raw }, + )), + 1 => Ok(MultiplexTestMultiplexorIndex::M1( + MultiplexTestMultiplexorM1 { raw: self.raw }, + )), + multiplexor => Err(CanError::InvalidMultiplexor { + message_id: MultiplexTest::MESSAGE_ID, + multiplexor: multiplexor.into(), + }), + } + } + /// Set value of Multiplexor + #[inline(always)] + fn set_multiplexor(&mut self, value: u8) -> Result<(), CanError> { + if value < 0_u8 || 2_u8 < value { + return Err(CanError::ParameterOutOfRange { + message_id: MultiplexTest::MESSAGE_ID, + }); + } + let factor = 1; + let value = value.checked_sub(0).ok_or(CanError::ParameterOutOfRange { + message_id: MultiplexTest::MESSAGE_ID, + })?; + let value = (value / factor) as u8; + + self.raw.view_bits_mut::()[0..4].store_le(value); + Ok(()) + } + + /// Set value of Multiplexor + #[inline(always)] + pub fn set_m0(&mut self, value: MultiplexTestMultiplexorM0) -> Result<(), CanError> { + let b0 = BitArray::<_, LocalBits>::new(self.raw); + let b1 = BitArray::<_, LocalBits>::new(value.raw); + self.raw = b0.bitor(b1).into_inner(); + self.set_multiplexor(0)?; + Ok(()) + } + + /// Set value of Multiplexor + #[inline(always)] + pub fn set_m1(&mut self, value: MultiplexTestMultiplexorM1) -> Result<(), CanError> { + let b0 = BitArray::<_, LocalBits>::new(self.raw); + let b1 = BitArray::<_, LocalBits>::new(value.raw); + self.raw = b0.bitor(b1).into_inner(); + self.set_multiplexor(1)?; + Ok(()) + } + + /// UnmultiplexedSignal + /// + /// - Min: 0 + /// - Max: 4 + /// - Unit: "" + /// - Receivers: Vector__XXX + #[inline(always)] + pub fn unmultiplexed_signal(&self) -> u8 { + self.unmultiplexed_signal_raw() + } + + /// Get raw value of UnmultiplexedSignal + /// + /// - Start bit: 4 + /// - Signal size: 8 bits + /// - Factor: 1 + /// - Offset: 0 + /// - Byte order: LittleEndian + /// - Value type: Unsigned + #[inline(always)] + pub fn unmultiplexed_signal_raw(&self) -> u8 { + let signal = self.raw.view_bits::()[4..12].load_le::(); + + let factor = 1; + u8::from(signal).saturating_mul(factor).saturating_add(0) + } + + /// Set value of UnmultiplexedSignal + #[inline(always)] + pub fn set_unmultiplexed_signal(&mut self, value: u8) -> Result<(), CanError> { + if value < 0_u8 || 4_u8 < value { + return Err(CanError::ParameterOutOfRange { + message_id: MultiplexTest::MESSAGE_ID, + }); + } + let factor = 1; + let value = value.checked_sub(0).ok_or(CanError::ParameterOutOfRange { + message_id: MultiplexTest::MESSAGE_ID, + })?; + let value = (value / factor) as u8; + + self.raw.view_bits_mut::()[4..12].store_le(value); + Ok(()) + } +} + +impl core::convert::TryFrom<&[u8]> for MultiplexTest { + type Error = CanError; + + #[inline(always)] + fn try_from(payload: &[u8]) -> Result { + if payload.len() != 8 { + return Err(CanError::InvalidPayloadSize); + } + let mut raw = [0u8; 8]; + raw.copy_from_slice(&payload[..8]); + Ok(Self { raw }) + } +} + +impl embedded_can::Frame for MultiplexTest { + fn new(id: impl Into, data: &[u8]) -> Option { + if id.into() != Self::MESSAGE_ID { + None + } else { + data.try_into().ok() + } + } + + fn new_remote(_id: impl Into, _dlc: usize) -> Option { + unimplemented!() + } + + fn is_extended(&self) -> bool { + match self.id() { + Id::Standard(_) => false, + Id::Extended(_) => true, + } + } + + fn is_remote_frame(&self) -> bool { + false + } + + fn id(&self) -> Id { + Self::MESSAGE_ID + } + + fn dlc(&self) -> usize { + self.raw.len() + } + + fn data(&self) -> &[u8] { + &self.raw + } +} +impl core::fmt::Debug for MultiplexTest { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + if f.alternate() { + f.debug_struct("MultiplexTest") + .field("unmultiplexed_signal", &self.unmultiplexed_signal()) + .finish() + } else { + f.debug_tuple("MultiplexTest").field(&self.raw).finish() + } + } +} + +impl defmt::Format for MultiplexTest { + fn format(&self, f: defmt::Formatter) { + defmt::write!( + f, + "MultiplexTest {{ UnmultiplexedSignal={:?} }}", + self.unmultiplexed_signal(), + ); + } +} + +#[cfg(feature = "arb")] +impl<'a> Arbitrary<'a> for MultiplexTest { + fn arbitrary(u: &mut Unstructured<'a>) -> Result { + let multiplexor = u.int_in_range(0..=2)?; + let unmultiplexed_signal = u.int_in_range(0..=4)?; + MultiplexTest::new(multiplexor, unmultiplexed_signal) + .map_err(|_| arbitrary::Error::IncorrectFormat) + } +} +/// Defined values for multiplexed signal MultiplexTest +#[derive(Debug, defmt::Format)] +pub enum MultiplexTestMultiplexorIndex { + M0(MultiplexTestMultiplexorM0), + M1(MultiplexTestMultiplexorM1), +} + +#[derive(Debug, defmt::Format, Default)] +pub struct MultiplexTestMultiplexorM0 { + raw: [u8; 8], +} + +impl MultiplexTestMultiplexorM0 { + pub fn new() -> Self { + Self { raw: [0u8; 8] } + } + /// MultiplexedSignalZeroA + /// + /// - Min: 0 + /// - Max: 3 + /// - Unit: "" + /// - Receivers: Vector__XXX + #[inline(always)] + pub fn multiplexed_signal_zero_a(&self) -> f32 { + self.multiplexed_signal_zero_a_raw() + } + + /// Get raw value of MultiplexedSignalZeroA + /// + /// - Start bit: 12 + /// - Signal size: 8 bits + /// - Factor: 0.1 + /// - Offset: 0 + /// - Byte order: LittleEndian + /// - Value type: Unsigned + #[inline(always)] + pub fn multiplexed_signal_zero_a_raw(&self) -> f32 { + let signal = self.raw.view_bits::()[12..20].load_le::(); + + let factor = 0.1_f32; + let offset = 0_f32; + (signal as f32) * factor + offset + } + + /// Set value of MultiplexedSignalZeroA + #[inline(always)] + pub fn set_multiplexed_signal_zero_a(&mut self, value: f32) -> Result<(), CanError> { + if value < 0_f32 || 3_f32 < value { + return Err(CanError::ParameterOutOfRange { + message_id: MultiplexTest::MESSAGE_ID, + }); + } + let factor = 0.1_f32; + let offset = 0_f32; + let value = ((value - offset) / factor) as u8; + + self.raw.view_bits_mut::()[12..20].store_le(value); + Ok(()) + } + + /// MultiplexedSignalZeroB + /// + /// - Min: 0 + /// - Max: 3 + /// - Unit: "" + /// - Receivers: Vector__XXX + #[inline(always)] + pub fn multiplexed_signal_zero_b(&self) -> f32 { + self.multiplexed_signal_zero_b_raw() + } + + /// Get raw value of MultiplexedSignalZeroB + /// + /// - Start bit: 20 + /// - Signal size: 8 bits + /// - Factor: 0.1 + /// - Offset: 0 + /// - Byte order: LittleEndian + /// - Value type: Unsigned + #[inline(always)] + pub fn multiplexed_signal_zero_b_raw(&self) -> f32 { + let signal = self.raw.view_bits::()[20..28].load_le::(); + + let factor = 0.1_f32; + let offset = 0_f32; + (signal as f32) * factor + offset + } + + /// Set value of MultiplexedSignalZeroB + #[inline(always)] + pub fn set_multiplexed_signal_zero_b(&mut self, value: f32) -> Result<(), CanError> { + if value < 0_f32 || 3_f32 < value { + return Err(CanError::ParameterOutOfRange { + message_id: MultiplexTest::MESSAGE_ID, + }); + } + let factor = 0.1_f32; + let offset = 0_f32; + let value = ((value - offset) / factor) as u8; + + self.raw.view_bits_mut::()[20..28].store_le(value); + Ok(()) + } +} + +#[derive(Debug, defmt::Format, Default)] +pub struct MultiplexTestMultiplexorM1 { + raw: [u8; 8], +} + +impl MultiplexTestMultiplexorM1 { + pub fn new() -> Self { + Self { raw: [0u8; 8] } + } + /// MultiplexedSignalOneA + /// + /// - Min: 0 + /// - Max: 6 + /// - Unit: "" + /// - Receivers: Vector__XXX + #[inline(always)] + pub fn multiplexed_signal_one_a(&self) -> f32 { + self.multiplexed_signal_one_a_raw() + } + + /// Get raw value of MultiplexedSignalOneA + /// + /// - Start bit: 12 + /// - Signal size: 8 bits + /// - Factor: 0.1 + /// - Offset: 0 + /// - Byte order: LittleEndian + /// - Value type: Unsigned + #[inline(always)] + pub fn multiplexed_signal_one_a_raw(&self) -> f32 { + let signal = self.raw.view_bits::()[12..20].load_le::(); + + let factor = 0.1_f32; + let offset = 0_f32; + (signal as f32) * factor + offset + } + + /// Set value of MultiplexedSignalOneA + #[inline(always)] + pub fn set_multiplexed_signal_one_a(&mut self, value: f32) -> Result<(), CanError> { + if value < 0_f32 || 6_f32 < value { + return Err(CanError::ParameterOutOfRange { + message_id: MultiplexTest::MESSAGE_ID, + }); + } + let factor = 0.1_f32; + let offset = 0_f32; + let value = ((value - offset) / factor) as u8; + + self.raw.view_bits_mut::()[12..20].store_le(value); + Ok(()) + } + + /// MultiplexedSignalOneB + /// + /// - Min: 0 + /// - Max: 6 + /// - Unit: "" + /// - Receivers: Vector__XXX + #[inline(always)] + pub fn multiplexed_signal_one_b(&self) -> f32 { + self.multiplexed_signal_one_b_raw() + } + + /// Get raw value of MultiplexedSignalOneB + /// + /// - Start bit: 20 + /// - Signal size: 8 bits + /// - Factor: 0.1 + /// - Offset: 0 + /// - Byte order: LittleEndian + /// - Value type: Unsigned + #[inline(always)] + pub fn multiplexed_signal_one_b_raw(&self) -> f32 { + let signal = self.raw.view_bits::()[20..28].load_le::(); + + let factor = 0.1_f32; + let offset = 0_f32; + (signal as f32) * factor + offset + } + + /// Set value of MultiplexedSignalOneB + #[inline(always)] + pub fn set_multiplexed_signal_one_b(&mut self, value: f32) -> Result<(), CanError> { + if value < 0_f32 || 6_f32 < value { + return Err(CanError::ParameterOutOfRange { + message_id: MultiplexTest::MESSAGE_ID, + }); + } + let factor = 0.1_f32; + let offset = 0_f32; + let value = ((value - offset) / factor) as u8; + + self.raw.view_bits_mut::()[20..28].store_le(value); + Ok(()) + } +} + +/// IntegerFactorOffset +/// +/// - Standard ID: 1337 (0x539) +/// - Size: 8 bytes +/// - Transmitter: Sit +#[derive(Clone, Copy)] +pub struct IntegerFactorOffset { + raw: [u8; 8], +} + +impl IntegerFactorOffset { + pub const MESSAGE_ID: embedded_can::Id = + Id::Standard(unsafe { StandardId::new_unchecked(0x539) }); + + pub const BYTE_WITH_OFFSET_MIN: u16 = 1_u16; + pub const BYTE_WITH_OFFSET_MAX: u16 = 256_u16; + pub const BYTE_WITH_FACTOR_MIN: u16 = 0_u16; + pub const BYTE_WITH_FACTOR_MAX: u16 = 1020_u16; + pub const BYTE_WITH_BOTH_MIN: u16 = 16_u16; + pub const BYTE_WITH_BOTH_MAX: u16 = 526_u16; + pub const BYTE_WITH_NEGATIVE_OFFSET_MIN: i16 = 0_i16; + pub const BYTE_WITH_NEGATIVE_OFFSET_MAX: i16 = 255_i16; + pub const BYTE_WITH_NEGATIVE_MIN_MIN: i16 = -127_i16; + pub const BYTE_WITH_NEGATIVE_MIN_MAX: i16 = 127_i16; + + /// Construct new IntegerFactorOffset from values + pub fn new( + byte_with_offset: u16, + byte_with_factor: u16, + byte_with_both: u16, + byte_with_negative_offset: i16, + byte_with_negative_min: i16, + ) -> Result { + let mut res = Self { raw: [0u8; 8] }; + res.set_byte_with_offset(byte_with_offset)?; + res.set_byte_with_factor(byte_with_factor)?; + res.set_byte_with_both(byte_with_both)?; + res.set_byte_with_negative_offset(byte_with_negative_offset)?; + res.set_byte_with_negative_min(byte_with_negative_min)?; + Ok(res) + } + + /// Access message payload raw value + pub fn raw(&self) -> &[u8; 8] { + &self.raw + } + + /// ByteWithOffset + /// + /// - Min: 1 + /// - Max: 256 + /// - Unit: "" + /// - Receivers: Vector__XXX + #[inline(always)] + pub fn byte_with_offset(&self) -> u16 { + self.byte_with_offset_raw() + } + + /// Get raw value of ByteWithOffset + /// + /// - Start bit: 0 + /// - Signal size: 8 bits + /// - Factor: 1 + /// - Offset: 1 + /// - Byte order: LittleEndian + /// - Value type: Unsigned + #[inline(always)] + pub fn byte_with_offset_raw(&self) -> u16 { + let signal = self.raw.view_bits::()[0..8].load_le::(); + + let factor = 1; + u16::from(signal).saturating_mul(factor).saturating_add(1) + } + + /// Set value of ByteWithOffset + #[inline(always)] + pub fn set_byte_with_offset(&mut self, value: u16) -> Result<(), CanError> { + if value < 1_u16 || 256_u16 < value { + return Err(CanError::ParameterOutOfRange { + message_id: IntegerFactorOffset::MESSAGE_ID, + }); + } + let factor = 1; + let value = value.checked_sub(1).ok_or(CanError::ParameterOutOfRange { + message_id: IntegerFactorOffset::MESSAGE_ID, + })?; + let value = (value / factor) as u8; + + self.raw.view_bits_mut::()[0..8].store_le(value); + Ok(()) + } + + /// ByteWithFactor + /// + /// - Min: 0 + /// - Max: 1020 + /// - Unit: "" + /// - Receivers: Vector__XXX + #[inline(always)] + pub fn byte_with_factor(&self) -> u16 { + self.byte_with_factor_raw() + } + + /// Get raw value of ByteWithFactor + /// + /// - Start bit: 8 + /// - Signal size: 8 bits + /// - Factor: 4 + /// - Offset: 0 + /// - Byte order: LittleEndian + /// - Value type: Unsigned + #[inline(always)] + pub fn byte_with_factor_raw(&self) -> u16 { + let signal = self.raw.view_bits::()[8..16].load_le::(); + + let factor = 4; + u16::from(signal).saturating_mul(factor).saturating_add(0) + } + + /// Set value of ByteWithFactor + #[inline(always)] + pub fn set_byte_with_factor(&mut self, value: u16) -> Result<(), CanError> { + if value < 0_u16 || 1020_u16 < value { + return Err(CanError::ParameterOutOfRange { + message_id: IntegerFactorOffset::MESSAGE_ID, + }); + } + let factor = 4; + let value = value.checked_sub(0).ok_or(CanError::ParameterOutOfRange { + message_id: IntegerFactorOffset::MESSAGE_ID, + })?; + let value = (value / factor) as u8; + + self.raw.view_bits_mut::()[8..16].store_le(value); + Ok(()) + } + + /// ByteWithBoth + /// + /// - Min: 16 + /// - Max: 526 + /// - Unit: "" + /// - Receivers: Vector__XXX + #[inline(always)] + pub fn byte_with_both(&self) -> u16 { + self.byte_with_both_raw() + } + + /// Get raw value of ByteWithBoth + /// + /// - Start bit: 16 + /// - Signal size: 8 bits + /// - Factor: 2 + /// - Offset: 16 + /// - Byte order: LittleEndian + /// - Value type: Unsigned + #[inline(always)] + pub fn byte_with_both_raw(&self) -> u16 { + let signal = self.raw.view_bits::()[16..24].load_le::(); + + let factor = 2; + u16::from(signal).saturating_mul(factor).saturating_add(16) + } + + /// Set value of ByteWithBoth + #[inline(always)] + pub fn set_byte_with_both(&mut self, value: u16) -> Result<(), CanError> { + if value < 16_u16 || 526_u16 < value { + return Err(CanError::ParameterOutOfRange { + message_id: IntegerFactorOffset::MESSAGE_ID, + }); + } + let factor = 2; + let value = value.checked_sub(16).ok_or(CanError::ParameterOutOfRange { + message_id: IntegerFactorOffset::MESSAGE_ID, + })?; + let value = (value / factor) as u8; + + self.raw.view_bits_mut::()[16..24].store_le(value); + Ok(()) + } + + /// ByteWithNegativeOffset + /// + /// - Min: 0 + /// - Max: 255 + /// - Unit: "" + /// - Receivers: Vector__XXX + #[inline(always)] + pub fn byte_with_negative_offset(&self) -> i16 { + self.byte_with_negative_offset_raw() + } + + /// Get raw value of ByteWithNegativeOffset + /// + /// - Start bit: 24 + /// - Signal size: 8 bits + /// - Factor: 1 + /// - Offset: -1 + /// - Byte order: LittleEndian + /// - Value type: Unsigned + #[inline(always)] + pub fn byte_with_negative_offset_raw(&self) -> i16 { + let signal = self.raw.view_bits::()[24..32].load_le::(); + + let factor = 1; + i16::from(signal).saturating_mul(factor).saturating_sub(1) + } + + /// Set value of ByteWithNegativeOffset + #[inline(always)] + pub fn set_byte_with_negative_offset(&mut self, value: i16) -> Result<(), CanError> { + if value < 0_i16 || 255_i16 < value { + return Err(CanError::ParameterOutOfRange { + message_id: IntegerFactorOffset::MESSAGE_ID, + }); + } + let factor = 1; + let value = value.checked_add(1).ok_or(CanError::ParameterOutOfRange { + message_id: IntegerFactorOffset::MESSAGE_ID, + })?; + let value = (value / factor) as u8; + + self.raw.view_bits_mut::()[24..32].store_le(value); + Ok(()) + } + + /// ByteWithNegativeMin + /// + /// - Min: -127 + /// - Max: 127 + /// - Unit: "" + /// - Receivers: Vector__XXX + #[inline(always)] + pub fn byte_with_negative_min(&self) -> i16 { + self.byte_with_negative_min_raw() + } + + /// Get raw value of ByteWithNegativeMin + /// + /// - Start bit: 32 + /// - Signal size: 8 bits + /// - Factor: 1 + /// - Offset: -1 + /// - Byte order: LittleEndian + /// - Value type: Unsigned + #[inline(always)] + pub fn byte_with_negative_min_raw(&self) -> i16 { + let signal = self.raw.view_bits::()[32..40].load_le::(); + + let factor = 1; + i16::from(signal).saturating_mul(factor).saturating_sub(1) + } + + /// Set value of ByteWithNegativeMin + #[inline(always)] + pub fn set_byte_with_negative_min(&mut self, value: i16) -> Result<(), CanError> { + if value < -127_i16 || 127_i16 < value { + return Err(CanError::ParameterOutOfRange { + message_id: IntegerFactorOffset::MESSAGE_ID, + }); + } + let factor = 1; + let value = value.checked_add(1).ok_or(CanError::ParameterOutOfRange { + message_id: IntegerFactorOffset::MESSAGE_ID, + })?; + let value = (value / factor) as u8; + + self.raw.view_bits_mut::()[32..40].store_le(value); + Ok(()) + } +} + +impl core::convert::TryFrom<&[u8]> for IntegerFactorOffset { + type Error = CanError; + + #[inline(always)] + fn try_from(payload: &[u8]) -> Result { + if payload.len() != 8 { + return Err(CanError::InvalidPayloadSize); + } + let mut raw = [0u8; 8]; + raw.copy_from_slice(&payload[..8]); + Ok(Self { raw }) + } +} + +impl embedded_can::Frame for IntegerFactorOffset { + fn new(id: impl Into, data: &[u8]) -> Option { + if id.into() != Self::MESSAGE_ID { + None + } else { + data.try_into().ok() + } + } + + fn new_remote(_id: impl Into, _dlc: usize) -> Option { + unimplemented!() + } + + fn is_extended(&self) -> bool { + match self.id() { + Id::Standard(_) => false, + Id::Extended(_) => true, + } + } + + fn is_remote_frame(&self) -> bool { + false + } + + fn id(&self) -> Id { + Self::MESSAGE_ID + } + + fn dlc(&self) -> usize { + self.raw.len() + } + + fn data(&self) -> &[u8] { + &self.raw + } +} +impl core::fmt::Debug for IntegerFactorOffset { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + if f.alternate() { + f.debug_struct("IntegerFactorOffset") + .field("byte_with_offset", &self.byte_with_offset()) + .field("byte_with_factor", &self.byte_with_factor()) + .field("byte_with_both", &self.byte_with_both()) + .field( + "byte_with_negative_offset", + &self.byte_with_negative_offset(), + ) + .field("byte_with_negative_min", &self.byte_with_negative_min()) + .finish() + } else { + f.debug_tuple("IntegerFactorOffset") + .field(&self.raw) + .finish() + } + } +} + +impl defmt::Format for IntegerFactorOffset { + fn format(&self, f: defmt::Formatter) { + defmt::write!(f, + "IntegerFactorOffset {{ ByteWithOffset={:?} ByteWithFactor={:?} ByteWithBoth={:?} ByteWithNegativeOffset={:?} ByteWithNegativeMin={:?} }}", + self.byte_with_offset(), + self.byte_with_factor(), + self.byte_with_both(), + self.byte_with_negative_offset(), + self.byte_with_negative_min(), + ); + } +} + +#[cfg(feature = "arb")] +impl<'a> Arbitrary<'a> for IntegerFactorOffset { + fn arbitrary(u: &mut Unstructured<'a>) -> Result { + let byte_with_offset = u.int_in_range(1..=256)?; + let byte_with_factor = u.int_in_range(0..=1020)?; + let byte_with_both = u.int_in_range(16..=526)?; + let byte_with_negative_offset = u.int_in_range(0..=255)?; + let byte_with_negative_min = u.int_in_range(-127..=127)?; + IntegerFactorOffset::new( + byte_with_offset, + byte_with_factor, + byte_with_both, + byte_with_negative_offset, + byte_with_negative_min, + ) + .map_err(|_| arbitrary::Error::IncorrectFormat) + } +} + +/// NegativeFactorTest +/// +/// - Standard ID: 1344 (0x540) +/// - Size: 4 bytes +/// - Transmitter: Sit +#[derive(Clone, Copy)] +pub struct NegativeFactorTest { + raw: [u8; 4], +} + +impl NegativeFactorTest { + pub const MESSAGE_ID: embedded_can::Id = + Id::Standard(unsafe { StandardId::new_unchecked(0x540) }); + + pub const UNSIGNED_NEGATIVE_FACTOR_SIGNAL_MIN: i32 = -65535_i32; + pub const UNSIGNED_NEGATIVE_FACTOR_SIGNAL_MAX: i32 = 0_i32; + pub const WIDTH_MORE_THAN_MIN_MAX_MIN: i16 = -2_i16; + pub const WIDTH_MORE_THAN_MIN_MAX_MAX: i16 = 2_i16; + + /// Construct new NegativeFactorTest from values + pub fn new( + unsigned_negative_factor_signal: i32, + width_more_than_min_max: i16, + ) -> Result { + let mut res = Self { raw: [0u8; 4] }; + res.set_unsigned_negative_factor_signal(unsigned_negative_factor_signal)?; + res.set_width_more_than_min_max(width_more_than_min_max)?; + Ok(res) + } + + /// Access message payload raw value + pub fn raw(&self) -> &[u8; 4] { + &self.raw + } + + /// UnsignedNegativeFactorSignal + /// + /// - Min: -65535 + /// - Max: 0 + /// - Unit: "" + /// - Receivers: Vector__XXX + #[inline(always)] + pub fn unsigned_negative_factor_signal(&self) -> i32 { + self.unsigned_negative_factor_signal_raw() + } + + /// Get raw value of UnsignedNegativeFactorSignal + /// + /// - Start bit: 0 + /// - Signal size: 16 bits + /// - Factor: -1 + /// - Offset: 0 + /// - Byte order: LittleEndian + /// - Value type: Unsigned + #[inline(always)] + pub fn unsigned_negative_factor_signal_raw(&self) -> i32 { + let signal = self.raw.view_bits::()[0..16].load_le::(); + + let factor = -1; + i32::from(signal).saturating_mul(factor).saturating_add(0) + } + + /// Set value of UnsignedNegativeFactorSignal + #[inline(always)] + pub fn set_unsigned_negative_factor_signal(&mut self, value: i32) -> Result<(), CanError> { + if value < -65535_i32 || 0_i32 < value { + return Err(CanError::ParameterOutOfRange { + message_id: NegativeFactorTest::MESSAGE_ID, + }); + } + let factor = -1; + let value = value.checked_sub(0).ok_or(CanError::ParameterOutOfRange { + message_id: NegativeFactorTest::MESSAGE_ID, + })?; + let value = (value / factor) as u16; + + self.raw.view_bits_mut::()[0..16].store_le(value); + Ok(()) + } + + /// WidthMoreThanMinMax + /// + /// - Min: -2 + /// - Max: 2 + /// - Unit: "" + /// - Receivers: Vector__XXX + #[inline(always)] + pub fn width_more_than_min_max(&self) -> i16 { + self.width_more_than_min_max_raw() + } + + /// Get raw value of WidthMoreThanMinMax + /// + /// - Start bit: 16 + /// - Signal size: 10 bits + /// - Factor: 1 + /// - Offset: 0 + /// - Byte order: LittleEndian + /// - Value type: Signed + #[inline(always)] + pub fn width_more_than_min_max_raw(&self) -> i16 { + let signal = self.raw.view_bits::()[16..26].load_le::(); + + let factor = 1; + let signal = signal as i16; + i16::from(signal).saturating_mul(factor).saturating_add(0) + } + + /// Set value of WidthMoreThanMinMax + #[inline(always)] + pub fn set_width_more_than_min_max(&mut self, value: i16) -> Result<(), CanError> { + if value < -2_i16 || 2_i16 < value { + return Err(CanError::ParameterOutOfRange { + message_id: NegativeFactorTest::MESSAGE_ID, + }); + } + let factor = 1; + let value = value.checked_sub(0).ok_or(CanError::ParameterOutOfRange { + message_id: NegativeFactorTest::MESSAGE_ID, + })?; + let value = (value / factor) as i16; + + let value = u16::from_ne_bytes(value.to_ne_bytes()); + self.raw.view_bits_mut::()[16..26].store_le(value); + Ok(()) + } +} + +impl core::convert::TryFrom<&[u8]> for NegativeFactorTest { + type Error = CanError; + + #[inline(always)] + fn try_from(payload: &[u8]) -> Result { + if payload.len() != 4 { + return Err(CanError::InvalidPayloadSize); + } + let mut raw = [0u8; 4]; + raw.copy_from_slice(&payload[..4]); + Ok(Self { raw }) + } +} + +impl embedded_can::Frame for NegativeFactorTest { + fn new(id: impl Into, data: &[u8]) -> Option { + if id.into() != Self::MESSAGE_ID { + None + } else { + data.try_into().ok() + } + } + + fn new_remote(_id: impl Into, _dlc: usize) -> Option { + unimplemented!() + } + + fn is_extended(&self) -> bool { + match self.id() { + Id::Standard(_) => false, + Id::Extended(_) => true, + } + } + + fn is_remote_frame(&self) -> bool { + false + } + + fn id(&self) -> Id { + Self::MESSAGE_ID + } + + fn dlc(&self) -> usize { + self.raw.len() + } + + fn data(&self) -> &[u8] { + &self.raw + } +} +impl core::fmt::Debug for NegativeFactorTest { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + if f.alternate() { + f.debug_struct("NegativeFactorTest") + .field( + "unsigned_negative_factor_signal", + &self.unsigned_negative_factor_signal(), + ) + .field("width_more_than_min_max", &self.width_more_than_min_max()) + .finish() + } else { + f.debug_tuple("NegativeFactorTest") + .field(&self.raw) + .finish() + } + } +} + +impl defmt::Format for NegativeFactorTest { + fn format(&self, f: defmt::Formatter) { + defmt::write!( + f, + "NegativeFactorTest {{ UnsignedNegativeFactorSignal={:?} WidthMoreThanMinMax={:?} }}", + self.unsigned_negative_factor_signal(), + self.width_more_than_min_max(), + ); + } +} + +#[cfg(feature = "arb")] +impl<'a> Arbitrary<'a> for NegativeFactorTest { + fn arbitrary(u: &mut Unstructured<'a>) -> Result { + let unsigned_negative_factor_signal = u.int_in_range(-65535..=0)?; + let width_more_than_min_max = u.int_in_range(-2..=2)?; + NegativeFactorTest::new(unsigned_negative_factor_signal, width_more_than_min_max) + .map_err(|_| arbitrary::Error::IncorrectFormat) + } +} + +/// LargerIntsWithOffsets +/// +/// - Standard ID: 1338 (0x53a) +/// - Size: 8 bytes +/// - Transmitter: Sit +#[derive(Clone, Copy)] +pub struct LargerIntsWithOffsets { + raw: [u8; 8], +} + +impl LargerIntsWithOffsets { + pub const MESSAGE_ID: embedded_can::Id = + Id::Standard(unsafe { StandardId::new_unchecked(0x53a) }); + + pub const TWELVE_MIN: i16 = -1000_i16; + pub const TWELVE_MAX: i16 = 3000_i16; + pub const SIXTEEN_MIN: i32 = -1000_i32; + pub const SIXTEEN_MAX: i32 = 64535_i32; + + /// Construct new LargerIntsWithOffsets from values + pub fn new(twelve: i16, sixteen: i32) -> Result { + let mut res = Self { raw: [0u8; 8] }; + res.set_twelve(twelve)?; + res.set_sixteen(sixteen)?; + Ok(res) + } + + /// Access message payload raw value + pub fn raw(&self) -> &[u8; 8] { + &self.raw + } + + /// Twelve + /// + /// - Min: -1000 + /// - Max: 3000 + /// - Unit: "" + /// - Receivers: XXX + #[inline(always)] + pub fn twelve(&self) -> i16 { + self.twelve_raw() + } + + /// Get raw value of Twelve + /// + /// - Start bit: 0 + /// - Signal size: 12 bits + /// - Factor: 1 + /// - Offset: -1000 + /// - Byte order: LittleEndian + /// - Value type: Unsigned + #[inline(always)] + pub fn twelve_raw(&self) -> i16 { + let signal = self.raw.view_bits::()[0..12].load_le::(); + + let factor = 1; + let signal = signal as i16; + i16::from(signal) + .saturating_mul(factor) + .saturating_sub(1000) + } + + /// Set value of Twelve + #[inline(always)] + pub fn set_twelve(&mut self, value: i16) -> Result<(), CanError> { + if value < -1000_i16 || 3000_i16 < value { + return Err(CanError::ParameterOutOfRange { + message_id: LargerIntsWithOffsets::MESSAGE_ID, + }); + } + let factor = 1; + let value = value + .checked_add(1000) + .ok_or(CanError::ParameterOutOfRange { + message_id: LargerIntsWithOffsets::MESSAGE_ID, + })?; + let value = (value / factor) as u16; + + self.raw.view_bits_mut::()[0..12].store_le(value); + Ok(()) + } + + /// Sixteen + /// + /// - Min: -1000 + /// - Max: 64535 + /// - Unit: "" + /// - Receivers: XXX + #[inline(always)] + pub fn sixteen(&self) -> i32 { + self.sixteen_raw() + } + + /// Get raw value of Sixteen + /// + /// - Start bit: 12 + /// - Signal size: 16 bits + /// - Factor: 1 + /// - Offset: -1000 + /// - Byte order: LittleEndian + /// - Value type: Unsigned + #[inline(always)] + pub fn sixteen_raw(&self) -> i32 { + let signal = self.raw.view_bits::()[12..28].load_le::(); + + let factor = 1; + i32::from(signal) + .saturating_mul(factor) + .saturating_sub(1000) + } + + /// Set value of Sixteen + #[inline(always)] + pub fn set_sixteen(&mut self, value: i32) -> Result<(), CanError> { + if value < -1000_i32 || 64535_i32 < value { + return Err(CanError::ParameterOutOfRange { + message_id: LargerIntsWithOffsets::MESSAGE_ID, + }); + } + let factor = 1; + let value = value + .checked_add(1000) + .ok_or(CanError::ParameterOutOfRange { + message_id: LargerIntsWithOffsets::MESSAGE_ID, + })?; + let value = (value / factor) as u16; + + self.raw.view_bits_mut::()[12..28].store_le(value); + Ok(()) + } +} + +impl core::convert::TryFrom<&[u8]> for LargerIntsWithOffsets { + type Error = CanError; + + #[inline(always)] + fn try_from(payload: &[u8]) -> Result { + if payload.len() != 8 { + return Err(CanError::InvalidPayloadSize); + } + let mut raw = [0u8; 8]; + raw.copy_from_slice(&payload[..8]); + Ok(Self { raw }) + } +} + +impl embedded_can::Frame for LargerIntsWithOffsets { + fn new(id: impl Into, data: &[u8]) -> Option { + if id.into() != Self::MESSAGE_ID { + None + } else { + data.try_into().ok() + } + } + + fn new_remote(_id: impl Into, _dlc: usize) -> Option { + unimplemented!() + } + + fn is_extended(&self) -> bool { + match self.id() { + Id::Standard(_) => false, + Id::Extended(_) => true, + } + } + + fn is_remote_frame(&self) -> bool { + false + } + + fn id(&self) -> Id { + Self::MESSAGE_ID + } + + fn dlc(&self) -> usize { + self.raw.len() + } + + fn data(&self) -> &[u8] { + &self.raw + } +} +impl core::fmt::Debug for LargerIntsWithOffsets { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + if f.alternate() { + f.debug_struct("LargerIntsWithOffsets") + .field("twelve", &self.twelve()) + .field("sixteen", &self.sixteen()) + .finish() + } else { + f.debug_tuple("LargerIntsWithOffsets") + .field(&self.raw) + .finish() + } + } +} + +impl defmt::Format for LargerIntsWithOffsets { + fn format(&self, f: defmt::Formatter) { + defmt::write!( + f, + "LargerIntsWithOffsets {{ Twelve={:?} Sixteen={:?} }}", + self.twelve(), + self.sixteen(), + ); + } +} + +#[cfg(feature = "arb")] +impl<'a> Arbitrary<'a> for LargerIntsWithOffsets { + fn arbitrary(u: &mut Unstructured<'a>) -> Result { + let twelve = u.int_in_range(-1000..=3000)?; + let sixteen = u.int_in_range(-1000..=64535)?; + LargerIntsWithOffsets::new(twelve, sixteen).map_err(|_| arbitrary::Error::IncorrectFormat) + } +} + +/// MsgWithoutSignals +/// +/// - Standard ID: 513 (0x201) +/// - Size: 8 bytes +/// - Transmitter: Ipsum +#[derive(Clone, Copy)] +pub struct MsgWithoutSignals { + raw: [u8; 8], +} + +impl MsgWithoutSignals { + pub const MESSAGE_ID: embedded_can::Id = + Id::Standard(unsafe { StandardId::new_unchecked(0x201) }); + + /// Construct new MsgWithoutSignals from values + pub fn new() -> Result { + let res = Self { raw: [0u8; 8] }; + Ok(res) + } + + /// Access message payload raw value + pub fn raw(&self) -> &[u8; 8] { + &self.raw + } +} + +impl core::convert::TryFrom<&[u8]> for MsgWithoutSignals { + type Error = CanError; + + #[inline(always)] + fn try_from(payload: &[u8]) -> Result { + if payload.len() != 8 { + return Err(CanError::InvalidPayloadSize); + } + let mut raw = [0u8; 8]; + raw.copy_from_slice(&payload[..8]); + Ok(Self { raw }) + } +} + +impl embedded_can::Frame for MsgWithoutSignals { + fn new(id: impl Into, data: &[u8]) -> Option { + if id.into() != Self::MESSAGE_ID { + None + } else { + data.try_into().ok() + } + } + + fn new_remote(_id: impl Into, _dlc: usize) -> Option { + unimplemented!() + } + + fn is_extended(&self) -> bool { + match self.id() { + Id::Standard(_) => false, + Id::Extended(_) => true, + } + } + + fn is_remote_frame(&self) -> bool { + false + } + + fn id(&self) -> Id { + Self::MESSAGE_ID + } + + fn dlc(&self) -> usize { + self.raw.len() + } + + fn data(&self) -> &[u8] { + &self.raw + } +} +impl core::fmt::Debug for MsgWithoutSignals { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + if f.alternate() { + f.debug_struct("MsgWithoutSignals").finish() + } else { + f.debug_tuple("MsgWithoutSignals").field(&self.raw).finish() + } + } +} + +impl defmt::Format for MsgWithoutSignals { + fn format(&self, f: defmt::Formatter) { + defmt::write!(f, "MsgWithoutSignals {{ }}",); + } +} + +#[cfg(feature = "arb")] +impl<'a> Arbitrary<'a> for MsgWithoutSignals { + fn arbitrary(_u: &mut Unstructured<'a>) -> Result { + MsgWithoutSignals::new().map_err(|_| arbitrary::Error::IncorrectFormat) + } +} + +/// TruncatedBeSignal +/// +/// - Standard ID: 9001 (0x2329) +/// - Size: 8 bytes +/// - Transmitter: Ipsum +#[derive(Clone, Copy)] +pub struct TruncatedBeSignal { + raw: [u8; 8], +} + +impl TruncatedBeSignal { + pub const MESSAGE_ID: embedded_can::Id = + Id::Standard(unsafe { StandardId::new_unchecked(0x2329) }); + + pub const FOO_MIN: i16 = -100_i16; + pub const FOO_MAX: i16 = 100_i16; + + /// Construct new TruncatedBeSignal from values + pub fn new(foo: i16) -> Result { + let mut res = Self { raw: [0u8; 8] }; + res.set_foo(foo)?; + Ok(res) + } + + /// Access message payload raw value + pub fn raw(&self) -> &[u8; 8] { + &self.raw + } + + /// Foo + /// + /// - Min: -100 + /// - Max: 100 + /// - Unit: "" + /// - Receivers: Vector__XXX + #[inline(always)] + pub fn foo(&self) -> i16 { + self.foo_raw() + } + + /// Get raw value of Foo + /// + /// - Start bit: 0 + /// - Signal size: 12 bits + /// - Factor: 1 + /// - Offset: 0 + /// - Byte order: BigEndian + /// - Value type: Signed + #[inline(always)] + pub fn foo_raw(&self) -> i16 { + let signal = self.raw.view_bits::()[7..19].load_be::(); + + let factor = 1; + let signal = signal as i16; + i16::from(signal).saturating_mul(factor).saturating_add(0) + } + + /// Set value of Foo + #[inline(always)] + pub fn set_foo(&mut self, value: i16) -> Result<(), CanError> { + if value < -100_i16 || 100_i16 < value { + return Err(CanError::ParameterOutOfRange { + message_id: TruncatedBeSignal::MESSAGE_ID, + }); + } + let factor = 1; + let value = value.checked_sub(0).ok_or(CanError::ParameterOutOfRange { + message_id: TruncatedBeSignal::MESSAGE_ID, + })?; + let value = (value / factor) as i16; + + let value = u16::from_ne_bytes(value.to_ne_bytes()); + self.raw.view_bits_mut::()[7..19].store_be(value); + Ok(()) + } +} + +impl core::convert::TryFrom<&[u8]> for TruncatedBeSignal { + type Error = CanError; + + #[inline(always)] + fn try_from(payload: &[u8]) -> Result { + if payload.len() != 8 { + return Err(CanError::InvalidPayloadSize); + } + let mut raw = [0u8; 8]; + raw.copy_from_slice(&payload[..8]); + Ok(Self { raw }) + } +} + +impl embedded_can::Frame for TruncatedBeSignal { + fn new(id: impl Into, data: &[u8]) -> Option { + if id.into() != Self::MESSAGE_ID { + None + } else { + data.try_into().ok() + } + } + + fn new_remote(_id: impl Into, _dlc: usize) -> Option { + unimplemented!() + } + + fn is_extended(&self) -> bool { + match self.id() { + Id::Standard(_) => false, + Id::Extended(_) => true, + } + } + + fn is_remote_frame(&self) -> bool { + false + } + + fn id(&self) -> Id { + Self::MESSAGE_ID + } + + fn dlc(&self) -> usize { + self.raw.len() + } + + fn data(&self) -> &[u8] { + &self.raw + } +} +impl core::fmt::Debug for TruncatedBeSignal { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + if f.alternate() { + f.debug_struct("TruncatedBeSignal") + .field("foo", &self.foo()) + .finish() + } else { + f.debug_tuple("TruncatedBeSignal").field(&self.raw).finish() + } + } +} + +impl defmt::Format for TruncatedBeSignal { + fn format(&self, f: defmt::Formatter) { + defmt::write!(f, "TruncatedBeSignal {{ Foo={:?} }}", self.foo(),); + } +} + +#[cfg(feature = "arb")] +impl<'a> Arbitrary<'a> for TruncatedBeSignal { + fn arbitrary(u: &mut Unstructured<'a>) -> Result { + let foo = u.int_in_range(-100..=100)?; + TruncatedBeSignal::new(foo).map_err(|_| arbitrary::Error::IncorrectFormat) + } +} + +/// TruncatedLeSignal +/// +/// - Standard ID: 9002 (0x232a) +/// - Size: 8 bytes +/// - Transmitter: Ipsum +#[derive(Clone, Copy)] +pub struct TruncatedLeSignal { + raw: [u8; 8], +} + +impl TruncatedLeSignal { + pub const MESSAGE_ID: embedded_can::Id = + Id::Standard(unsafe { StandardId::new_unchecked(0x232a) }); + + pub const FOO_MIN: i16 = -100_i16; + pub const FOO_MAX: i16 = 100_i16; + + /// Construct new TruncatedLeSignal from values + pub fn new(foo: i16) -> Result { + let mut res = Self { raw: [0u8; 8] }; + res.set_foo(foo)?; + Ok(res) + } + + /// Access message payload raw value + pub fn raw(&self) -> &[u8; 8] { + &self.raw + } + + /// Foo + /// + /// - Min: -100 + /// - Max: 100 + /// - Unit: "" + /// - Receivers: Vector__XXX + #[inline(always)] + pub fn foo(&self) -> i16 { + self.foo_raw() + } + + /// Get raw value of Foo + /// + /// - Start bit: 0 + /// - Signal size: 12 bits + /// - Factor: 1 + /// - Offset: 0 + /// - Byte order: LittleEndian + /// - Value type: Signed + #[inline(always)] + pub fn foo_raw(&self) -> i16 { + let signal = self.raw.view_bits::()[0..12].load_le::(); + + let factor = 1; + let signal = signal as i16; + i16::from(signal).saturating_mul(factor).saturating_add(0) + } + + /// Set value of Foo + #[inline(always)] + pub fn set_foo(&mut self, value: i16) -> Result<(), CanError> { + if value < -100_i16 || 100_i16 < value { + return Err(CanError::ParameterOutOfRange { + message_id: TruncatedLeSignal::MESSAGE_ID, + }); + } + let factor = 1; + let value = value.checked_sub(0).ok_or(CanError::ParameterOutOfRange { + message_id: TruncatedLeSignal::MESSAGE_ID, + })?; + let value = (value / factor) as i16; + + let value = u16::from_ne_bytes(value.to_ne_bytes()); + self.raw.view_bits_mut::()[0..12].store_le(value); + Ok(()) + } +} + +impl core::convert::TryFrom<&[u8]> for TruncatedLeSignal { + type Error = CanError; + + #[inline(always)] + fn try_from(payload: &[u8]) -> Result { + if payload.len() != 8 { + return Err(CanError::InvalidPayloadSize); + } + let mut raw = [0u8; 8]; + raw.copy_from_slice(&payload[..8]); + Ok(Self { raw }) + } +} + +impl embedded_can::Frame for TruncatedLeSignal { + fn new(id: impl Into, data: &[u8]) -> Option { + if id.into() != Self::MESSAGE_ID { + None + } else { + data.try_into().ok() + } + } + + fn new_remote(_id: impl Into, _dlc: usize) -> Option { + unimplemented!() + } + + fn is_extended(&self) -> bool { + match self.id() { + Id::Standard(_) => false, + Id::Extended(_) => true, + } + } + + fn is_remote_frame(&self) -> bool { + false + } + + fn id(&self) -> Id { + Self::MESSAGE_ID + } + + fn dlc(&self) -> usize { + self.raw.len() + } + + fn data(&self) -> &[u8] { + &self.raw + } +} +impl core::fmt::Debug for TruncatedLeSignal { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + if f.alternate() { + f.debug_struct("TruncatedLeSignal") + .field("foo", &self.foo()) + .finish() + } else { + f.debug_tuple("TruncatedLeSignal").field(&self.raw).finish() + } + } +} + +impl defmt::Format for TruncatedLeSignal { + fn format(&self, f: defmt::Formatter) { + defmt::write!(f, "TruncatedLeSignal {{ Foo={:?} }}", self.foo(),); + } +} + +#[cfg(feature = "arb")] +impl<'a> Arbitrary<'a> for TruncatedLeSignal { + fn arbitrary(u: &mut Unstructured<'a>) -> Result { + let foo = u.int_in_range(-100..=100)?; + TruncatedLeSignal::new(foo).map_err(|_| arbitrary::Error::IncorrectFormat) + } +} + +/// MsgExtendedId +/// +/// - Extended ID: 4660 (0x1234) +/// - Size: 8 bytes +/// - Transmitter: Sit +#[derive(Clone, Copy)] +pub struct MsgExtendedId { + raw: [u8; 8], +} + +impl MsgExtendedId { + pub const MESSAGE_ID: embedded_can::Id = + Id::Extended(unsafe { ExtendedId::new_unchecked(0x1234) }); + + pub const DUMMY_MIN: u8 = 0_u8; + pub const DUMMY_MAX: u8 = 3_u8; + + /// Construct new MsgExtendedId from values + pub fn new(dummy: u8) -> Result { + let mut res = Self { raw: [0u8; 8] }; + res.set_dummy(dummy)?; + Ok(res) + } + + /// Access message payload raw value + pub fn raw(&self) -> &[u8; 8] { + &self.raw + } + + /// Dummy + /// + /// - Min: 0 + /// - Max: 3 + /// - Unit: "" + /// - Receivers: XXX + #[inline(always)] + pub fn dummy(&self) -> u8 { + self.dummy_raw() + } + + /// Get raw value of Dummy + /// + /// - Start bit: 15 + /// - Signal size: 2 bits + /// - Factor: 1 + /// - Offset: 0 + /// - Byte order: BigEndian + /// - Value type: Unsigned + #[inline(always)] + pub fn dummy_raw(&self) -> u8 { + let signal = self.raw.view_bits::()[8..10].load_be::(); + + let factor = 1; + u8::from(signal).saturating_mul(factor).saturating_add(0) + } + + /// Set value of Dummy + #[inline(always)] + pub fn set_dummy(&mut self, value: u8) -> Result<(), CanError> { + if value < 0_u8 || 3_u8 < value { + return Err(CanError::ParameterOutOfRange { + message_id: MsgExtendedId::MESSAGE_ID, + }); + } + let factor = 1; + let value = value.checked_sub(0).ok_or(CanError::ParameterOutOfRange { + message_id: MsgExtendedId::MESSAGE_ID, + })?; + let value = (value / factor) as u8; + + self.raw.view_bits_mut::()[8..10].store_be(value); + Ok(()) + } +} + +impl core::convert::TryFrom<&[u8]> for MsgExtendedId { + type Error = CanError; + + #[inline(always)] + fn try_from(payload: &[u8]) -> Result { + if payload.len() != 8 { + return Err(CanError::InvalidPayloadSize); + } + let mut raw = [0u8; 8]; + raw.copy_from_slice(&payload[..8]); + Ok(Self { raw }) + } +} + +impl embedded_can::Frame for MsgExtendedId { + fn new(id: impl Into, data: &[u8]) -> Option { + if id.into() != Self::MESSAGE_ID { + None + } else { + data.try_into().ok() + } + } + + fn new_remote(_id: impl Into, _dlc: usize) -> Option { + unimplemented!() + } + + fn is_extended(&self) -> bool { + match self.id() { + Id::Standard(_) => false, + Id::Extended(_) => true, + } + } + + fn is_remote_frame(&self) -> bool { + false + } + + fn id(&self) -> Id { + Self::MESSAGE_ID + } + + fn dlc(&self) -> usize { + self.raw.len() + } + + fn data(&self) -> &[u8] { + &self.raw + } +} +impl core::fmt::Debug for MsgExtendedId { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + if f.alternate() { + f.debug_struct("MsgExtendedId") + .field("dummy", &self.dummy()) + .finish() + } else { + f.debug_tuple("MsgExtendedId").field(&self.raw).finish() + } + } +} + +impl defmt::Format for MsgExtendedId { + fn format(&self, f: defmt::Formatter) { + defmt::write!(f, "MsgExtendedId {{ Dummy={:?} }}", self.dummy(),); + } +} + +#[cfg(feature = "arb")] +impl<'a> Arbitrary<'a> for MsgExtendedId { + fn arbitrary(u: &mut Unstructured<'a>) -> Result { + let dummy = u.int_in_range(0..=3)?; + MsgExtendedId::new(dummy).map_err(|_| arbitrary::Error::IncorrectFormat) + } +} + +/// This is just to make testing easier +#[allow(dead_code)] +fn main() {} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum CanError { + UnknownMessageId(embedded_can::Id), + /// Signal parameter is not within the range + /// defined in the dbc + ParameterOutOfRange { + /// dbc message id + message_id: embedded_can::Id, + }, + InvalidPayloadSize, + /// Multiplexor value not defined in the dbc + InvalidMultiplexor { + /// dbc message id + message_id: embedded_can::Id, + /// Multiplexor value not defined in the dbc + multiplexor: u16, + }, +} + +impl core::fmt::Display for CanError { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + write!(f, "{:?}", self) + } +} +#[cfg(feature = "std")] +impl std::error::Error for CanError {} +#[cfg(feature = "arb")] +trait UnstructuredFloatExt { + fn float_in_range(&mut self, range: core::ops::RangeInclusive) -> arbitrary::Result; +} + +#[cfg(feature = "arb")] +impl UnstructuredFloatExt for arbitrary::Unstructured<'_> { + fn float_in_range(&mut self, range: core::ops::RangeInclusive) -> arbitrary::Result { + let min = range.start(); + let max = range.end(); + let steps = u32::MAX; + let factor = (max - min) / (steps as f32); + let random_int: u32 = self.int_in_range(0..=steps)?; + let random = min + factor * (random_int as f32); + Ok(random) + } +} diff --git a/testing/can-messages/build.rs b/testing/can-messages/build.rs index 5d7a7d0..2e863de 100644 --- a/testing/can-messages/build.rs +++ b/testing/can-messages/build.rs @@ -8,7 +8,7 @@ use std::{ fn main() -> Result<()> { let out_file = "src/messages.rs"; - let dbc_file = fs::read("../dbc-examples/example.dbc")?; + let dbc_file = fs::read_to_string("../dbc-examples/example.dbc")?; let mut out = BufWriter::new(File::create(out_file)?); println!("cargo:rerun-if-changed=../dbc-examples/example.dbc"); println!("cargo:rerun-if-changed=../../src"); diff --git a/testing/rust-integration/src/main.rs b/testing/rust-integration/src/main.rs index 7f33e4a..1b582c8 100644 --- a/testing/rust-integration/src/main.rs +++ b/testing/rust-integration/src/main.rs @@ -5,7 +5,7 @@ fn main() { let input = std::env::args() .nth(1) .expect("first cli arg should be candump file (`candump vcan0 -l`)"); - let file = std::fs::read_to_string(&input).unwrap(); + let file = std::fs::read_to_string(input).unwrap(); for line in file.lines() { let data = line.split(' ').last().unwrap(); let (id, payload) = {