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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions Cargo.lock

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

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ bacnet-macros = { path = "./bacnet-macros", version = "0.1.0" }

[dev-dependencies]
simple_logger = "5.0.0"
base64 = "0.22.1"
chrono = { version = "0.4.28" }
clap = { version = "4.5.4", features = ["derive"] }
tokio = { version = "1.40.0", features = ["rt-multi-thread", "net", "macros"] }
Expand Down
1 change: 1 addition & 0 deletions fixtures/datalink_no_segment
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
gQoCTgEI/iABCTCZDgwAAABkHilNTnUYAEktMzNAOV9RQUMyX1ZvbHRTeXN0UGhOTylVXpEAkQNfKXVOkQVPKW9OggQATx8MAAAAZR4pTU51GQBJLTMzQDlfUUFDMl9Wb2x0U3lzdFBoUGhPKVVekQCRA18pdU6RBU8pb06CBABPHwwAAABmHilNTnUYAEktMzNAOV9RQUMyX0N1cnJlbnRTeXN0TylVXpEAkQNfKXVOkQNPKW9OggQATx8MAAAAZx4pTU51FgBJLTMzQDlfUUFDMl9GcmVxdWVuY3lPKVVOREJH+uFPKXVOkRtPKW9OggQATx8MAAAAaB4pTU51FgBJLTMzQDlfUUFDMl9Wb2x0UGhOVjFPKVVORENoYUhPKXVOkQVPKW9OggQATx8MAAAAaR4pTU51FgBJLTMzQDlfUUFDMl9Wb2x0UGhOVjJPKVVORENouFJPKXVOkQVPKW9OggQATx8MAAAAah4pTU51FgBJLTMzQDlfUUFDMl9Wb2x0UGhOVjNPKVVORENoczNPKXVOkQVPKW9OggQATx8MAAAAax4pTU51FgBJLTMzQDlfUUFDMl9Wb2x0UGhOVm5PKVVekQCRA18pdU6RBU8pb06CBABPHwwAAABsHilNTnUYAEktMzNAOV9RQUMyX1ZvbHRQaFBoVTEyTylVTkRDyXcKTyl1TpEFTylvToIEAE8fDAAAAG0eKU1OdRgASS0zM0A5X1FBQzJfVm9sdFBoUGhVMjNPKVVOREPJVHtPKXVOkQVPKW9OggQATx8=
4 changes: 2 additions & 2 deletions src/application_protocol/application_pdu.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ pub enum ApplicationPdu<'a> {
ComplexAck(ComplexAck<'a>),
SimpleAck(SimpleAck),
Error(ConfirmedBacnetError),
Segment(Segment<'a>),
Segment(Segment),
SegmentAck(SegmentAck),
// add more here (see ApduType)
}
Expand Down Expand Up @@ -88,7 +88,7 @@ impl From<u8> for MaxSegments {
}
}

#[derive(Debug, Clone)]
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[repr(u8)]
pub enum MaxAdpu {
Expand Down
10 changes: 3 additions & 7 deletions src/application_protocol/segment.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@

#[cfg(feature = "alloc")]
use {
crate::common::spooky::Phantom,
alloc::{vec, vec::Vec},
};

Expand Down Expand Up @@ -34,7 +33,7 @@ pub struct Segment<'a> {
#[cfg(feature = "alloc")]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[derive(Debug, Clone)]
pub struct Segment<'a> {
pub struct Segment {
pub apdu_type: ApduType,
pub more_follows: bool,

Expand All @@ -45,10 +44,9 @@ pub struct Segment<'a> {

// apdu data
pub data: Vec<u8>,
_phantom: &'a Phantom,
}

impl<'a> Segment<'a> {
impl Segment {
#[cfg(feature = "alloc")]
pub fn new(
apdu_type: ApduType,
Expand All @@ -59,7 +57,6 @@ impl<'a> Segment<'a> {
service_choice: u8,
data: Vec<u8>,
) -> Self {
use crate::common::spooky::PHANTOM;

Segment {
apdu_type,
Expand All @@ -68,8 +65,7 @@ impl<'a> Segment<'a> {
sequence_number,
window_size,
service_choice,
data,
_phantom: &PHANTOM,
data
}
}

Expand Down
22 changes: 17 additions & 5 deletions src/application_protocol/services/i_am.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::{
application_protocol::unconfirmed::UnconfirmedServiceChoice,
application_protocol::{application_pdu::MaxAdpu, unconfirmed::UnconfirmedServiceChoice},
common::{
error::Error,
helper::{
Expand All @@ -17,7 +17,7 @@ use crate::{
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct IAm {
pub device_id: ObjectId,
pub max_apdu: usize,
pub max_apdu: MaxAdpu,
pub segmentation: Segmentation,
pub vendor_id: u16,
}
Expand All @@ -26,7 +26,7 @@ impl IAm {
pub fn encode(&self, writer: &mut Writer) {
writer.push(UnconfirmedServiceChoice::IAm as u8);
encode_application_object_id(writer, &self.device_id);
encode_application_unsigned(writer, self.max_apdu as u64);
encode_application_unsigned(writer, self.max_apdu.clone() as u64);
encode_application_enumerated(writer, self.segmentation.clone() as u32);
encode_application_unsigned(writer, self.vendor_id as u64);
}
Expand All @@ -53,8 +53,20 @@ impl IAm {
"expected unsigned_int tag type for IAm max_apdu field",
));
}
let max_apdu = decode_unsigned(tag.value, reader, buf)?;
let max_apdu = max_apdu as usize;
let raw_max_apdu = decode_unsigned(tag.value, reader, buf)?;
let max_apdu: MaxAdpu = match raw_max_apdu {
0 => MaxAdpu::_0,
128 => MaxAdpu::_128,
206 => MaxAdpu::_206,
480 => MaxAdpu::_480,
1024 => MaxAdpu::_1024,
1476 => MaxAdpu::_1476,
_ => {
return Err(Error::InvalidValueValue(
"unexpected value for maximum apdu size", raw_max_apdu
));
}
};

// parse a tag then segmentation
let tag = Tag::decode(reader, buf)?;
Expand Down
31 changes: 23 additions & 8 deletions src/application_protocol/services/read_range.rs
Original file line number Diff line number Diff line change
Expand Up @@ -369,35 +369,35 @@ impl<'a> ReadRangeItem<'a> {
reader,
buf,
TagNumber::ContextSpecificOpening(Self::DATE_TIME_TAG),
"ReadRangeItem decode",
"ReadRangeItem decode open date time",
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

let me know if I should back these changes out - but it made it much easier to debug.

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

They are a little redundant because you have access to the Tag there but if they made your life easier then I have no problem at all putting them in. They are there for debugging after all.

)?;
Tag::decode_expected(
reader,
buf,
TagNumber::Application(ApplicationTagNumber::Date),
"ReadRangeItem decode",
"ReadRangeItem decode date",
)?;
let date = Date::decode(reader, buf)?;
Tag::decode_expected(
reader,
buf,
TagNumber::Application(ApplicationTagNumber::Time),
"ReadRangeItem decode",
"ReadRangeItem decode time",
)?;
let time = Time::decode(reader, buf)?;
Tag::decode_expected(
reader,
buf,
TagNumber::ContextSpecificClosing(Self::DATE_TIME_TAG),
"ReadRangeItem decode",
"ReadRangeItem decode close date time",
)?;

// value
Tag::decode_expected(
reader,
buf,
TagNumber::ContextSpecificOpening(Self::VALUE_TAG),
"ReadRangeItem decode",
"ReadRangeItem decode open value",
)?;
let tag = Tag::decode(reader, buf)?;
let value_type: ReadRangeValueType = match tag.number {
Expand All @@ -410,22 +410,37 @@ impl<'a> ReadRangeItem<'a> {
ReadRangeValueType::Real => {
let value = f32::from_be_bytes(reader.read_bytes(buf)?);
ReadRangeValue::Real(value)
}
},
ReadRangeValueType::Bool => {
let bytes = reader.read_byte(buf)?;
ReadRangeValue::Bool(bytes > 0)
},
ReadRangeValueType::Unsigned => {
let value = u32::from_be_bytes(reader.read_bytes(buf)?);
ReadRangeValue::Unsigned(value)
},
ReadRangeValueType::Signed => {
let value = i32::from_be_bytes(reader.read_bytes(buf)?);
ReadRangeValue::Signed(value)
},
ReadRangeValueType::Null => {
ReadRangeValue::Null
},
x => return Err(Error::Unimplemented(Unimplemented::ReadRangeValueType(x))),
};
Tag::decode_expected(
reader,
buf,
TagNumber::ContextSpecificClosing(Self::VALUE_TAG),
"ReadRangeItem decode",
"ReadRangeItem decode close value",
)?;

// status flags
Tag::decode_expected(
reader,
buf,
TagNumber::ContextSpecific(Self::STATUS_FLAGS_TAG),
"ReadRangeItem decode",
"ReadRangeItem decode status",
)?;
let status_flags = BitString::decode(&PropertyId::PropStatusFlags, tag.value, reader, buf)?;

Expand Down
1 change: 1 addition & 0 deletions src/common/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ use crate::{
pub enum Error {
Length((&'static str, u32)),
InvalidValue(&'static str),
InvalidValueValue(&'static str, u64),
InvalidVariant((&'static str, u32)),
Unimplemented(Unimplemented),
SegmentationNotSupported,
Expand Down
4 changes: 2 additions & 2 deletions src/common/spec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ pub const BACNET_MAX_PRIORITY: u32 = 16;

/*
TODO: use derive_more when it reaches 1.0 (to automatically impl TryFrom for all enums)
#[derive(Debug, Clone, derive_more::TryFrom)]
#[derive(Debug, Clone, derive_more::TryFrom, PartialEq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[try_from(repr)]
Expand All @@ -25,7 +25,7 @@ pub enum Segmentation {
}
*/

#[derive(Debug, Clone)]
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[repr(u32)]
Expand Down
7 changes: 7 additions & 0 deletions src/common/time_value.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ pub enum SimpleApplicationDataValue {
Real(f32),
Double(f64),
Enumerated(Enumerated),
Null,
}

impl SimpleApplicationDataValue {
Expand All @@ -37,6 +38,9 @@ impl SimpleApplicationDataValue {
Self::Enumerated(_) => {
Tag::new(TagNumber::Application(ApplicationTagNumber::Enumerated), 1)
}
Self::Null => {
Tag::new(TagNumber::Application(ApplicationTagNumber::Null), 0)
}
}
}
pub fn decode(tag: &Tag, reader: &mut Reader, buf: &[u8]) -> Result<Self, Error> {
Expand Down Expand Up @@ -75,6 +79,9 @@ impl SimpleApplicationDataValue {
let value = Enumerated::Binary(value);
Ok(SimpleApplicationDataValue::Enumerated(value))
}
ApplicationTagNumber::Null => {
Ok(SimpleApplicationDataValue::Null)
}

x => Err(Error::Unimplemented(Unimplemented::ApplicationTagNumber(
x.clone(),
Expand Down
2 changes: 1 addition & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#![no_std]
#![cfg_attr(not(test), no_std)]
#![allow(clippy::large_enum_variant)]

// This library supports the IP version of bacnet and this is how the network packet is wrapped:
Expand Down
39 changes: 37 additions & 2 deletions src/network_protocol/data_link.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,10 @@ impl<'a> DataLink<'a> {
// const BVLC_ORIGINAL_BROADCAST_NPDU: u8 = 11;

pub fn new(function: DataLinkFunction, npdu: Option<NetworkPdu<'a>>) -> Self {
Self { function, npdu }
Self {
function,
npdu,
}
}

pub fn new_confirmed_req(req: ConfirmedRequest<'a>) -> Self {
Expand Down Expand Up @@ -120,6 +123,38 @@ impl<'a> DataLink<'a> {
_ => None,
};

Ok(Self { function, npdu })
Ok(Self {
function,
npdu,
})
}
}

#[cfg(test)]
mod tests {
use std::{fs, path::Path};

use crate::{common::io::Reader, network_protocol::network_pdu::Addr};
use base64::{Engine as _, engine::general_purpose::STANDARD};
use super::DataLink;

fn load_fixture(name: &str) -> std::io::Result<Vec<u8>> {
let path = Path::new("fixtures").join(name);
let base64_string = fs::read_to_string(path)?;
Ok(STANDARD.decode(base64_string.strip_suffix("\n").unwrap())
.map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?)
}

#[test]
fn decode_no_segment() -> std::io::Result<()> {
let buf = load_fixture("datalink_no_segment")?;
let mut reader = Reader::new_with_len(buf.len());
let datalink = DataLink::decode(&mut reader, &buf).unwrap();
let npdu = datalink.npdu.unwrap();
let source = npdu.src.unwrap();
assert_eq!(source.net, 65056);
assert_eq!(source.addr.unwrap(), Addr::Mac(9));
assert!(npdu.dst.is_none());
Ok(())
}
}
Loading