From a02d526b4686865bcf381b631f88cdede632e4fc Mon Sep 17 00:00:00 2001 From: jadamcrain Date: Thu, 26 Nov 2026 14:37:44 -0800 Subject: [PATCH 1/5] Keep ReadRequest and Request apart in Rust and the bindings ReadRequest is now opaque and holds only READ headers; Headers is renamed Request. The bindings gain a read_request class for reads and polls, so a read can no longer carry write headers that were silently dropped. --- dnp3/src/app/attr.rs | 4 +- .../src/master/association/scheduler_tests.rs | 4 +- dnp3/src/master/builder.rs | 2 +- dnp3/src/master/handler.rs | 6 +- dnp3/src/master/poll.rs | 2 +- dnp3/src/master/request.rs | 806 ++++++++++-------- dnp3/src/master/tasks/empty_response.rs | 10 +- dnp3/src/master/tests/link_frames.rs | 2 +- dnp3/src/master/tests/outcomes.rs | 27 +- dnp3/src/master/tests/read_errors.rs | 10 +- dnp3/src/master/tests/read_types.rs | 9 +- dnp3/src/master/tests/scheduling.rs | 4 +- dnp3/src/master/tests/shared_link.rs | 4 +- dnp3/src/master/tests/startup.rs | 2 +- dnp3/src/master/tests/time_sync.rs | 2 +- dnp3/src/no_panic_check/encode.rs | 58 +- examples/master/src/main.rs | 34 +- ffi/bindings/c/master_example.c | 33 +- ffi/bindings/c/master_example.cpp | 17 +- ffi/bindings/c/smoke_test.c | 4 +- ffi/bindings/c/smoke_test.cpp | 2 +- ffi/bindings/dotnet/dnp3-tests/SmokeTest.cs | 2 +- .../dotnet/examples/master/Program.cs | 17 +- .../io/stepfunc/dnp3/tests/SmokeTest.java | 2 +- .../stepfunc/dnp3/examples/MasterExample.java | 19 +- ffi/dnp3-ffi/src/master/functions.rs | 22 +- ffi/dnp3-ffi/src/request.rs | 310 ++++--- ffi/dnp3-schema/src/master/mod.rs | 10 +- ffi/dnp3-schema/src/master/request.rs | 383 +++++---- ffi/dnp3-schema/src/variation.rs | 2 +- guide/docs/api/master/association_polls.mdx | 7 +- 31 files changed, 1043 insertions(+), 773 deletions(-) diff --git a/dnp3/src/app/attr.rs b/dnp3/src/app/attr.rs index 8c8e9b04..8352fffe 100644 --- a/dnp3/src/app/attr.rs +++ b/dnp3/src/app/attr.rs @@ -2156,7 +2156,7 @@ mod test { use crate::app::parse::parser::{HeaderCollection, ObjectHeader, Width}; use crate::app::FunctionCode; use crate::master::error::TaskErrorKind; - use crate::master::Headers; + use crate::master::Request; use proptest::prelude::*; /// group, variation, qualifier, start and stop @@ -2377,7 +2377,7 @@ mod test { /// written fn write(attr: &OwnedAttribute, buffer: &mut [u8]) -> (Result<(), TaskErrorKind>, Vec) { let mut cursor = WriteCursor::new(buffer); - let result = Headers::new() + let result = Request::new() .add_attribute(attr.clone()) .write(&mut HeaderWriter::new(&mut cursor)); (result, cursor.written().to_vec()) diff --git a/dnp3/src/master/association/scheduler_tests.rs b/dnp3/src/master/association/scheduler_tests.rs index 18305a6a..45abcd97 100644 --- a/dnp3/src/master/association/scheduler_tests.rs +++ b/dnp3/src/master/association/scheduler_tests.rs @@ -773,7 +773,7 @@ impl System { fn queue_request(&mut self, index: usize) { let (promise, reply) = Promise::one_shot(); - let task = SingleReadTask::new(ReadRequest::ClassScan(Classes::all()), promise); + let task = SingleReadTask::new(ReadRequest::class_scan(Classes::all()), promise); self.association(index) .process_message(AssociationMsgType::QueueTask(Task::from(task).into()), true); self.requests.push(reply); @@ -927,7 +927,7 @@ async fn apply( let id = system .association(index) .polls - .add(ReadRequest::ClassScan(Classes::all()), period); + .add(ReadRequest::class_scan(Classes::all()), period); system.polls[index].push(id); } } diff --git a/dnp3/src/master/builder.rs b/dnp3/src/master/builder.rs index b7925e27..984ba069 100644 --- a/dnp3/src/master/builder.rs +++ b/dnp3/src/master/builder.rs @@ -571,7 +571,7 @@ mod tests { let mut association = add_stream_association(&mut builder, address).unwrap(); let mut poll = association.add_poll( - ReadRequest::ClassScan(crate::master::Classes::all()), + ReadRequest::class_scan(crate::master::Classes::all()), Duration::from_secs(5), ); let handle = association.into_handle(); diff --git a/dnp3/src/master/handler.rs b/dnp3/src/master/handler.rs index 444d0124..1ddf0fe7 100644 --- a/dnp3/src/master/handler.rs +++ b/dnp3/src/master/handler.rs @@ -36,7 +36,7 @@ use crate::master::tasks::time::PendingTimeSync; use crate::master::tasks::{OneShot, QueuedTask, Task}; use crate::master::{ AuthKey, BlockNumber, DeadBandHeader, DirReadConfig, FileCredentials, FileError, FileHandle, - FileInfo, FileMode, FileReadConfig, FileReader, Headers, OpenFile, ReadHandler, + FileInfo, FileMode, FileReadConfig, FileReader, OpenFile, ReadHandler, Request, }; use crate::phys::PhysAddr; use crate::transport::FragmentAddr; @@ -310,10 +310,10 @@ impl AssociationHandle { pub async fn send_and_expect_empty_response( &mut self, function: FunctionCode, - headers: Headers, + request: Request, ) -> Result<(), TaskError> { let (promise, rx) = Promise::one_shot(); - let task = OneShot::new(EmptyResponseRequest::new(function, headers), promise); + let task = OneShot::new(EmptyResponseRequest::new(function, request), promise); self.send_task(task).await?; await_result(rx).await } diff --git a/dnp3/src/master/poll.rs b/dnp3/src/master/poll.rs index 38b72b9f..ffb3996a 100644 --- a/dnp3/src/master/poll.rs +++ b/dnp3/src/master/poll.rs @@ -270,7 +270,7 @@ mod tests { use crate::master::Classes; fn request() -> ReadRequest { - ReadRequest::ClassScan(Classes::all()) + ReadRequest::class_scan(Classes::all()) } #[test] diff --git a/dnp3/src/master/request.rs b/dnp3/src/master/request.rs index 379d241e..251f22d1 100644 --- a/dnp3/src/master/request.rs +++ b/dnp3/src/master/request.rs @@ -83,53 +83,6 @@ pub struct Classes { pub events: EventClasses, } -/// struct representing a one-byte range scan -#[derive(Copy, Clone, Debug, PartialEq, Eq)] -pub struct OneByteRangeScan { - /// variation to READ - pub variation: Variation, - /// start address of the READ - pub start: u8, - /// stop address of the READ - pub stop: u8, -} - -/// struct representing a two-byte range scan -#[derive(Copy, Clone, Debug, PartialEq, Eq)] -pub struct TwoByteRangeScan { - /// variation to READ - pub variation: Variation, - /// start address of the READ - pub start: u16, - /// stop address of the READ - pub stop: u16, -} - -/// struct representing an "all objects" (QC = 0x06) scan -#[derive(Copy, Clone, Debug, PartialEq, Eq)] -pub struct AllObjectsScan { - /// variation to READ - pub variation: Variation, -} - -/// struct representing a one-byte limited count scan -#[derive(Copy, Clone, Debug, PartialEq, Eq)] -pub struct OneByteLimitedCountScan { - /// variation to READ - pub variation: Variation, - /// maximum number of events - pub count: u8, -} - -/// struct representing a two-byte limited count scan -#[derive(Copy, Clone, Debug, PartialEq, Eq)] -pub struct TwoByteLimitedCountScan { - /// variation to READ - pub variation: Variation, - /// maximum number of events - pub count: u16, -} - /// Represents a single header in a WRITE request to modify dead-bands within the outstation #[derive(Debug, Clone)] pub struct DeadBandHeader { @@ -249,16 +202,7 @@ impl EventClasses { } pub(crate) fn write(self, writer: &mut HeaderWriter) -> Result<(), scursor::WriteError> { - if self.class1 { - writer.write_all_objects_header(Variation::Group60Var2)?; - } - if self.class2 { - writer.write_all_objects_header(Variation::Group60Var3)?; - } - if self.class3 { - writer.write_all_objects_header(Variation::Group60Var4)?; - } - Ok(()) + Classes::new(false, self).write(writer) } } @@ -306,152 +250,171 @@ impl Classes { } pub(crate) fn write(self, writer: &mut HeaderWriter) -> Result<(), scursor::WriteError> { - self.events.write(writer)?; - if self.class0 { - writer.write_all_objects_header(Variation::Group60Var1)?; + for variation in self.variations() { + writer.write_all_objects_header(variation)?; } Ok(()) } + + /// the class variations to read, events in classes 1, 2 and 3 first, then class 0 + fn variations(self) -> impl Iterator { + [ + (self.events.class1, Variation::Group60Var2), + (self.events.class2, Variation::Group60Var3), + (self.events.class3, Variation::Group60Var4), + (self.class0, Variation::Group60Var1), + ] + .into_iter() + .filter_map(|(enabled, variation)| enabled.then_some(variation)) + } } -impl OneByteRangeScan { - /// construct a `OneByteRangeScan` from its fields - pub fn new(variation: Variation, start: u8, stop: u8) -> Self { - Self { - variation, - start, - stop, - } +/// The object headers of a READ, for one-time reads and polls +/// +/// Only headers that are valid in a READ can be added. A request that also writes or freezes +/// objects is a [`Request`]. +#[derive(Clone, Debug)] +pub struct ReadRequest { + inner: ReadInner, +} + +/// Single headers and class scans don't allocate, since polls clone their request every period +#[derive(Clone, Debug)] +enum ReadInner { + Single(ReadHeader), + ClassScan(Classes), + Multiple(Vec), +} + +impl ReadRequest { + /// Read the specified classes: events in classes 1, 2 and 3, then class 0 + pub fn class_scan(classes: Classes) -> Self { + Self::from_inner(ReadInner::ClassScan(classes)) } - pub(crate) fn write(self, writer: &mut HeaderWriter) -> Result<(), scursor::WriteError> { - writer.write_range_only(self.variation, self.start, self.stop) + /// Read every object of a variation, with an all objects header (0x06) + pub fn all_objects(variation: Variation) -> Self { + Self::single(ReadHeader::AllObjects { variation }) } -} -impl TwoByteRangeScan { - /// construct a `TwoByteRangeScan` from its fields - pub fn new(variation: Variation, start: u16, stop: u16) -> Self { - Self { + /// Read a range of a variation, with an 8-bit start/stop header (0x00) + pub fn one_byte_range(variation: Variation, start: u8, stop: u8) -> Self { + Self::single(ReadHeader::Range8 { variation, start, stop, - } - } - - pub(crate) fn write(self, writer: &mut HeaderWriter) -> Result<(), scursor::WriteError> { - writer.write_range_only(self.variation, self.start, self.stop) + }) } -} -impl AllObjectsScan { - /// construct an `AllObjectsScan` from the variation - pub fn new(variation: Variation) -> Self { - Self { variation } + /// Read a range of a variation, with a 16-bit start/stop header (0x01) + pub fn two_byte_range(variation: Variation, start: u16, stop: u16) -> Self { + Self::single(ReadHeader::Range16 { + variation, + start, + stop, + }) } - pub(crate) fn write(self, writer: &mut HeaderWriter) -> Result<(), scursor::WriteError> { - writer.write_all_objects_header(self.variation) + /// Read up to `count` objects of a variation, with an 8-bit limited count header (0x07) + pub fn one_byte_limited_count(variation: Variation, count: u8) -> Self { + Self::single(ReadHeader::LimitedCount8 { variation, count }) } -} -impl OneByteLimitedCountScan { - /// construct an [`OneByteLimitedCountScan`] from the variation - pub fn new(variation: Variation, count: u8) -> Self { - Self { variation, count } + /// Read up to `count` objects of a variation, with a 16-bit limited count header (0x08) + pub fn two_byte_limited_count(variation: Variation, count: u16) -> Self { + Self::single(ReadHeader::LimitedCount16 { variation, count }) } - pub(crate) fn write(self, writer: &mut HeaderWriter) -> Result<(), scursor::WriteError> { - writer.write_limited_count(self.variation, self.count) + /// Read a device attribute (group 0) of a set + pub fn device_attribute>(variation: T, set: AttrSet) -> Self { + Self::single(ReadHeader::device_attribute(variation.into(), set)) } -} -impl TwoByteLimitedCountScan { - /// construct an [`TwoByteLimitedCountScan`] from the variation - pub fn new(variation: Variation, count: u16) -> Self { - Self { variation, count } + /// Add an all objects header (0x06) with the specified variation + pub fn add_all_objects(self, variation: Variation) -> Self { + self.add(ReadHeader::AllObjects { variation }) } - pub(crate) fn write(self, writer: &mut HeaderWriter) -> Result<(), scursor::WriteError> { - writer.write_limited_count(self.variation, self.count) + /// Add an 8-bit start/stop header (0x00) with the specified variation + pub fn add_range_8(self, variation: Variation, start: u8, stop: u8) -> Self { + self.add(ReadHeader::Range8 { + variation, + start, + stop, + }) } -} - -/// Enum representing all of the allowed scan types -#[derive(Copy, Clone, Debug, PartialEq, Eq)] -pub enum ReadHeader { - /// variant for one byte range scans - Range8(OneByteRangeScan), - /// variant for two byte range scans - Range16(TwoByteRangeScan), - /// variant for all objects scans - AllObjects(AllObjectsScan), - /// variant for one byte limited count - LimitedCount8(OneByteLimitedCountScan), - /// variant for two byte limited count - LimitedCount16(TwoByteLimitedCountScan), -} -impl ReadHeader { - /// construct a one byte range [`ReadHeader`] - pub fn one_byte_range(variation: Variation, start: u8, stop: u8) -> Self { - ReadHeader::Range8(OneByteRangeScan::new(variation, start, stop)) + /// Add a 16-bit start/stop header (0x01) with the specified variation + pub fn add_range_16(self, variation: Variation, start: u16, stop: u16) -> Self { + self.add(ReadHeader::Range16 { + variation, + start, + stop, + }) } - /// construct a two range [`ReadHeader`] - pub fn two_byte_range(variation: Variation, start: u16, stop: u16) -> Self { - ReadHeader::Range16(TwoByteRangeScan::new(variation, start, stop)) + /// Add an 8-bit limited count header (0x07) with the specified count and variation + pub fn add_one_byte_limited_count(self, variation: Variation, count: u8) -> Self { + self.add(ReadHeader::LimitedCount8 { variation, count }) } - /// construct an all objects [`ReadHeader`] - pub fn all_objects(variation: Variation) -> Self { - ReadHeader::AllObjects(AllObjectsScan::new(variation)) + /// Add a 16-bit limited count header (0x08) with the specified count and variation + pub fn add_two_byte_limited_count(self, variation: Variation, count: u16) -> Self { + self.add(ReadHeader::LimitedCount16 { variation, count }) } - /// construct a one byte limited count scan [`ReadHeader`] - pub fn one_byte_limited_count(variation: Variation, count: u8) -> Self { - ReadHeader::LimitedCount8(OneByteLimitedCountScan::new(variation, count)) + /// Add a header that reads a device attribute (group 0) of a set + pub fn add_device_attribute>(self, variation: T, set: AttrSet) -> Self { + self.add(ReadHeader::device_attribute(variation.into(), set)) } - /// construct a two byte limited count scan [`ReadHeader`] - pub fn two_byte_limited_count(variation: Variation, count: u16) -> Self { - ReadHeader::LimitedCount16(TwoByteLimitedCountScan::new(variation, count)) + pub(crate) fn format(&self, writer: &mut HeaderWriter) -> Result<(), TaskErrorKind> { + match &self.inner { + ReadInner::Single(header) => { + header.validate()?; + header.format(writer)?; + } + ReadInner::ClassScan(classes) => classes.write(writer)?, + ReadInner::Multiple(headers) => { + for header in headers { + header.validate()?; + } + for header in headers { + header.format(writer)?; + } + } + } + Ok(()) } - fn variation(self) -> Variation { - match self { - ReadHeader::Range8(scan) => scan.variation, - ReadHeader::Range16(scan) => scan.variation, - ReadHeader::AllObjects(scan) => scan.variation, - ReadHeader::LimitedCount8(scan) => scan.variation, - ReadHeader::LimitedCount16(scan) => scan.variation, - } + fn single(header: ReadHeader) -> Self { + Self::from_inner(ReadInner::Single(header)) } - /// The variation must name an object: `Group0(0)` writes g0v0, which names none - fn validate(self) -> Result<(), BadEncoding> { - let variation = self.variation(); - let (group, var) = variation.to_group_and_var(); - match Variation::lookup(group, var) { - Some(_) => Ok(()), - None => Err(BadEncoding::UndefinedVariation(variation)), - } + fn from_inner(inner: ReadInner) -> Self { + Self { inner } } - pub(crate) fn format(self, writer: &mut HeaderWriter) -> Result<(), scursor::WriteError> { - match self { - ReadHeader::Range8(scan) => scan.write(writer), - ReadHeader::Range16(scan) => scan.write(writer), - ReadHeader::AllObjects(scan) => scan.write(writer), - ReadHeader::LimitedCount8(scan) => scan.write(writer), - ReadHeader::LimitedCount16(scan) => scan.write(writer), - } + fn add(self, header: ReadHeader) -> Self { + let mut headers = match self.inner { + ReadInner::Single(first) => vec![first], + ReadInner::ClassScan(classes) => classes + .variations() + .map(|variation| ReadHeader::AllObjects { variation }) + .collect(), + ReadInner::Multiple(headers) => headers, + }; + headers.push(header); + Self::from_inner(ReadInner::Multiple(headers)) } } -/// Builder for write requests that hides the underlying type +/// The object headers of a request that expects an empty response, such as a WRITE or a FREEZE +/// +/// It holds READ-style headers, which name the objects to freeze, as well as freeze times and +/// device attributes to write. #[derive(Clone, Debug, Default)] -pub struct Headers { +pub struct Request { headers: Vec
, } @@ -462,99 +425,46 @@ enum Header { Attribute(OwnedAttribute), } -impl Header { - pub(crate) fn format(&self, writer: &mut HeaderWriter) -> Result<(), TaskErrorKind> { - match self { - Header::Read(x) => { - x.format(writer)?; - } - Header::TimeAndInterval(x) => { - let g50v2: Group50Var2 = >::into(*x); - writer.write_count_of_one(g50v2)?; - } - Header::Attribute(x) => { - writer.write_attribute(x)?; - } - } - Ok(()) - } - - fn validate(&self) -> Result<(), BadEncoding> { - match self { - Header::Read(x) => x.validate(), - Header::TimeAndInterval(_) => Ok(()), - Header::Attribute(x) => x.check_encodable().map_err(BadEncoding::Attribute), - } - } - - #[cfg(feature = "ffi")] - pub(crate) fn to_read_header(&self) -> Option { - match self { - Header::Read(x) => Some(*x), - Header::TimeAndInterval(_) => None, - Header::Attribute(_) => None, - } - } -} - -impl Headers { - /// Construct an empty set of request headers +impl Request { + /// Construct a request with no headers pub fn new() -> Self { Default::default() } - /// Convert this generic request into a ReadRequest dropping irrelevant headers - #[cfg(feature = "ffi")] - pub fn to_read_request(&self) -> ReadRequest { - ReadRequest::MultipleHeader( - self.headers - .iter() - .filter_map(|x| x.to_read_header()) - .collect(), - ) - } - - /// Add a header to the collection - #[cfg(feature = "ffi")] - pub fn push_read_header(&mut self, header: ReadHeader) { - self.headers.push(header.into()); - } - - /// Add a header to the collection - #[cfg(feature = "ffi")] - pub fn push_freeze_interval(&mut self, interval: FreezeInterval) { - self.headers.push(Header::TimeAndInterval(interval)); - } - - /// Add an attribute header to the collection - #[cfg(feature = "ffi")] - pub fn push_attr(&mut self, attr: OwnedAttribute) { - self.headers.push(Header::Attribute(attr)); - } - /// Add an all objects header (0x06) with the specified variation pub fn add_all_objects(self, variation: Variation) -> Self { - self.add(ReadHeader::all_objects(variation).into()) + self.add(Header::Read(ReadHeader::AllObjects { variation })) } - /// Add 8-bit start/stop header (0x00) with the specified variation + /// Add an 8-bit start/stop header (0x00) with the specified variation pub fn add_range_8(self, variation: Variation, start: u8, stop: u8) -> Self { - self.add(ReadHeader::one_byte_range(variation, start, stop).into()) + self.add(Header::Read(ReadHeader::Range8 { + variation, + start, + stop, + })) } - /// Add 16-bit start/stop header (0x01) with the specified variation + /// Add a 16-bit start/stop header (0x01) with the specified variation pub fn add_range_16(self, variation: Variation, start: u16, stop: u16) -> Self { - self.add(ReadHeader::two_byte_range(variation, start, stop).into()) + self.add(Header::Read(ReadHeader::Range16 { + variation, + start, + stop, + })) } - /// add a one byte limited count header (0x7) with the specified count and variation + /// Add an 8-bit limited count header (0x07) with the specified count and variation pub fn add_one_byte_limited_count(self, variation: Variation, count: u8) -> Self { - self.add(ReadHeader::one_byte_limited_count(variation, count).into()) + self.add(Header::Read(ReadHeader::LimitedCount8 { variation, count })) } - /// add a two byte limited count (0x08) header with the specified count and variation + /// Add a 16-bit limited count header (0x08) with the specified count and variation pub fn add_two_byte_limited_count(self, variation: Variation, count: u16) -> Self { - self.add(ReadHeader::two_byte_limited_count(variation, count).into()) + self.add(Header::Read(ReadHeader::LimitedCount16 { + variation, + count, + })) } /// Add a limited count (0x07) with a single g50v2 @@ -596,71 +506,108 @@ impl Headers { } } -/// Enum representing all of the READ request types available from the master API -#[derive(Clone, Debug)] -pub enum ReadRequest { - /// Read a single header - SingleHeader(ReadHeader), - /// Read class data - ClassScan(Classes), - /// Read multiple headers - MultipleHeader(Vec), -} - -impl ReadRequest { - /// construct a `ReadRequest` from a `Classes` instance - pub fn class_scan(scan: Classes) -> Self { - Self::ClassScan(scan) +impl Header { + fn format(&self, writer: &mut HeaderWriter) -> Result<(), TaskErrorKind> { + match self { + Header::Read(x) => { + x.format(writer)?; + } + Header::TimeAndInterval(x) => { + let g50v2: Group50Var2 = >::into(*x); + writer.write_count_of_one(g50v2)?; + } + Header::Attribute(x) => { + writer.write_attribute(x)?; + } + } + Ok(()) } - /// construct a `ReadRequest` consisting of a single one-byte range - pub fn one_byte_range(variation: Variation, start: u8, stop: u8) -> Self { - Self::SingleHeader(ReadHeader::one_byte_range(variation, start, stop)) + fn validate(&self) -> Result<(), BadEncoding> { + match self { + Header::Read(x) => x.validate(), + Header::TimeAndInterval(_) => Ok(()), + Header::Attribute(x) => x.check_encodable().map_err(BadEncoding::Attribute), + } } +} - /// construct a `ReadRequest` consisting of a single one-byte range specifying a specific device attribute - pub fn device_attribute>(variation: T, set: AttrSet) -> Self { - Self::one_byte_range(Group0(variation.into()), set.value(), set.value()) - } +/// A header that names objects without carrying values, as in a READ +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +enum ReadHeader { + Range8 { + variation: Variation, + start: u8, + stop: u8, + }, + Range16 { + variation: Variation, + start: u16, + stop: u16, + }, + AllObjects { + variation: Variation, + }, + LimitedCount8 { + variation: Variation, + count: u8, + }, + LimitedCount16 { + variation: Variation, + count: u16, + }, +} - /// construct a `ReadRequest` consisting of a single two-byte range - pub fn two_byte_range(variation: Variation, start: u16, stop: u16) -> Self { - Self::SingleHeader(ReadHeader::two_byte_range(variation, start, stop)) +impl ReadHeader { + fn device_attribute(variation: u8, set: AttrSet) -> Self { + let set = set.value(); + ReadHeader::Range8 { + variation: Group0(variation), + start: set, + stop: set, + } } - /// construct an all objects `ReadRequest` for a particular variation - pub fn all_objects(variation: Variation) -> Self { - Self::SingleHeader(ReadHeader::all_objects(variation)) + fn variation(self) -> Variation { + match self { + ReadHeader::Range8 { variation, .. } + | ReadHeader::Range16 { variation, .. } + | ReadHeader::AllObjects { variation } + | ReadHeader::LimitedCount8 { variation, .. } + | ReadHeader::LimitedCount16 { variation, .. } => variation, + } } - /// construct a `ReadRequest` consisting of multiple headers - pub fn multiple_headers(headers: &[ReadHeader]) -> Self { - Self::MultipleHeader(headers.to_vec()) + /// The variation must name an object: `Group0(0)` writes g0v0, which names none + fn validate(self) -> Result<(), BadEncoding> { + let variation = self.variation(); + let (group, var) = variation.to_group_and_var(); + match Variation::lookup(group, var) { + Some(_) => Ok(()), + None => Err(BadEncoding::UndefinedVariation(variation)), + } } - pub(crate) fn format(&self, writer: &mut HeaderWriter) -> Result<(), TaskErrorKind> { + fn format(self, writer: &mut HeaderWriter) -> Result<(), scursor::WriteError> { match self { - ReadRequest::SingleHeader(req) => { - req.validate()?; - req.format(writer)?; + ReadHeader::Range8 { + variation, + start, + stop, + } => writer.write_range_only(variation, start, stop), + ReadHeader::Range16 { + variation, + start, + stop, + } => writer.write_range_only(variation, start, stop), + ReadHeader::AllObjects { variation } => writer.write_all_objects_header(variation), + ReadHeader::LimitedCount8 { variation, count } => { + writer.write_limited_count(variation, count) } - ReadRequest::ClassScan(req) => req.write(writer)?, - ReadRequest::MultipleHeader(reqs) => { - for req in reqs { - req.validate()?; - } - for req in reqs { - req.format(writer)?; - } + ReadHeader::LimitedCount16 { variation, count } => { + writer.write_limited_count(variation, count) } } - Ok(()) - } -} - -impl From for Header { - fn from(value: ReadHeader) -> Self { - Header::Read(value) } } @@ -1218,8 +1165,8 @@ mod tests { fn attribute_with_a_variation_that_cannot_carry_a_value_leaves_the_cursor_untouched() { use crate::app::attr::{var, BadAttribute, OwnedAttrValue}; - let headers = |variation| { - Headers::new() + let request = |variation| { + Request::new() .add_all_objects(Variation::Group60Var1) .add_attribute(OwnedAttribute::new( AttrSet::Default, @@ -1238,7 +1185,7 @@ mod tests { cursor.write_u8(0xAA).unwrap(); assert_eq!( - headers(variation).write(&mut HeaderWriter::new(&mut cursor)), + request(variation).write(&mut HeaderWriter::new(&mut cursor)), Err(BadEncoding::Attribute(BadAttribute::BadVariation(variation)).into()) ); assert_eq!(cursor.written(), &[0xAA]); @@ -1246,7 +1193,7 @@ mod tests { let mut buffer = [0u8; 64]; let mut cursor = WriteCursor::new(&mut buffer); - headers(var::DEVICE_MANUFACTURER_NAME) + request(var::DEVICE_MANUFACTURER_NAME) .write(&mut HeaderWriter::new(&mut cursor)) .unwrap(); assert_eq!( @@ -1259,45 +1206,53 @@ mod tests { fn read_of_group0_var0_leaves_the_cursor_untouched() { const G0V0: Variation = Variation::Group0(0); let expected: Result<(), TaskErrorKind> = Err(BadEncoding::UndefinedVariation(G0V0).into()); - let valid = ReadHeader::all_objects(Variation::Group60Var1); - - for header in [ - ReadHeader::all_objects(G0V0), - ReadHeader::one_byte_range(G0V0, 1, 2), - ReadHeader::two_byte_range(G0V0, 1, 2), - ReadHeader::one_byte_limited_count(G0V0, 1), - ReadHeader::two_byte_limited_count(G0V0, 1), + + let valid = || ReadRequest::all_objects(Variation::Group60Var1); + for request in [ + ReadRequest::all_objects(G0V0), + ReadRequest::one_byte_range(G0V0, 1, 2), + ReadRequest::two_byte_range(G0V0, 1, 2), + ReadRequest::one_byte_limited_count(G0V0, 1), + ReadRequest::two_byte_limited_count(G0V0, 1), + valid().add_all_objects(G0V0), + valid().add_range_8(G0V0, 1, 2), + valid().add_range_16(G0V0, 1, 2), + valid().add_one_byte_limited_count(G0V0, 1), + valid().add_two_byte_limited_count(G0V0, 1), ] { - for request in [ - ReadRequest::SingleHeader(header), - ReadRequest::multiple_headers(&[valid, header]), - ] { - let mut buffer = [0u8; 64]; - let mut cursor = WriteCursor::new(&mut buffer); - cursor.write_u8(0xAA).unwrap(); - assert_eq!( - request.format(&mut HeaderWriter::new(&mut cursor)), - expected, - "{request:?}" - ); - assert_eq!(cursor.written(), &[0xAA], "{request:?}"); - } + let mut buffer = [0u8; 64]; + let mut cursor = WriteCursor::new(&mut buffer); + cursor.write_u8(0xAA).unwrap(); + assert_eq!( + request.format(&mut HeaderWriter::new(&mut cursor)), + expected, + "{request:?}" + ); + assert_eq!(cursor.written(), &[0xAA], "{request:?}"); + } - let headers = Headers::new().add(valid.into()).add(header.into()); + let valid = || Request::new().add_all_objects(Variation::Group60Var1); + for request in [ + valid().add_all_objects(G0V0), + valid().add_range_8(G0V0, 1, 2), + valid().add_range_16(G0V0, 1, 2), + valid().add_one_byte_limited_count(G0V0, 1), + valid().add_two_byte_limited_count(G0V0, 1), + ] { let mut buffer = [0u8; 64]; let mut cursor = WriteCursor::new(&mut buffer); cursor.write_u8(0xAA).unwrap(); assert_eq!( - headers.write(&mut HeaderWriter::new(&mut cursor)), + request.write(&mut HeaderWriter::new(&mut cursor)), expected, - "{header:?}" + "{request:?}" ); - assert_eq!(cursor.written(), &[0xAA], "{header:?}"); + assert_eq!(cursor.written(), &[0xAA], "{request:?}"); } } mod round_trip { - //! READ requests and generic request headers as the master writes them, against oracles + //! READ requests and `Request` headers as the master writes them, against oracles //! that share no code with it: a hand encoding of each header (`model_request`, //! `model_header`, `Qualifier::bytes`, `freeze_bytes`), and for which headers the //! outstation accepts, the READ table `read_accepts` in @@ -1307,13 +1262,13 @@ mod tests { //! Generated: for each qualifier kind, variations a READ accepts with it, less often ones //! it doesn't, and rarely g0v0, in any header position, with groups 0, 110 and 111 no more //! likely than the others; one and two-byte ranges, with single indices and the ends more - //! likely; one and two-byte counts, with 0, 1, 255 and the maximum more likely; single and - //! multiple headers (up to five), class scans of any classes, and device attribute reads; - //! generic headers of up to five READ headers and g50v2 freeze times, with a time and - //! interval of 0 or any value. + //! likely; one and two-byte counts, with 0, 1, 255 and the maximum more likely; READ + //! requests built from a single header, a class scan of any classes or a device attribute + //! read, then up to five headers or device attribute reads added to it; a `Request` of up + //! to five READ headers and g50v2 freeze times, with a time and interval of 0 or any value. //! - //! Not generated: a group and variation that isn't a `Variation`, attribute headers among - //! generic headers (see `app/attr.rs` and the attribute example above), and requests + //! Not generated: a group and variation that isn't a `Variation`, attribute headers in a + //! `Request` (see `app/attr.rs` and the attribute example above), and requests //! longer than the write buffer. use super::*; @@ -1379,23 +1334,56 @@ mod tests { fn model_header(header: ReadHeader) -> ModelHeader { let (variation, qualifier) = match header { - ReadHeader::Range8(x) => (x.variation, Qualifier::Range8(x.start, x.stop)), - ReadHeader::Range16(x) => (x.variation, Qualifier::Range16(x.start, x.stop)), - ReadHeader::AllObjects(x) => (x.variation, Qualifier::AllObjects), - ReadHeader::LimitedCount8(x) => (x.variation, Qualifier::Count8(x.count)), - ReadHeader::LimitedCount16(x) => (x.variation, Qualifier::Count16(x.count)), + ReadHeader::Range8 { + variation, + start, + stop, + } => (variation, Qualifier::Range8(start, stop)), + ReadHeader::Range16 { + variation, + start, + stop, + } => (variation, Qualifier::Range16(start, stop)), + ReadHeader::AllObjects { variation } => (variation, Qualifier::AllObjects), + ReadHeader::LimitedCount8 { variation, count } => { + (variation, Qualifier::Count8(count)) + } + ReadHeader::LimitedCount16 { variation, count } => { + (variation, Qualifier::Count16(count)) + } }; (variation.to_group_and_var(), qualifier) } - fn model_request(request: &ReadRequest) -> Vec { - match request { - ReadRequest::SingleHeader(header) => vec![model_header(*header)], - ReadRequest::MultipleHeader(headers) => { - headers.iter().copied().map(model_header).collect() + /// How a generated READ request starts: a single header, a device attribute or classes + #[derive(Clone, Debug)] + enum Start { + Read(ReadOp), + Classes(Classes), + } + + /// A header that a READ request starts with or adds + #[derive(Clone, Copy, Debug)] + enum ReadOp { + Header(ReadHeader), + /// the variation and set of a device attribute read + DeviceAttribute(u8, u8), + } + + fn model_op(op: ReadOp) -> ModelHeader { + match op { + ReadOp::Header(header) => model_header(header), + ReadOp::DeviceAttribute(variation, set) => { + ((0, variation), Qualifier::Range8(set, set)) } + } + } + + fn model_request(start: &Start, ops: &[ReadOp]) -> Vec { + let first: Vec = match start { + Start::Read(op) => vec![model_op(*op)], // the event classes first, then class 0 - ReadRequest::ClassScan(classes) => [ + Start::Classes(classes) => [ (classes.events.class1, (60, 2)), (classes.events.class2, (60, 3)), (classes.events.class3, (60, 4)), @@ -1405,7 +1393,64 @@ mod tests { .filter(|(enabled, _)| *enabled) .map(|(_, group_var)| (group_var, Qualifier::AllObjects)) .collect(), - } + }; + first + .into_iter() + .chain(ops.iter().copied().map(model_op)) + .collect() + } + + /// the request built through the public constructor and add method for each header + fn build_request(start: &Start, ops: &[ReadOp]) -> ReadRequest { + let first = match *start { + Start::Classes(classes) => ReadRequest::class_scan(classes), + Start::Read(ReadOp::DeviceAttribute(variation, set)) => { + ReadRequest::device_attribute(variation, AttrSet::new(set)) + } + Start::Read(ReadOp::Header(header)) => match header { + ReadHeader::Range8 { + variation, + start, + stop, + } => ReadRequest::one_byte_range(variation, start, stop), + ReadHeader::Range16 { + variation, + start, + stop, + } => ReadRequest::two_byte_range(variation, start, stop), + ReadHeader::AllObjects { variation } => ReadRequest::all_objects(variation), + ReadHeader::LimitedCount8 { variation, count } => { + ReadRequest::one_byte_limited_count(variation, count) + } + ReadHeader::LimitedCount16 { variation, count } => { + ReadRequest::two_byte_limited_count(variation, count) + } + }, + }; + ops.iter().fold(first, |request, op| match *op { + ReadOp::DeviceAttribute(variation, set) => { + request.add_device_attribute(variation, AttrSet::new(set)) + } + ReadOp::Header(ReadHeader::Range8 { + variation, + start, + stop, + }) => request.add_range_8(variation, start, stop), + ReadOp::Header(ReadHeader::Range16 { + variation, + start, + stop, + }) => request.add_range_16(variation, start, stop), + ReadOp::Header(ReadHeader::AllObjects { variation }) => { + request.add_all_objects(variation) + } + ReadOp::Header(ReadHeader::LimitedCount8 { variation, count }) => { + request.add_one_byte_limited_count(variation, count) + } + ReadOp::Header(ReadHeader::LimitedCount16 { variation, count }) => { + request.add_two_byte_limited_count(variation, count) + } + }) } fn model_bytes(&((group, var), qualifier): &ModelHeader) -> Vec { @@ -1508,38 +1553,52 @@ mod tests { fn read_header() -> impl Strategy { prop_oneof![ - (variation(ReadKind::Range), range(u8::MAX)) - .prop_map(|(v, (start, stop))| { ReadHeader::one_byte_range(v, start, stop) }), - (variation(ReadKind::Range), range(u16::MAX)) - .prop_map(|(v, (start, stop))| { ReadHeader::two_byte_range(v, start, stop) }), - variation(ReadKind::AllObjects).prop_map(ReadHeader::all_objects), + (variation(ReadKind::Range), range(u8::MAX)).prop_map( + |(variation, (start, stop))| { + ReadHeader::Range8 { + variation, + start, + stop, + } + } + ), + (variation(ReadKind::Range), range(u16::MAX)).prop_map( + |(variation, (start, stop))| ReadHeader::Range16 { + variation, + start, + stop, + } + ), + variation(ReadKind::AllObjects) + .prop_map(|variation| ReadHeader::AllObjects { variation }), (variation(ReadKind::Count), count(vec![0, 1, u8::MAX])) - .prop_map(|(v, count)| ReadHeader::one_byte_limited_count(v, count)), + .prop_map(|(variation, count)| ReadHeader::LimitedCount8 { variation, count }), ( variation(ReadKind::Count), count(vec![0, 1, 255, 256, u16::MAX]) ) - .prop_map(|(v, count)| ReadHeader::two_byte_limited_count(v, count)), + .prop_map(|(variation, count)| ReadHeader::LimitedCount16 { variation, count }), ] } - fn read_request() -> impl Strategy { + fn read_op() -> impl Strategy { prop_oneof![ - read_header().prop_map(ReadRequest::SingleHeader), - prop::collection::vec(read_header(), 0..6) - .prop_map(|headers| ReadRequest::multiple_headers(&headers)), - any::<[bool; 4]>().prop_map(|[class0, class1, class2, class3]| { - ReadRequest::class_scan(Classes::new( - class0, - EventClasses::new(class1, class2, class3), - )) - }), - (count(vec![0, 254, 255]), any::()).prop_map(|(variation, set)| { - ReadRequest::device_attribute(variation, AttrSet::new(set)) - }), + 3 => read_header().prop_map(ReadOp::Header), + 1 => (count(vec![0, 254, 255]), any::()) + .prop_map(|(variation, set)| ReadOp::DeviceAttribute(variation, set)), ] } + fn read_request() -> impl Strategy)> { + let start = prop_oneof![ + 2 => read_op().prop_map(Start::Read), + 1 => any::<[bool; 4]>().prop_map(|[class0, class1, class2, class3]| { + Start::Classes(Classes::new(class0, EventClasses::new(class1, class2, class3))) + }), + ]; + (start, prop::collection::vec(read_op(), 0..6)) + } + #[derive(Clone, Debug)] enum Item { Read(ReadHeader), @@ -1558,23 +1617,29 @@ mod tests { ] } - fn add(headers: Headers, item: &Item) -> Headers { + fn add(request: Request, item: &Item) -> Request { match *item { - Item::Read(ReadHeader::Range8(x)) => { - headers.add_range_8(x.variation, x.start, x.stop) - } - Item::Read(ReadHeader::Range16(x)) => { - headers.add_range_16(x.variation, x.start, x.stop) + Item::Read(ReadHeader::Range8 { + variation, + start, + stop, + }) => request.add_range_8(variation, start, stop), + Item::Read(ReadHeader::Range16 { + variation, + start, + stop, + }) => request.add_range_16(variation, start, stop), + Item::Read(ReadHeader::AllObjects { variation }) => { + request.add_all_objects(variation) } - Item::Read(ReadHeader::AllObjects(x)) => headers.add_all_objects(x.variation), - Item::Read(ReadHeader::LimitedCount8(x)) => { - headers.add_one_byte_limited_count(x.variation, x.count) + Item::Read(ReadHeader::LimitedCount8 { variation, count }) => { + request.add_one_byte_limited_count(variation, count) } - Item::Read(ReadHeader::LimitedCount16(x)) => { - headers.add_two_byte_limited_count(x.variation, x.count) + Item::Read(ReadHeader::LimitedCount16 { variation, count }) => { + request.add_two_byte_limited_count(variation, count) } Item::Freeze(time, interval) => { - headers.add_time_and_interval(Timestamp::new(time), interval) + request.add_time_and_interval(Timestamp::new(time), interval) } } } @@ -1611,11 +1676,12 @@ mod tests { /// variation with that qualifier. A request with a header for g0v0 in any position, /// which names no object, fails and writes nothing #[test] - fn read_requests_parse_to_the_headers_written(request in read_request()) { + fn read_requests_parse_to_the_headers_written((start, ops) in read_request()) { + let request = build_request(&start, &ops); let mut buffer = [0; 256]; let mut cursor = WriteCursor::new(&mut buffer); let result = request.format(&mut HeaderWriter::new(&mut cursor)); - let model = model_request(&request); + let model = model_request(&start, &ops); if model.iter().any(|(group_var, _)| *group_var == (0, 0)) { prop_assert_eq!( result, @@ -1639,7 +1705,7 @@ mod tests { prop_assert_eq!(parse_read(written), expected); } - /// Generic request headers are written as the READ headers and g50v2 freeze times + /// A `Request` is written as the READ-style headers and g50v2 freeze times /// they hold, in order, and each g50v2 parses back to its time and interval. Headers /// with a READ of g0v0 in any position fail and write nothing. Attribute headers aren't /// generated: `app/attr.rs` tests their values, and @@ -1647,10 +1713,10 @@ mod tests { /// the header #[test] fn headers_are_written_in_order(items in prop::collection::vec(item(), 0..6)) { - let headers = items.iter().fold(Headers::new(), add); + let request = items.iter().fold(Request::new(), add); let mut buffer = [0; 256]; let mut cursor = WriteCursor::new(&mut buffer); - let result = headers.write(&mut HeaderWriter::new(&mut cursor)); + let result = request.write(&mut HeaderWriter::new(&mut cursor)); let g0v0 = Variation::Group0(0); if items .iter() diff --git a/dnp3/src/master/tasks/empty_response.rs b/dnp3/src/master/tasks/empty_response.rs index 09b6740d..6afe26ab 100644 --- a/dnp3/src/master/tasks/empty_response.rs +++ b/dnp3/src/master/tasks/empty_response.rs @@ -9,17 +9,17 @@ use crate::app::parse::parser::Response; use crate::app::FunctionCode; use crate::master::error::TaskErrorKind; use crate::master::tasks::{NonReadTask, OneShot, OneShotRequest}; -use crate::master::{Headers, TaskType}; +use crate::master::{Request, TaskType}; /// Any request whose response has no object headers pub(crate) struct EmptyResponseRequest { function: FunctionCode, - headers: Headers, + request: Request, } impl EmptyResponseRequest { - pub(crate) fn new(function: FunctionCode, headers: Headers) -> Self { - Self { function, headers } + pub(crate) fn new(function: FunctionCode, request: Request) -> Self { + Self { function, request } } } @@ -45,7 +45,7 @@ impl OneShotRequest for EmptyResponseRequest { } fn write(&self, writer: &mut HeaderWriter) -> Result<(), TaskErrorKind> { - self.headers.write(writer) + self.request.write(writer) } fn parse(&self, response: Response<'_>) -> Result<(), TaskErrorKind> { diff --git a/dnp3/src/master/tests/link_frames.rs b/dnp3/src/master/tests/link_frames.rs index fd70a9e7..a437673d 100644 --- a/dnp3/src/master/tests/link_frames.rs +++ b/dnp3/src/master/tests/link_frames.rs @@ -164,7 +164,7 @@ impl Kind { let result = match self { Kind::Read => { association - .read(ReadRequest::ClassScan(Classes::class0())) + .read(ReadRequest::class_scan(Classes::class0())) .await } Kind::NonRead => association.cold_restart().await.map(|_| ()), diff --git a/dnp3/src/master/tests/outcomes.rs b/dnp3/src/master/tests/outcomes.rs index a173a708..b3303f14 100644 --- a/dnp3/src/master/tests/outcomes.rs +++ b/dnp3/src/master/tests/outcomes.rs @@ -49,7 +49,7 @@ use crate::master::{ AssociationHandle, AssociationHandler, AssociationInformation, AuthKey, BlockNumber, Classes, CommandBuilder, CommandError, CommandHeaders, CommandMode, CommandSupport, DeadBandHeader, DirReadConfig, FileCredentials, FileError, FileHandle, FileMode, FileReadConfig, HeaderInfo, - Headers, MasterChannel, MasterChannelType, OpenFile, ReadHandler, ReadRequest, ReadType, + MasterChannel, MasterChannelType, OpenFile, ReadHandler, ReadRequest, ReadType, Request, TaskError, TaskType, TimeSyncError, TimeSyncProcedure, }; use crate::util::lifecycle::{RunError, StopReason}; @@ -132,7 +132,7 @@ impl Kind { match self { Kind::Read => Reply::Read( association - .read(ReadRequest::ClassScan(Classes::class0())) + .read(ReadRequest::class_scan(Classes::class0())) .await, ), Kind::DirectOperate => Reply::Command( @@ -150,7 +150,7 @@ impl Kind { association .send_and_expect_empty_response( FunctionCode::ImmediateFreeze, - Headers::new().add_all_objects(Variation::Group20Var0), + Request::new().add_all_objects(Variation::Group20Var0), ) .await, ), @@ -796,7 +796,7 @@ async fn every_task_fails_with_a_link_error_when_the_connection_drops() { .harness .association .send_task(SingleReadTask::new( - ReadRequest::ClassScan(Classes::class0()), + ReadRequest::class_scan(Classes::class0()), promise, )) .await @@ -862,7 +862,7 @@ async fn running_and_queued_tasks_complete_their_promises_on_shutdown() { harness .association .send_task(SingleReadTask::new( - ReadRequest::ClassScan(Classes::class0()), + ReadRequest::class_scan(Classes::class0()), promise, )) .await @@ -953,7 +953,7 @@ async fn queued_tasks_fail_with_no_such_association_when_the_association_is_remo harness .association .send_task(SingleReadTask::new( - ReadRequest::ClassScan(Classes::class0()), + ReadRequest::class_scan(Classes::class0()), promise, )) .await @@ -1066,7 +1066,7 @@ async fn requests_to_a_removed_association_fail_with_no_such_association() { } let poll = stale .add_poll( - ReadRequest::ClassScan(Classes::class0()), + ReadRequest::class_scan(Classes::class0()), Duration::from_secs(1), ) .await; @@ -1092,10 +1092,9 @@ async fn requests_to_a_removed_association_fail_with_no_such_association() { .await .unwrap(); harness.set_source(OTHER); - let read = - tokio::spawn( - async move { other.read(ReadRequest::ClassScan(Classes::class0())).await }, - ); + let read = tokio::spawn(async move { + other.read(ReadRequest::class_scan(Classes::class0())).await + }); next_request(&mut harness, 0, FunctionCode::Read).await; respond(&mut harness, empty_response(Sequence::new(0))).await; assert_eq!(read.await.unwrap(), Ok(()), "{via_handle}"); @@ -1377,7 +1376,7 @@ async fn read_callbacks_and_sequence_numbers_follow_the_fragments_in_order() { let read = tokio::spawn(async move { association - .read(ReadRequest::ClassScan(Classes::class0())) + .read(ReadRequest::class_scan(Classes::class0())) .await }); next_request(&mut harness, 0, FunctionCode::Read).await; @@ -1589,7 +1588,7 @@ async fn writing_an_attribute_whose_variation_cannot_carry_a_value_sends_nothing var::ALL_ATTRIBUTES_REQUEST, var::LIST_OF_ATTRIBUTE_VARIATIONS, ] { - let headers = Headers::new().add_attribute(OwnedAttribute::new( + let headers = Request::new().add_attribute(OwnedAttribute::new( AttrSet::Default, variation, OwnedAttrValue::UnsignedInt(0), @@ -1628,7 +1627,7 @@ async fn reading_group0_var0_sends_nothing() { .association .send_and_expect_empty_response( FunctionCode::Read, - Headers::new().add_all_objects(g0v0) + Request::new().add_all_objects(g0v0) ) .await, Err(err) diff --git a/dnp3/src/master/tests/read_errors.rs b/dnp3/src/master/tests/read_errors.rs index af7bbb6c..9ca06ffc 100644 --- a/dnp3/src/master/tests/read_errors.rs +++ b/dnp3/src/master/tests/read_errors.rs @@ -54,7 +54,7 @@ async fn read_with_iin2_and_data_delivers_the_data_and_succeeds() { let mut association = harness.association.clone(); let read = tokio::spawn(async move { association - .read(ReadRequest::ClassScan(Classes::class0())) + .read(ReadRequest::class_scan(Classes::class0())) .await }); @@ -90,7 +90,7 @@ async fn read_with_iin2_and_no_data_fails() { let mut association = harness.association.clone(); let read = tokio::spawn(async move { association - .read(ReadRequest::ClassScan(Classes::class0())) + .read(ReadRequest::class_scan(Classes::class0())) .await }); @@ -123,7 +123,7 @@ async fn multi_fragment_read_with_iin2_in_the_first_fragment_reads_every_fragmen let mut association = harness.association.clone(); let read = tokio::spawn(async move { association - .read(ReadRequest::ClassScan(Classes::class0())) + .read(ReadRequest::class_scan(Classes::class0())) .await }); @@ -160,7 +160,7 @@ async fn start_read( let mut association = harness.association.clone(); let read = tokio::spawn(async move { association - .read(ReadRequest::ClassScan(Classes::class0())) + .read(ReadRequest::class_scan(Classes::class0())) .await }); harness @@ -262,7 +262,7 @@ async fn periodic_poll_with_iin2_and_no_data_fails() { let mut association = harness.association.clone(); let _poll = association .add_poll( - ReadRequest::ClassScan(Classes::class0()), + ReadRequest::class_scan(Classes::class0()), std::time::Duration::from_secs(1), ) .await diff --git a/dnp3/src/master/tests/read_types.rs b/dnp3/src/master/tests/read_types.rs index 3ed4761a..f4bebe3d 100644 --- a/dnp3/src/master/tests/read_types.rs +++ b/dnp3/src/master/tests/read_types.rs @@ -114,7 +114,7 @@ async fn periodic_poll_reports_periodic_poll() { let mut association = harness.association.clone(); let _poll = association .add_poll( - ReadRequest::ClassScan(Classes::class0()), + ReadRequest::class_scan(Classes::class0()), std::time::Duration::from_secs(1), ) .await @@ -146,7 +146,7 @@ async fn single_read_reports_single_poll() { let mut association = harness.association.clone(); let read = tokio::spawn(async move { association - .read(ReadRequest::ClassScan(Classes::class0())) + .read(ReadRequest::class_scan(Classes::class0())) .await }); harness @@ -178,7 +178,10 @@ async fn single_read_with_custom_handler_reports_single_poll_to_that_handler_onl let mut association = harness.association.clone(); let read = tokio::spawn(async move { association - .read_with_handler(ReadRequest::ClassScan(Classes::class0()), Box::new(handler)) + .read_with_handler( + ReadRequest::class_scan(Classes::class0()), + Box::new(handler), + ) .await }); harness diff --git a/dnp3/src/master/tests/scheduling.rs b/dnp3/src/master/tests/scheduling.rs index 114ed7ce..c0d3fe70 100644 --- a/dnp3/src/master/tests/scheduling.rs +++ b/dnp3/src/master/tests/scheduling.rs @@ -231,7 +231,7 @@ fn spawn_read( classes: Classes, ) -> JoinHandle> { let mut association = association.clone(); - tokio::spawn(async move { association.read(ReadRequest::ClassScan(classes)).await }) + tokio::spawn(async move { association.read(ReadRequest::class_scan(classes)).await }) } async fn add_poll( @@ -240,7 +240,7 @@ async fn add_poll( period: Duration, ) -> PollHandle { association - .add_poll(ReadRequest::ClassScan(classes), period) + .add_poll(ReadRequest::class_scan(classes), period) .await .unwrap() } diff --git a/dnp3/src/master/tests/shared_link.rs b/dnp3/src/master/tests/shared_link.rs index f2e7ea1a..039ee8ea 100644 --- a/dnp3/src/master/tests/shared_link.rs +++ b/dnp3/src/master/tests/shared_link.rs @@ -65,7 +65,7 @@ async fn response_from_another_outstation_during_any_task_refreshes_its_own_keep let task = tokio::spawn(async move { match kind { Kind::NonRead => other.cold_restart().await.map(|_| ()), - Kind::Read => other.read(ReadRequest::ClassScan(Classes::class0())).await, + Kind::Read => other.read(ReadRequest::class_scan(Classes::class0())).await, Kind::LinkStatus => other.check_link_status().await, } }); @@ -87,7 +87,7 @@ async fn response_from_another_outstation_during_any_task_refreshes_its_own_keep let mut association = harness.association.clone(); let read = tokio::spawn(async move { association - .read(ReadRequest::ClassScan(Classes::class0())) + .read(ReadRequest::class_scan(Classes::class0())) .await }); harness diff --git a/dnp3/src/master/tests/startup.rs b/dnp3/src/master/tests/startup.rs index 6bb0d769..99cca33c 100644 --- a/dnp3/src/master/tests/startup.rs +++ b/dnp3/src/master/tests/startup.rs @@ -344,7 +344,7 @@ async fn detect_restart_in_read_response() { // Spawn a task that sends an integrity scan let mut assoc = harness.association.clone(); let read_task = - tokio::spawn(async move { assoc.read(ReadRequest::ClassScan(Classes::all())).await }); + tokio::spawn(async move { assoc.read(ReadRequest::class_scan(Classes::all())).await }); // expect the integrity scan and respond with DEVICE_RESTART harness diff --git a/dnp3/src/master/tests/time_sync.rs b/dnp3/src/master/tests/time_sync.rs index 20baf10d..348a4aa2 100644 --- a/dnp3/src/master/tests/time_sync.rs +++ b/dnp3/src/master/tests/time_sync.rs @@ -685,7 +685,7 @@ fn class_3() -> Classes { async fn add_class_3_poll(harness: &mut TestHarness, period: Duration) -> PollHandle { harness .association - .add_poll(ReadRequest::ClassScan(class_3()), period) + .add_poll(ReadRequest::class_scan(class_3()), period) .await .unwrap() } diff --git a/dnp3/src/no_panic_check/encode.rs b/dnp3/src/no_panic_check/encode.rs index 5d7875de..4402b38a 100644 --- a/dnp3/src/no_panic_check/encode.rs +++ b/dnp3/src/no_panic_check/encode.rs @@ -26,7 +26,7 @@ //! - [`read_request`]: `ReadRequest::format`, which periodic polls and single reads use //! - [`command_headers`]: `CommandHeaders::write`, for g12v1 and g41v1 to g41v4 with 8 and //! 16-bit indexes, which commands with and without acknowledgment use -//! - [`one_shot`]: `OneShotRequest::write` for deadbands, generic requests (`Headers`, with read +//! - [`one_shot`]: `OneShotRequest::write` for deadbands, generic requests (`Request`, with read //! headers, freeze intervals and attributes), restarts and the file requests //! - [`auto_task`]: `ResponseTask::write` for the automatic tasks (class scans for startup //! integrity and event scans are `Classes::write`, reached through [`read_request`]) @@ -70,7 +70,7 @@ use crate::master::tasks::restart::RestartType; use crate::master::tasks::{OneShotRequest, ResponseTask}; use crate::master::{ AuthKey, BlockNumber, Classes, CommandBuilder, CommandHeaders, CommandSupport, DeadBandHeader, - EventClasses, FileCredentials, FileHandle, FileMode, Headers, ReadHeader, ReadRequest, + EventClasses, FileCredentials, FileHandle, FileMode, ReadRequest, Request, }; use crate::outstation::FreezeInterval; use crate::transport::real::sequence::Sequence; @@ -228,14 +228,17 @@ fn variation(source: &mut Source) -> Variation { Variation::lookup(source.u8(), source.u8()).unwrap_or(Variation::Group0(0)) } -fn read_header(source: &mut Source) -> ReadHeader { +/// a request of one header, a device attribute read or a class scan +fn read_start(source: &mut Source) -> ReadRequest { let variation = variation(source); - match source.u8() % 5 { - 0 => ReadHeader::one_byte_range(variation, source.u8(), source.u8()), - 1 => ReadHeader::two_byte_range(variation, source.u16(), source.u16()), - 2 => ReadHeader::all_objects(variation), - 3 => ReadHeader::one_byte_limited_count(variation, source.u8()), - _ => ReadHeader::two_byte_limited_count(variation, source.u16()), + match source.u8() % 7 { + 0 => ReadRequest::one_byte_range(variation, source.u8(), source.u8()), + 1 => ReadRequest::two_byte_range(variation, source.u16(), source.u16()), + 2 => ReadRequest::all_objects(variation), + 3 => ReadRequest::one_byte_limited_count(variation, source.u8()), + 4 => ReadRequest::two_byte_limited_count(variation, source.u16()), + 5 => ReadRequest::device_attribute(source.u8(), AttrSet::new(source.u8())), + _ => ReadRequest::class_scan(classes(source)), } } @@ -248,11 +251,18 @@ fn classes(source: &mut Source) -> Classes { } fn read(source: &mut Source) -> ReadRequest { - match source.u8() % 3 { - 0 => ReadRequest::SingleHeader(read_header(source)), - 1 => ReadRequest::ClassScan(classes(source)), - _ => ReadRequest::MultipleHeader(source.many(read_header)), - } + let len = source.len(); + (0..len).fold(read_start(source), |request, _| { + let variation = variation(source); + match source.u8() % 6 { + 0 => request.add_all_objects(variation), + 1 => request.add_range_8(variation, source.u8(), source.u8()), + 2 => request.add_range_16(variation, source.u16(), source.u16()), + 3 => request.add_one_byte_limited_count(variation, source.u8()), + 4 => request.add_two_byte_limited_count(variation, source.u16()), + _ => request.add_device_attribute(source.u8(), AttrSet::new(source.u8())), + } + }) } fn attr_value(source: &mut Source) -> OwnedAttrValue { @@ -277,21 +287,21 @@ pub(super) fn attribute(source: &mut Source) -> OwnedAttribute { OwnedAttribute::new(set, source.u8(), attr_value(source)) } -fn headers(source: &mut Source) -> Headers { +fn request(source: &mut Source) -> Request { let len = source.len(); - (0..len).fold(Headers::new(), |headers, _| { + (0..len).fold(Request::new(), |request, _| { let variation = variation(source); match source.u8() % 7 { - 0 => headers.add_all_objects(variation), - 1 => headers.add_range_8(variation, source.u8(), source.u8()), - 2 => headers.add_range_16(variation, source.u16(), source.u16()), - 3 => headers.add_one_byte_limited_count(variation, source.u8()), - 4 => headers.add_two_byte_limited_count(variation, source.u16()), - 5 => headers.add_freeze_interval(FreezeInterval::new( + 0 => request.add_all_objects(variation), + 1 => request.add_range_8(variation, source.u8(), source.u8()), + 2 => request.add_range_16(variation, source.u16(), source.u16()), + 3 => request.add_one_byte_limited_count(variation, source.u8()), + 4 => request.add_two_byte_limited_count(variation, source.u16()), + 5 => request.add_freeze_interval(FreezeInterval::new( Timestamp::new(source.u64()), source.u32(), )), - _ => headers.add_attribute(attribute(source)), + _ => request.add_attribute(attribute(source)), } }) } @@ -502,7 +512,7 @@ fn encoders(source: &mut Source) { let dead_bands = DeadBandsRequest::new(source.many(dead_band_header)); one_shot(&dead_bands, &mut source.buffer()); let function = FunctionCode::from(source.u8()).unwrap_or(FunctionCode::Write); - let generic = EmptyResponseRequest::new(function, headers(source)); + let generic = EmptyResponseRequest::new(function, request(source)); one_shot(&generic, &mut source.buffer()); let restart = if source.bool() { RestartType::ColdRestart diff --git a/examples/master/src/main.rs b/examples/master/src/main.rs index 1bd830d5..8bb0670f 100644 --- a/examples/master/src/main.rs +++ b/examples/master/src/main.rs @@ -66,7 +66,7 @@ async fn main() -> Result<(), Box> { // ANCHOR: add_poll let poll = association .add_poll( - ReadRequest::ClassScan(Classes::class123()), + ReadRequest::class_scan(Classes::class123()), Duration::from_secs(5), ) .await?; @@ -458,18 +458,18 @@ impl CliHandler { } "rmo" => { self.association - .read(ReadRequest::multiple_headers(&[ - ReadHeader::all_objects(Variation::Group10Var0), - ReadHeader::all_objects(Variation::Group40Var0), - ])) + .read( + ReadRequest::all_objects(Variation::Group10Var0) + .add_all_objects(Variation::Group40Var0), + ) .await?; } "rco" => { self.association - .read(ReadRequest::multiple_headers(&[ - ReadHeader::all_objects(Variation::Group20Var0), - ReadHeader::all_objects(Variation::Group21Var0), - ])) + .read( + ReadRequest::all_objects(Variation::Group20Var0) + .add_all_objects(Variation::Group21Var0), + ) .await?; } "cmd" => { @@ -520,29 +520,29 @@ impl CliHandler { } "fat" => { // ANCHOR: freeze_at_time - let headers = Headers::new() + let request = Request::new() // freeze all the counters once per day relative to the beginning of the current hour .add_freeze_interval(FreezeInterval::PeriodicallyFreezeRelative(86_400_000)) // apply this schedule to all counters .add_all_objects(Variation::Group20Var0); self.association - .send_and_expect_empty_response(FunctionCode::FreezeAtTime, headers) + .send_and_expect_empty_response(FunctionCode::FreezeAtTime, request) .await?; // ANCHOR_END: freeze_at_time } "ifz" => { // copy every counter to its frozen counter - let headers = Headers::new().add_all_objects(Variation::Group20Var0); + let request = Request::new().add_all_objects(Variation::Group20Var0); self.association - .send_and_expect_empty_response(FunctionCode::ImmediateFreeze, headers) + .send_and_expect_empty_response(FunctionCode::ImmediateFreeze, request) .await?; } "fcl" => { // copy every counter to its frozen counter, then clear the counter - let headers = Headers::new().add_all_objects(Variation::Group20Var0); + let request = Request::new().add_all_objects(Variation::Group20Var0); self.association - .send_and_expect_empty_response(FunctionCode::FreezeClear, headers) + .send_and_expect_empty_response(FunctionCode::FreezeClear, request) .await?; } "rda" => { @@ -557,11 +557,11 @@ impl CliHandler { } "wda" => { // ANCHOR: write_attribute - let headers = Headers::default() + let request = Request::new() .add_attribute(StringAttr::UserAssignedLocation.with_value("Mt. Olympus")); self.association - .send_and_expect_empty_response(FunctionCode::Write, headers) + .send_and_expect_empty_response(FunctionCode::Write, request) .await?; // ANCHOR_END: write_attribute } diff --git a/ffi/bindings/c/master_example.c b/ffi/bindings/c/master_example.c index 5f779f9b..41c6fd33 100644 --- a/ffi/bindings/c/master_example.c +++ b/ffi/bindings/c/master_example.c @@ -294,10 +294,10 @@ int run_channel(dnp3_master_channel_t *channel, dnp3_association_id_t associatio { // create an event poll // ANCHOR: add_poll - dnp3_request_t *poll_request = dnp3_request_new_class(false, true, true, true); + dnp3_read_request_t *poll_request = dnp3_read_request_new_class_scan(false, true, true, true); dnp3_poll_id_t poll_id; dnp3_param_error_t err = dnp3_master_channel_add_poll(channel, association_id, poll_request, 5000, &poll_id); - dnp3_request_destroy(poll_request); + dnp3_read_request_destroy(poll_request); // ANCHOR_END: add_poll if (err) { printf("unable to add poll: %s\n", dnp3_param_error_to_string(err)); @@ -347,8 +347,7 @@ void run_command(dnp3_master_channel_t *channel, dnp3_association_id_t associati print_outcome("dlv", dnp3_master_channel_set_decode_level(channel, level), "success"); } else if (strcmp(cmd, "rao") == 0) { - dnp3_request_t *request = dnp3_request_create(); - dnp3_request_add_all_objects_header(request, DNP3_VARIATION_GROUP40_VAR0); + dnp3_read_request_t *request = dnp3_read_request_new_all_objects(DNP3_VARIATION_GROUP40_VAR0); dnp3_read_task_callback_t cb = { .on_complete = &on_read_complete, .on_failure = &on_read_failure, @@ -356,13 +355,12 @@ void run_command(dnp3_master_channel_t *channel, dnp3_association_id_t associati .ctx = "rao", }; dnp3_param_error_t err = dnp3_master_channel_read(channel, association_id, request, cb); - dnp3_request_destroy(request); + dnp3_read_request_destroy(request); print_outcome("rao", err, NULL); } else if (strcmp(cmd, "rmo") == 0) { - dnp3_request_t *request = dnp3_request_create(); - dnp3_request_add_all_objects_header(request, DNP3_VARIATION_GROUP10_VAR0); - dnp3_request_add_all_objects_header(request, DNP3_VARIATION_GROUP40_VAR0); + dnp3_read_request_t *request = dnp3_read_request_new_all_objects(DNP3_VARIATION_GROUP10_VAR0); + dnp3_read_request_add_all_objects_header(request, DNP3_VARIATION_GROUP40_VAR0); dnp3_read_task_callback_t cb = { .on_complete = &on_read_complete, .on_failure = &on_read_failure, @@ -370,13 +368,12 @@ void run_command(dnp3_master_channel_t *channel, dnp3_association_id_t associati .ctx = "rmo", }; dnp3_param_error_t err = dnp3_master_channel_read(channel, association_id, request, cb); - dnp3_request_destroy(request); + dnp3_read_request_destroy(request); print_outcome("rmo", err, NULL); } else if (strcmp(cmd, "rco") == 0) { - dnp3_request_t *request = dnp3_request_create(); - dnp3_request_add_all_objects_header(request, DNP3_VARIATION_GROUP20_VAR0); - dnp3_request_add_all_objects_header(request, DNP3_VARIATION_GROUP21_VAR0); + dnp3_read_request_t *request = dnp3_read_request_new_all_objects(DNP3_VARIATION_GROUP20_VAR0); + dnp3_read_request_add_all_objects_header(request, DNP3_VARIATION_GROUP21_VAR0); dnp3_read_task_callback_t cb = { .on_complete = &on_read_complete, .on_failure = &on_read_failure, @@ -384,7 +381,7 @@ void run_command(dnp3_master_channel_t *channel, dnp3_association_id_t associati .ctx = "rco", }; dnp3_param_error_t err = dnp3_master_channel_read(channel, association_id, request, cb); - dnp3_request_destroy(request); + dnp3_read_request_destroy(request); print_outcome("rco", err, NULL); } else if (strcmp(cmd, "cmd") == 0) { @@ -516,8 +513,7 @@ void run_command(dnp3_master_channel_t *channel, dnp3_association_id_t associati } else if (strcmp(cmd, "rda") == 0) { // ANCHOR: read_attributes - dnp3_request_t *request = dnp3_request_create(); - dnp3_request_add_specific_attribute(request, DNP3_ATTRIBUTE_VARIATIONS_ALL_ATTRIBUTES_REQUEST, 0); + dnp3_read_request_t *request = dnp3_read_request_new_specific_attribute(DNP3_ATTRIBUTE_VARIATIONS_ALL_ATTRIBUTES_REQUEST, 0); dnp3_read_task_callback_t cb = { .on_complete = &on_read_complete, @@ -527,7 +523,7 @@ void run_command(dnp3_master_channel_t *channel, dnp3_association_id_t associati }; dnp3_param_error_t err = dnp3_master_channel_read(channel, association_id, request, cb); - dnp3_request_destroy(request); + dnp3_read_request_destroy(request); // ANCHOR_END: read_attributes print_outcome("rda", err, NULL); } @@ -549,8 +545,7 @@ void run_command(dnp3_master_channel_t *channel, dnp3_association_id_t associati print_outcome("wda", err, NULL); } else if (strcmp(cmd, "ral") == 0) { - dnp3_request_t *request = dnp3_request_create(); - dnp3_request_add_specific_attribute(request, DNP3_ATTRIBUTE_VARIATIONS_LIST_OF_VARIATIONS, 0); + dnp3_read_request_t *request = dnp3_read_request_new_specific_attribute(DNP3_ATTRIBUTE_VARIATIONS_LIST_OF_VARIATIONS, 0); dnp3_read_task_callback_t cb = { .on_complete = &on_read_complete, .on_failure = &on_read_failure, @@ -558,7 +553,7 @@ void run_command(dnp3_master_channel_t *channel, dnp3_association_id_t associati .ctx = "ral", }; dnp3_param_error_t err = dnp3_master_channel_read(channel, association_id, request, cb); - dnp3_request_destroy(request); + dnp3_read_request_destroy(request); print_outcome("ral", err, NULL); } else if (strcmp(cmd, "crt") == 0) { diff --git a/ffi/bindings/c/master_example.cpp b/ffi/bindings/c/master_example.cpp index 70e09a9e..71e14041 100644 --- a/ffi/bindings/c/master_example.cpp +++ b/ffi/bindings/c/master_example.cpp @@ -226,7 +226,7 @@ void run_channel(dnp3::MasterChannel &channel, dnp3::AssociationId assoc) { // create an event poll // ANCHOR: add_poll - auto event_scan = dnp3::Request::class_request(false, true, true, true); + auto event_scan = dnp3::ReadRequest::class_scan(false, true, true, true); const auto event_poll = channel.add_poll(assoc, event_scan, std::chrono::seconds(5)); // ANCHOR_END: add_poll @@ -281,19 +281,16 @@ void run_command(const std::string &cmd, dnp3::MasterChannel &channel, dnp3::Ass std::cout << "dlv: success" << std::endl; } else if (cmd == "rao") { - dnp3::Request request; - request.add_all_objects_header(dnp3::Variation::group40_var0); + auto request = dnp3::ReadRequest::all_objects(dnp3::Variation::group40_var0); channel.read(assoc, request, create_read_callback("rao")); } else if (cmd == "rmo") { - dnp3::Request request; - request.add_all_objects_header(dnp3::Variation::group10_var0); + auto request = dnp3::ReadRequest::all_objects(dnp3::Variation::group10_var0); request.add_all_objects_header(dnp3::Variation::group40_var0); channel.read(assoc, request, create_read_callback("rmo")); } else if (cmd == "rco") { - dnp3::Request request; - request.add_all_objects_header(dnp3::Variation::group20_var0); + auto request = dnp3::ReadRequest::all_objects(dnp3::Variation::group20_var0); request.add_all_objects_header(dnp3::Variation::group21_var0); channel.read(assoc, request, create_read_callback("rco")); } @@ -354,8 +351,7 @@ void run_command(const std::string &cmd, dnp3::MasterChannel &channel, dnp3::Ass } else if (cmd == "rda") { // ANCHOR: read_attributes - dnp3::Request request; - request.add_specific_attribute(dnp3::attribute_variations::all_attributes_request, 0); + auto request = dnp3::ReadRequest::specific_attribute(dnp3::attribute_variations::all_attributes_request, 0); channel.read(assoc, request, create_read_callback("rda")); // ANCHOR_END: read_attributes } @@ -367,8 +363,7 @@ void run_command(const std::string &cmd, dnp3::MasterChannel &channel, dnp3::Ass // ANCHOR_END: write_attribute } else if (cmd == "ral") { - dnp3::Request request; - request.add_specific_attribute(dnp3::attribute_variations::list_of_variations, 0); + auto request = dnp3::ReadRequest::specific_attribute(dnp3::attribute_variations::list_of_variations, 0); channel.read(assoc, request, create_read_callback("ral")); } else if (cmd == "crt") { diff --git a/ffi/bindings/c/smoke_test.c b/ffi/bindings/c/smoke_test.c index 02c53874..6f210a47 100644 --- a/ffi/bindings/c/smoke_test.c +++ b/ffi/bindings/c/smoke_test.c @@ -300,9 +300,9 @@ static bool read_class0(dnp3_master_channel_t *channel, dnp3_association_id_t as .on_failure = &on_read_failure, .ctx = state, }; - dnp3_request_t *request = dnp3_request_new_class(true, false, false, false); + dnp3_read_request_t *request = dnp3_read_request_new_class_scan(true, false, false, false); dnp3_param_error_t err = dnp3_master_channel_read(channel, association, request, callback); - dnp3_request_destroy(request); + dnp3_read_request_destroy(request); if (!check_param(err, "start the read") || !wait_for(state, &read_done, "the read")) { return false; } diff --git a/ffi/bindings/c/smoke_test.cpp b/ffi/bindings/c/smoke_test.cpp index 25e20c2f..67bb0638 100644 --- a/ffi/bindings/c/smoke_test.cpp +++ b/ffi/bindings/c/smoke_test.cpp @@ -286,7 +286,7 @@ void run(State &state) state.wait_for([&]() { return state.connected; }, "the master to connect"); // a class 0 read returns the outstation's values - auto request = dnp3::Request::class_request(true, false, false, false); + auto request = dnp3::ReadRequest::class_scan(true, false, false, false); channel.read(association, request, std::make_unique(state)); state.wait_for([&]() { return state.read_result != Result::pending; }, "the read"); { diff --git a/ffi/bindings/dotnet/dnp3-tests/SmokeTest.cs b/ffi/bindings/dotnet/dnp3-tests/SmokeTest.cs index 5c0de5bc..598e0038 100644 --- a/ffi/bindings/dotnet/dnp3-tests/SmokeTest.cs +++ b/ffi/bindings/dotnet/dnp3-tests/SmokeTest.cs @@ -219,7 +219,7 @@ public async Task MasterReadsAndOperatesOutstation() await connected.Task.WaitAsync(WaitTimeout); // a class 0 read returns the outstation's values - await channel.Read(association, Request.ClassRequest(true, false, false, false)).WaitAsync(WaitTimeout); + await channel.Read(association, ReadRequest.ClassScan(true, false, false, false)).WaitAsync(WaitTimeout); Assert.AreEqual(true, readHandler.BinaryValue); Assert.AreEqual(42.0, readHandler.AnalogValue); diff --git a/ffi/bindings/dotnet/examples/master/Program.cs b/ffi/bindings/dotnet/examples/master/Program.cs index 63d0a814..5fcf7308 100644 --- a/ffi/bindings/dotnet/examples/master/Program.cs +++ b/ffi/bindings/dotnet/examples/master/Program.cs @@ -73,7 +73,7 @@ public static async Task Main(string[] args) // create an event poll // ANCHOR: add_poll - var poll = channel.AddPoll(association, Request.ClassRequest(false, true, true, true), TimeSpan.FromSeconds(5)); + var poll = channel.AddPoll(association, ReadRequest.ClassScan(false, true, true, true), TimeSpan.FromSeconds(5)); // ANCHOR_END: add_poll // enable communications @@ -237,23 +237,20 @@ private static async Task RunOneCommand(MasterChannel channel, Associati } case "rao": { - var request = new Request(); - request.AddAllObjectsHeader(Variation.Group40Var0); + var request = ReadRequest.AllObjects(Variation.Group40Var0); await channel.Read(association, request); return Success; } case "rmo": { - var request = new Request(); - request.AddAllObjectsHeader(Variation.Group10Var0); + var request = ReadRequest.AllObjects(Variation.Group10Var0); request.AddAllObjectsHeader(Variation.Group40Var0); await channel.Read(association, request); return Success; } case "rco": { - var request = new Request(); - request.AddAllObjectsHeader(Variation.Group20Var0); + var request = ReadRequest.AllObjects(Variation.Group20Var0); request.AddAllObjectsHeader(Variation.Group21Var0); await channel.Read(association, request); return Success; @@ -334,8 +331,7 @@ private static async Task RunOneCommand(MasterChannel channel, Associati case "rda": { // ANCHOR: read_attributes - var request = new Request(); - request.AddSpecificAttribute(AttributeVariations.AllAttributesRequest, 0); + var request = ReadRequest.SpecificAttribute(AttributeVariations.AllAttributesRequest, 0); await channel.Read(association, request); // ANCHOR_END: read_attributes return Success; @@ -351,8 +347,7 @@ private static async Task RunOneCommand(MasterChannel channel, Associati } case "ral": { - var request = new Request(); - request.AddSpecificAttribute(AttributeVariations.ListOfVariations, 0); + var request = ReadRequest.SpecificAttribute(AttributeVariations.ListOfVariations, 0); await channel.Read(association, request); return Success; } diff --git a/ffi/bindings/java/dnp3-tests/src/test/java/io/stepfunc/dnp3/tests/SmokeTest.java b/ffi/bindings/java/dnp3-tests/src/test/java/io/stepfunc/dnp3/tests/SmokeTest.java index 955d7fb8..27868139 100644 --- a/ffi/bindings/java/dnp3-tests/src/test/java/io/stepfunc/dnp3/tests/SmokeTest.java +++ b/ffi/bindings/java/dnp3-tests/src/test/java/io/stepfunc/dnp3/tests/SmokeTest.java @@ -277,7 +277,7 @@ void masterReadsAndOperatesOutstation() throws Exception { // a class 0 read returns the outstation's values channel - .read(association, Request.classRequest(true, false, false, false)) + .read(association, ReadRequest.classScan(true, false, false, false)) .toCompletableFuture() .get(WAIT_TIMEOUT_SECONDS, TimeUnit.SECONDS); assertEquals(Boolean.TRUE, readHandler.getBinaryValue()); diff --git a/ffi/bindings/java/examples/src/main/java/io/stepfunc/dnp3/examples/MasterExample.java b/ffi/bindings/java/examples/src/main/java/io/stepfunc/dnp3/examples/MasterExample.java index 1a7b832c..b7c80dd0 100644 --- a/ffi/bindings/java/examples/src/main/java/io/stepfunc/dnp3/examples/MasterExample.java +++ b/ffi/bindings/java/examples/src/main/java/io/stepfunc/dnp3/examples/MasterExample.java @@ -93,7 +93,7 @@ private static void run(Runtime runtime, String[] args) throws IOException { // ANCHOR: add_poll PollId poll = channel.addPoll( - association, Request.classRequest(false, true, true, true), Duration.ofSeconds(5)); + association, ReadRequest.classScan(false, true, true, true), Duration.ofSeconds(5)); // ANCHOR_END: add_poll // enable communications @@ -297,23 +297,20 @@ private static String runOneCommand(MasterChannel channel, AssociationId associa return success; case "rao": { - Request request = new Request(); - request.addAllObjectsHeader(Variation.GROUP40_VAR0); + ReadRequest request = ReadRequest.allObjects(Variation.GROUP40_VAR0); channel.read(association, request).toCompletableFuture().get(); return success; } case "rmo": { - Request request = new Request(); - request.addAllObjectsHeader(Variation.GROUP10_VAR0); + ReadRequest request = ReadRequest.allObjects(Variation.GROUP10_VAR0); request.addAllObjectsHeader(Variation.GROUP40_VAR0); channel.read(association, request).toCompletableFuture().get(); return success; } case "rco": { - Request request = new Request(); - request.addAllObjectsHeader(Variation.GROUP20_VAR0); + ReadRequest request = ReadRequest.allObjects(Variation.GROUP20_VAR0); request.addAllObjectsHeader(Variation.GROUP21_VAR0); channel.read(association, request).toCompletableFuture().get(); return success; @@ -393,8 +390,8 @@ private static String runOneCommand(MasterChannel channel, AssociationId associa case "rda": { // ANCHOR: read_attributes - Request request = new Request(); - request.addSpecificAttribute(AttributeVariations.ALL_ATTRIBUTES_REQUEST, ubyte(0)); + ReadRequest request = + ReadRequest.specificAttribute(AttributeVariations.ALL_ATTRIBUTES_REQUEST, ubyte(0)); channel.read(association, request).toCompletableFuture().get(); // ANCHOR_END: read_attributes return success; @@ -410,8 +407,8 @@ private static String runOneCommand(MasterChannel channel, AssociationId associa } case "ral": { - Request request = new Request(); - request.addSpecificAttribute(AttributeVariations.LIST_OF_VARIATIONS, ubyte(0)); + ReadRequest request = + ReadRequest.specificAttribute(AttributeVariations.LIST_OF_VARIATIONS, ubyte(0)); channel.read(association, request).toCompletableFuture().get(); return success; } diff --git a/ffi/dnp3-ffi/src/master/functions.rs b/ffi/dnp3-ffi/src/master/functions.rs index 6e360d4a..9b0f346f 100644 --- a/ffi/dnp3-ffi/src/master/functions.rs +++ b/ffi/dnp3-ffi/src/master/functions.rs @@ -464,7 +464,7 @@ pub(crate) unsafe fn master_channel_remove_association( pub(crate) unsafe fn master_channel_add_poll( channel: *mut MasterChannel, id: ffi::AssociationId, - request: *mut crate::Request, + request: *mut crate::ReadRequest, period: std::time::Duration, ) -> Result { let channel = channel.as_mut().ok_or(ffi::ParamError::NullParameter)?; @@ -474,7 +474,7 @@ pub(crate) unsafe fn master_channel_add_poll( let mut association = AssociationHandle::create(address, channel.handle.clone()); let handle = channel .runtime - .block_on(association.add_poll(request.build_read_request(), period))??; + .block_on(association.add_poll(request.clone_inner(), period))??; Ok(ffi::PollId { association_id: id.address, @@ -519,7 +519,7 @@ pub(crate) unsafe fn master_channel_demand_poll( pub(crate) unsafe fn master_channel_read( channel: *mut crate::MasterChannel, association: ffi::AssociationId, - request: *mut crate::Request, + request: *mut crate::ReadRequest, callback: ffi::ReadTaskCallback, ) -> Result<(), ffi::ParamError> { let channel = channel.as_mut().ok_or(ffi::ParamError::NullParameter)?; @@ -527,7 +527,7 @@ pub(crate) unsafe fn master_channel_read( let request = request .as_ref() .ok_or(ffi::ParamError::NullParameter)? - .build_read_request(); + .clone_inner(); let promise = sfio_promise::wrap(callback); @@ -569,23 +569,23 @@ pub(crate) unsafe fn master_channel_send_and_expect_empty_response( channel: *mut crate::MasterChannel, association: ffi::AssociationId, function: ffi::FunctionCode, - headers: *mut crate::Request, + request: *mut crate::Request, callback: ffi::EmptyResponseCallback, ) -> Result<(), ffi::ParamError> { let channel = channel.as_mut().ok_or(ffi::ParamError::NullParameter)?; let address = EndpointAddress::try_new(association.address)?; let function: dnp3::app::FunctionCode = function.into(); - let headers = headers - .as_mut() + let request = request + .as_ref() .ok_or(ffi::ParamError::NullParameter)? - .build_headers(); + .clone_inner(); let promise = sfio_promise::wrap(callback); let mut handle = AssociationHandle::create(address, channel.handle.clone()); let task = async move { let res = handle - .send_and_expect_empty_response(function, headers) + .send_and_expect_empty_response(function, request) .await; promise.complete(res); }; @@ -597,7 +597,7 @@ pub(crate) unsafe fn master_channel_send_and_expect_empty_response( pub(crate) unsafe fn master_channel_read_with_handler( channel: *mut crate::MasterChannel, association: ffi::AssociationId, - request: *mut crate::Request, + request: *mut crate::ReadRequest, handler: ffi::ReadHandler, callback: ffi::ReadTaskCallback, ) -> Result<(), ffi::ParamError> { @@ -606,7 +606,7 @@ pub(crate) unsafe fn master_channel_read_with_handler( let request = request .as_ref() .ok_or(ffi::ParamError::NullParameter)? - .build_read_request(); + .clone_inner(); let promise = sfio_promise::wrap(callback); diff --git a/ffi/dnp3-ffi/src/request.rs b/ffi/dnp3-ffi/src/request.rs index 7ed36d63..51ab8888 100644 --- a/ffi/dnp3-ffi/src/request.rs +++ b/ffi/dnp3-ffi/src/request.rs @@ -6,48 +6,188 @@ use dnp3::app::attr::*; use dnp3::app::{Timestamp, Variation}; -use dnp3::master::{Headers, ReadHeader, ReadRequest}; -use dnp3::outstation::FreezeInterval; +use dnp3::master::{Classes, EventClasses}; use std::ffi::CStr; use crate::ffi; +pub struct ReadRequest { + inner: dnp3::master::ReadRequest, +} + +impl ReadRequest { + pub(crate) fn clone_inner(&self) -> dnp3::master::ReadRequest { + self.inner.clone() + } + + fn create(inner: dnp3::master::ReadRequest) -> *mut ReadRequest { + Box::into_raw(Box::new(ReadRequest { inner })) + } + + /// replace the request with `f` of it, since its add methods take it by value + fn update(&mut self, f: impl FnOnce(dnp3::master::ReadRequest) -> dnp3::master::ReadRequest) { + // a single header, which doesn't allocate, stands in until `f` returns + let placeholder = dnp3::master::ReadRequest::all_objects(Variation::Group60Var1); + let request = std::mem::replace(&mut self.inner, placeholder); + self.inner = f(request); + } +} + pub struct Request { - headers: Headers, + inner: dnp3::master::Request, } impl Request { - fn new() -> Self { - Self { - headers: Default::default(), - } + pub(crate) fn clone_inner(&self) -> dnp3::master::Request { + self.inner.clone() + } + + fn create(inner: dnp3::master::Request) -> *mut Request { + Box::into_raw(Box::new(Request { inner })) } - pub(crate) fn add_read_header(&mut self, header: ReadHeader) { - self.headers.push_read_header(header); + /// replace the request with `f` of it, since its add methods take it by value + fn update(&mut self, f: impl FnOnce(dnp3::master::Request) -> dnp3::master::Request) { + self.inner = f(std::mem::take(&mut self.inner)); } +} + +pub unsafe fn read_request_new_class_scan( + class0: bool, + class1: bool, + class2: bool, + class3: bool, +) -> *mut ReadRequest { + ReadRequest::create(dnp3::master::ReadRequest::class_scan(Classes::new( + class0, + EventClasses::new(class1, class2, class3), + ))) +} + +pub unsafe fn read_request_new_specific_attribute(variation: u8, set: u8) -> *mut ReadRequest { + ReadRequest::create(dnp3::master::ReadRequest::device_attribute( + variation, + AttrSet::new(set), + )) +} + +pub unsafe fn read_request_new_all_objects(variation: ffi::Variation) -> *mut ReadRequest { + ReadRequest::create(dnp3::master::ReadRequest::all_objects(variation.into())) +} + +pub unsafe fn read_request_new_one_byte_range( + variation: ffi::Variation, + start: u8, + stop: u8, +) -> *mut ReadRequest { + ReadRequest::create(dnp3::master::ReadRequest::one_byte_range( + variation.into(), + start, + stop, + )) +} + +pub unsafe fn read_request_new_two_byte_range( + variation: ffi::Variation, + start: u16, + stop: u16, +) -> *mut ReadRequest { + ReadRequest::create(dnp3::master::ReadRequest::two_byte_range( + variation.into(), + start, + stop, + )) +} + +pub unsafe fn read_request_new_one_byte_limited_count( + variation: ffi::Variation, + count: u8, +) -> *mut ReadRequest { + ReadRequest::create(dnp3::master::ReadRequest::one_byte_limited_count( + variation.into(), + count, + )) +} - pub(crate) fn add_attribute(&mut self, attr: OwnedAttribute) { - self.headers.push_attr(attr); +pub unsafe fn read_request_new_two_byte_limited_count( + variation: ffi::Variation, + count: u16, +) -> *mut ReadRequest { + ReadRequest::create(dnp3::master::ReadRequest::two_byte_limited_count( + variation.into(), + count, + )) +} + +pub unsafe fn read_request_destroy(request: *mut ReadRequest) { + if !request.is_null() { + drop(Box::from_raw(request)); } +} - pub(crate) fn add_time_and_interval(&mut self, time: Timestamp, interval: u32) { - self.headers - .push_freeze_interval(FreezeInterval::new(time, interval)); +pub(crate) unsafe fn read_request_add_specific_attribute( + request: *mut ReadRequest, + variation: u8, + set: u8, +) { + if let Some(request) = request.as_mut() { + request.update(|r| r.add_device_attribute(variation, AttrSet::new(set))); } +} - pub(crate) fn build_read_request(&self) -> ReadRequest { - self.headers.to_read_request() +pub(crate) unsafe fn read_request_add_one_byte_range_header( + request: *mut ReadRequest, + variation: ffi::Variation, + start: u8, + stop: u8, +) { + if let Some(request) = request.as_mut() { + request.update(|r| r.add_range_8(variation.into(), start, stop)); } +} - pub(crate) fn build_headers(&self) -> Headers { - self.headers.clone() +pub(crate) unsafe fn read_request_add_two_byte_range_header( + request: *mut ReadRequest, + variation: ffi::Variation, + start: u16, + stop: u16, +) { + if let Some(request) = request.as_mut() { + request.update(|r| r.add_range_16(variation.into(), start, stop)); + } +} + +pub(crate) unsafe fn read_request_add_all_objects_header( + request: *mut ReadRequest, + variation: ffi::Variation, +) { + if let Some(request) = request.as_mut() { + request.update(|r| r.add_all_objects(variation.into())); + } +} + +pub(crate) unsafe fn read_request_add_one_byte_limited_count_header( + request: *mut ReadRequest, + variation: ffi::Variation, + count: u8, +) { + if let Some(request) = request.as_mut() { + request.update(|r| r.add_one_byte_limited_count(variation.into(), count)); + } +} + +pub(crate) unsafe fn read_request_add_two_byte_limited_count_header( + request: *mut ReadRequest, + variation: ffi::Variation, + count: u16, +) { + if let Some(request) = request.as_mut() { + request.update(|r| r.add_two_byte_limited_count(variation.into(), count)); } } pub unsafe fn request_create() -> *mut Request { - let request = Box::new(Request::new()); - Box::into_raw(request) + Request::create(dnp3::master::Request::new()) } pub unsafe fn request_new_class( @@ -56,30 +196,24 @@ pub unsafe fn request_new_class( class2: bool, class3: bool, ) -> *mut Request { - let mut request = Request::new(); - if class1 { - request.add_read_header(ReadHeader::all_objects(Variation::Group60Var2)); - } - if class2 { - request.add_read_header(ReadHeader::all_objects(Variation::Group60Var3)); - } - if class3 { - request.add_read_header(ReadHeader::all_objects(Variation::Group60Var4)); - } - if class0 { - request.add_read_header(ReadHeader::all_objects(Variation::Group60Var1)); - } - - let request = Box::new(request); - Box::into_raw(request) + // the event classes first, then class 0, as a class scan writes them + let classes = [ + (class1, Variation::Group60Var2), + (class2, Variation::Group60Var3), + (class3, Variation::Group60Var4), + (class0, Variation::Group60Var1), + ]; + let request = classes + .into_iter() + .filter(|(enabled, _)| *enabled) + .fold(dnp3::master::Request::new(), |request, (_, variation)| { + request.add_all_objects(variation) + }); + Request::create(request) } pub unsafe fn request_new_all_objects(variation: ffi::Variation) -> *mut Request { - let mut request = Request::new(); - request.add_read_header(ReadHeader::all_objects(variation.into())); - - let request = Box::new(request); - Box::into_raw(request) + Request::create(dnp3::master::Request::new().add_all_objects(variation.into())) } pub unsafe fn request_new_one_byte_range( @@ -87,11 +221,7 @@ pub unsafe fn request_new_one_byte_range( start: u8, stop: u8, ) -> *mut Request { - let mut request = Request::new(); - request.add_read_header(ReadHeader::one_byte_range(variation.into(), start, stop)); - - let request = Box::new(request); - Box::into_raw(request) + Request::create(dnp3::master::Request::new().add_range_8(variation.into(), start, stop)) } pub unsafe fn request_new_two_byte_range( @@ -99,33 +229,25 @@ pub unsafe fn request_new_two_byte_range( start: u16, stop: u16, ) -> *mut Request { - let mut request = Request::new(); - request.add_read_header(ReadHeader::two_byte_range(variation.into(), start, stop)); - - let request = Box::new(request); - Box::into_raw(request) + Request::create(dnp3::master::Request::new().add_range_16(variation.into(), start, stop)) } pub unsafe fn request_new_one_byte_limited_count( variation: ffi::Variation, count: u8, ) -> *mut Request { - let mut request = Request::new(); - request.add_read_header(ReadHeader::one_byte_limited_count(variation.into(), count)); - - let request = Box::new(request); - Box::into_raw(request) + Request::create( + dnp3::master::Request::new().add_one_byte_limited_count(variation.into(), count), + ) } pub unsafe fn request_new_two_byte_limited_count( variation: ffi::Variation, count: u16, ) -> *mut Request { - let mut request = Request::new(); - request.add_read_header(ReadHeader::two_byte_limited_count(variation.into(), count)); - - let request = Box::new(request); - Box::into_raw(request) + Request::create( + dnp3::master::Request::new().add_two_byte_limited_count(variation.into(), count), + ) } pub unsafe fn request_destroy(request: *mut Request) { @@ -134,58 +256,46 @@ pub unsafe fn request_destroy(request: *mut Request) { } } -pub(crate) unsafe fn request_add_one_byte_range_header( - request: *mut Request, - variation: ffi::Variation, - start: u8, - stop: u8, -) { - if let Some(request) = request.as_mut() { - request.add_read_header(ReadHeader::one_byte_range(variation.into(), start, stop)); - } -} - -pub(crate) unsafe fn request_add_specific_attribute( - request: *mut crate::Request, - variation: u8, - set: u8, -) { - if let Some(request) = request.as_mut() { - request.add_read_header(ReadHeader::one_byte_range( - Variation::Group0(variation), - set, - set, - )); - } -} - pub(crate) unsafe fn request_add_string_attribute( - request: *mut crate::Request, + request: *mut Request, variation: u8, set: u8, value: &CStr, ) { if let Some(request) = request.as_mut() { - request.add_attribute(OwnedAttribute::new( + let attr = OwnedAttribute::new( AttrSet::new(set), variation, OwnedAttrValue::VisibleString(value.to_string_lossy().to_string()), - )) + ); + request.update(|r| r.add_attribute(attr)); } } pub(crate) unsafe fn request_add_uint_attribute( - request: *mut crate::Request, + request: *mut Request, variation: u8, set: u8, value: u32, ) { if let Some(request) = request.as_mut() { - request.add_attribute(OwnedAttribute::new( + let attr = OwnedAttribute::new( AttrSet::new(set), variation, OwnedAttrValue::UnsignedInt(value), - )) + ); + request.update(|r| r.add_attribute(attr)); + } +} + +pub(crate) unsafe fn request_add_one_byte_range_header( + request: *mut Request, + variation: ffi::Variation, + start: u8, + stop: u8, +) { + if let Some(request) = request.as_mut() { + request.update(|r| r.add_range_8(variation.into(), start, stop)); } } @@ -196,7 +306,7 @@ pub(crate) unsafe fn request_add_two_byte_range_header( stop: u16, ) { if let Some(request) = request.as_mut() { - request.add_read_header(ReadHeader::two_byte_range(variation.into(), start, stop)); + request.update(|r| r.add_range_16(variation.into(), start, stop)); } } @@ -205,36 +315,36 @@ pub(crate) unsafe fn request_add_all_objects_header( variation: ffi::Variation, ) { if let Some(request) = request.as_mut() { - request.add_read_header(ReadHeader::all_objects(variation.into())); + request.update(|r| r.add_all_objects(variation.into())); } } -pub unsafe fn request_add_one_byte_limited_count_header( +pub(crate) unsafe fn request_add_one_byte_limited_count_header( request: *mut Request, variation: ffi::Variation, count: u8, ) { if let Some(request) = request.as_mut() { - request.add_read_header(ReadHeader::one_byte_limited_count(variation.into(), count)); + request.update(|r| r.add_one_byte_limited_count(variation.into(), count)); } } -pub unsafe fn request_add_two_byte_limited_count_header( +pub(crate) unsafe fn request_add_two_byte_limited_count_header( request: *mut Request, variation: ffi::Variation, count: u16, ) { if let Some(request) = request.as_mut() { - request.add_read_header(ReadHeader::two_byte_limited_count(variation.into(), count)); + request.update(|r| r.add_two_byte_limited_count(variation.into(), count)); } } pub(crate) unsafe fn request_add_time_and_interval( - request: *mut crate::Request, + request: *mut Request, time: u64, interval_ms: u32, ) { if let Some(request) = request.as_mut() { - request.add_time_and_interval(Timestamp::new(time), interval_ms); + request.update(|r| r.add_time_and_interval(Timestamp::new(time), interval_ms)); } } diff --git a/ffi/dnp3-schema/src/master/mod.rs b/ffi/dnp3-schema/src/master/mod.rs index 8371ffa2..995ef7ef 100644 --- a/ffi/dnp3-schema/src/master/mod.rs +++ b/ffi/dnp3-schema/src/master/mod.rs @@ -266,7 +266,7 @@ pub(crate) fn define(lib: &mut LibraryBuilder, shared: &SharedDefinitions) -> Ba let association_information_interface = define_association_information(lib, shared)?; - let request_class = crate::master::request::define(lib, shared)?; + let requests = crate::master::request::define(lib, shared)?; let add_association_method = lib .define_method("add_association", master_channel_class.clone())? @@ -342,7 +342,7 @@ pub(crate) fn define(lib: &mut LibraryBuilder, shared: &SharedDefinitions) -> Ba let add_poll_method = lib.define_method("add_poll", master_channel_class.clone())? .param("id", association_id.clone(), "Association on which to add the poll")? - .param("request", request_class.declaration(), "Request to perform")? + .param("request", requests.read_request.declaration(), "Request to perform")? .param("period", DurationType::Milliseconds, "Period to wait between each poll (in ms)")? .returns(poll_id.clone(), "Id of the created poll")? .fails_with(shared.error_type.clone())? @@ -398,7 +398,7 @@ pub(crate) fn define(lib: &mut LibraryBuilder, shared: &SharedDefinitions) -> Ba let read_async = lib .define_future_method("read", master_channel_class.clone(), read_callback.clone())? .param("association",association_id.clone(), "Association on which to perform the read")? - .param("request",request_class.declaration(), "Request to send")? + .param("request",requests.read_request.declaration(), "Request to send")? .fails_with(shared.error_type.clone())? .doc( doc("Perform a read on the association.") @@ -446,7 +446,7 @@ pub(crate) fn define(lib: &mut LibraryBuilder, shared: &SharedDefinitions) -> Ba )? .param( "headers", - request_class.declaration(), + requests.request.declaration(), "Headers that will be contained in the request", )? .fails_with(shared.error_type.clone())? @@ -460,7 +460,7 @@ pub(crate) fn define(lib: &mut LibraryBuilder, shared: &SharedDefinitions) -> Ba let read_with_handler_async = lib .define_future_method("read_with_handler", master_channel_class.clone(), read_callback)? .param("association",association_id.clone(), "Association on which to perform the read")? - .param("request",request_class.declaration(), "Request to send")? + .param("request",requests.read_request.declaration(), "Request to send")? .param("handler",read_handler, "Custom {interface:read_handler} to send the data to")? .fails_with(shared.error_type.clone())? .doc( diff --git a/ffi/dnp3-schema/src/master/request.rs b/ffi/dnp3-schema/src/master/request.rs index 2a57be5d..0ee8a909 100644 --- a/ffi/dnp3-schema/src/master/request.rs +++ b/ffi/dnp3-schema/src/master/request.rs @@ -8,15 +8,109 @@ use oo_bindgen::model::*; use crate::shared::SharedDefinitions; +pub(crate) struct RequestClasses { + /// the headers of a READ, for reads and polls + pub(crate) read_request: ClassHandle, + /// the headers of a request that expects an empty response, such as a WRITE or a FREEZE + pub(crate) request: ClassHandle, +} + pub(crate) fn define( lib: &mut LibraryBuilder, shared: &SharedDefinitions, +) -> BackTraced { + Ok(RequestClasses { + read_request: define_read_request(lib, shared)?, + request: define_request(lib, shared)?, + }) +} + +fn define_read_request( + lib: &mut LibraryBuilder, + shared: &SharedDefinitions, ) -> BackTraced { - let request = lib.declare_class("request")?; + const NAME: &str = "read_request"; + let read_request = lib.declare_class(NAME)?; + + let class_scan_fn = lib + .define_function("read_request_new_class_scan")? + .param("class0", Primitive::Bool, "Ask for class 0 (static data)")? + .param("class1", Primitive::Bool, "Ask for class 1 events")? + .param("class2", Primitive::Bool, "Ask for class 2 events")? + .param("class3", Primitive::Bool, "Ask for class 3 events")? + .returns(read_request.clone(), "Handle to the created request")? + .doc( + doc("Create a new read request asking for classes") + .details("The request asks for events in classes 1, 2 and 3, then class 0."), + )? + .build_static("class_scan")?; + + let specific_attribute_fn = lib + .define_function("read_request_new_specific_attribute")? + .param( + "variation", + Primitive::U8, + "Variation of the device attribute, 1 to 255 (254 reads every attribute of the set)", + )? + .param( + "set", + Primitive::U8, + "The set (point) to which the attribute belongs", + )? + .returns(read_request.clone(), "Handle to the created request")? + .doc("Create a new read request asking for a specific device attribute (group 0)")? + .build_static("specific_attribute")?; + + let add_specific_attribute_fn = lib + .define_method("add_specific_attribute", read_request.clone())? + .param( + "variation", + Primitive::U8, + "Variation of the device attribute, 1 to 255 (254 reads every attribute of the set)", + )? + .param( + "set", + Primitive::U8, + "The set (point) to which the attribute belongs", + )? + .doc("Add a header that reads a specific device attribute (group 0)")? + .build()?; + + let destructor = lib.define_destructor(read_request.clone(), "Destroy a read request")?; + + let constructors = define_single_header_constructors(lib, shared, &read_request, NAME)?; + let header_methods = define_header_methods(lib, shared, &read_request)?; + + let mut builder = lib + .define_class(&read_request)? + .destructor(destructor)? + .static_method(class_scan_fn)? + .static_method(specific_attribute_fn)?; + for method in constructors { + builder = builder.static_method(method)?; + } + for method in header_methods { + builder = builder.method(method)?; + } + let read_request = builder + .method(add_specific_attribute_fn)? + .doc( + doc("The object headers of a READ, for one-time reads and polls") + .details("Only headers that are valid in a READ can be added. A request that writes or freezes objects is a {class:request}.") + .details("Whenever a method takes a read request as a parameter, the request is internally copied. Therefore, it is possible to reuse the same requests over and over.") + )? + .build()?; + + Ok(read_request) +} + +fn define_request(lib: &mut LibraryBuilder, shared: &SharedDefinitions) -> BackTraced { + const NAME: &str = "request"; + let request = lib.declare_class(NAME)?; let constructor = lib .define_constructor(request.clone())? - .doc("Create a new request")? + .doc("Create a new request with no headers")? .build()?; let request_new_class_fn = lib @@ -35,25 +129,113 @@ pub(crate) fn define( )? .build_static("class_request")?; - let request_new_all_objects_fn = lib - .define_function("request_new_all_objects")? + let destructor = lib + .define_destructor( + request.clone(), + "Destroy a request created with {class:request.[constructor]} or {class:request.class_request()}." + )?; + + let add_string_attribute_fn = lib + .define_method("add_string_attribute", request.clone())? + .param("variation", Primitive::U8, "Variation of the attribute")? + .param( + "set", + Primitive::U8, + "The set (point) to which the attribute belongs", + )? + .param("value", StringType, "Value of the attribute")? + .doc(doc( + "Add a header that writes a visible string device attribute (group 0) for use with a WRITE request", + ))? + .build()?; + + let add_uint_attribute_fn = lib + .define_method("add_uint_attribute", request.clone())? + .param("variation", Primitive::U8, "Variation of the attribute")? + .param( + "set", + Primitive::U8, + "The set (point) to which the attribute belongs", + )? + .param("value", Primitive::U32, "Value of the attribute")? + .doc(doc( + "Add a header that writes an unsigned integer device attribute (group 0) for use with a WRITE request", + ))? + .build()?; + + let add_time_and_interval = lib + .define_method("add_time_and_interval", request.clone())? + .param( + "time", + Primitive::U64, + "DNP3 48-bit timestamp representing count of milliseconds since epoch UTC", + )? + .param( + "interval_ms", + Primitive::U32, + "Interval expressed in milliseconds", + )? + .doc( + doc("Add a single g50v2 time-and-interval") + .details("This is useful when constructing freeze-at-time requests"), + )? + .build()?; + + let constructors = define_single_header_constructors(lib, shared, &request, NAME)?; + let header_methods = define_header_methods(lib, shared, &request)?; + + let mut builder = lib + .define_class(&request)? + .constructor(constructor)? + .destructor(destructor)? + .static_method(request_new_class_fn)?; + for method in constructors { + builder = builder.static_method(method)?; + } + for method in header_methods { + builder = builder.method(method)?; + } + let request = builder + .method(add_time_and_interval)? + .method(add_string_attribute_fn)? + .method(add_uint_attribute_fn)? + .doc( + doc("The object headers of a request that expects an empty response, such as a WRITE or a FREEZE") + .details("Reads and polls take a {class:read_request} instead.") + .details("Whenever a method takes a request as a parameter, the request is internally copied. Therefore, it is possible to reuse the same requests over and over.") + )? + .build()?; + + Ok(request) +} + +/// The static methods that create a request of a single header, for both request classes +fn define_single_header_constructors( + lib: &mut LibraryBuilder, + shared: &SharedDefinitions, + class: &ClassDeclarationHandle, + name: &str, +) -> BackTraced>> { + let more = |method: &str| { + format!("More headers can be added to it with {{class:{name}.{method}()}} and the other add methods.") + }; + + let all_objects = lib + .define_function(format!("{name}_new_all_objects"))? .param( "variation", shared.variation_enum.clone(), "Variation to ask for", )? - .returns( - request.clone(), - "Handle to the created request", - )? + .returns(class.clone(), "Handle to the created request")? .doc( doc("Create a new request asking for all objects of a particular variation.") - .details("An identical request can be created manually with {class:request.[constructor]} and {class:request.add_all_objects_header()}.") + .details(more("add_all_objects_header")), )? .build_static("all_objects")?; - let request_new_one_byte_range_fn = lib - .define_function("request_new_one_byte_range")? + let one_byte_range = lib + .define_function(format!("{name}_new_one_byte_range"))? .param( "variation", shared.variation_enum.clone(), @@ -61,18 +243,15 @@ pub(crate) fn define( )? .param("start", Primitive::U8, "Start index to ask")? .param("stop", Primitive::U8, "Stop index to ask (inclusive)")? - .returns( - request.clone(), - "Handle to the created request", - )? + .returns(class.clone(), "Handle to the created request")? .doc( doc("Create a new request asking for range of objects (using 8-bit start/stop).") - .details("An identical request can be created manually with {class:request.[constructor]} and {class:request.add_one_byte_range_header()}.") + .details(more("add_one_byte_range_header")), )? .build_static("one_byte_range")?; - let request_new_two_byte_range_fn = lib - .define_function("request_new_two_byte_range")? + let two_byte_range = lib + .define_function(format!("{name}_new_two_byte_range"))? .param( "variation", shared.variation_enum.clone(), @@ -80,105 +259,60 @@ pub(crate) fn define( )? .param("start", Primitive::U16, "Start index to ask")? .param("stop", Primitive::U16, "Stop index to ask (inclusive)")? - .returns( - request.clone(), - "Handle to the created request", - )? + .returns(class.clone(), "Handle to the created request")? .doc( doc("Create a new request asking for range of objects (using 16-bit start/stop).") - .details("An identical request can be created manually with {class:request.[constructor]} and {class:request.add_two_byte_range_header()}.") + .details(more("add_two_byte_range_header")), )? .build_static("two_byte_range")?; - let request_new_one_byte_limited_count_fn = lib - .define_function("request_new_one_byte_limited_count")? + let one_byte_limited_count = lib + .define_function(format!("{name}_new_one_byte_limited_count"))? .param( "variation", shared.variation_enum.clone(), "Variation to ask for", )? .param("count", Primitive::U8, "Maximum number of events")? - .returns( - request.clone(), - "Handle to the created request", - )? + .returns(class.clone(), "Handle to the created request")? .doc( - doc("Create a new request asking for a limited count of objects (using 8-bit start/stop).") - .details("An identical request can be created manually with {class:request.[constructor]} and {class:request.add_one_byte_limited_count_header()}.") + doc("Create a new request asking for a limited count of objects (using an 8-bit count).") + .details(more("add_one_byte_limited_count_header")), )? .build_static("one_byte_limited_count")?; - let request_new_two_byte_limited_count_fn = lib - .define_function("request_new_two_byte_limited_count")? + let two_byte_limited_count = lib + .define_function(format!("{name}_new_two_byte_limited_count"))? .param( "variation", shared.variation_enum.clone(), "Variation to ask for", )? .param("count", Primitive::U16, "Maximum number of events")? - .returns( - request.clone(), - "Handle to the created request", - )? + .returns(class.clone(), "Handle to the created request")? .doc( - doc("Create a new request asking for a limited count of objects (using 16-bit start/stop).") - .details("An identical request can be created manually with {class:request.[constructor]} and {class:request.add_two_byte_limited_count_header()}.") + doc("Create a new request asking for a limited count of objects (using a 16-bit count).") + .details(more("add_two_byte_limited_count_header")), )? .build_static("two_byte_limited_count")?; - let destructor = lib - .define_destructor( - request.clone(), - "Destroy a request created with {class:request.[constructor]} or {class:request.class_request()}." - )?; - - let add_specific_attribute_fn = lib - .define_method("add_specific_attribute", request.clone())? - .param( - "variation", - Primitive::U8, - "Variation of the device attribute, 1 to 255 (254 reads every attribute of the set)", - )? - .param( - "set", - Primitive::U8, - "The set (point) to which the attribute belongs", - )? - .doc(doc( - "Add a header that reads a specific device attribute (group 0) for use with a READ request", - ))? - .build()?; - - let add_string_attribute_fn = lib - .define_method("add_string_attribute", request.clone())? - .param("variation", Primitive::U8, "Variation of the attribute")? - .param( - "set", - Primitive::U8, - "The set (point) to which the attribute belongs", - )? - .param("value", StringType, "Value of the attribute")? - .doc(doc( - "Add a header that writes a visible string device attribute (group 0) for use with a WRITE request", - ))? - .build()?; - - let add_uint_attribute_fn = lib - .define_method("add_uint_attribute", request.clone())? - .param("variation", Primitive::U8, "Variation of the attribute")? - .param( - "set", - Primitive::U8, - "The set (point) to which the attribute belongs", - )? - .param("value", Primitive::U32, "Value of the attribute")? - .doc(doc( - "Add a header that writes an unsigned integer device attribute (group 0) for use with a WRITE request", - ))? - .build()?; + Ok(vec![ + all_objects, + one_byte_range, + two_byte_range, + one_byte_limited_count, + two_byte_limited_count, + ]) +} +/// The methods that add a READ-style header, for both request classes +fn define_header_methods( + lib: &mut LibraryBuilder, + shared: &SharedDefinitions, + class: &ClassDeclarationHandle, +) -> BackTraced>> { let add_one_byte_range_header = lib - .define_method("add_one_byte_range_header", request.clone())? + .define_method("add_one_byte_range_header", class.clone())? .param( "variation", shared.variation_enum.clone(), @@ -186,11 +320,11 @@ pub(crate) fn define( )? .param("start", Primitive::U8, "Start index to ask")? .param("stop", Primitive::U8, "Stop index to ask (inclusive)")? - .doc("Add a one-byte start/stop header for use with a READ request")? + .doc("Add a one-byte start/stop header")? .build()?; let add_two_byte_range_header = lib - .define_method("add_two_byte_range_header", request.clone())? + .define_method("add_two_byte_range_header", class.clone())? .param( "variation", shared.variation_enum.clone(), @@ -198,83 +332,46 @@ pub(crate) fn define( )? .param("start", Primitive::U16, "Start index to ask")? .param("stop", Primitive::U16, "Stop index to ask (inclusive)")? - .doc("Add a two-byte start/stop header for use with a READ request")? + .doc("Add a two-byte start/stop header")? .build()?; let add_all_objects_header = lib - .define_method("add_all_objects_header", request.clone())? + .define_method("add_all_objects_header", class.clone())? .param( "variation", shared.variation_enum.clone(), "Variation to ask for", )? - .doc("Add an all objects variation request")? + .doc("Add an all objects header")? .build()?; let add_one_byte_limited_count_header = lib - .define_method("add_one_byte_limited_count_header", request.clone())? + .define_method("add_one_byte_limited_count_header", class.clone())? .param( "variation", shared.variation_enum.clone(), "Variation to ask for", )? .param("count", Primitive::U8, "Maximum number of events")? - .doc("Add a one-byte limited count variation header for use with a READ request")? + .doc("Add a one-byte limited count header")? .build()?; let add_two_byte_limited_count_header = lib - .define_method("add_two_byte_limited_count_header", request.clone())? + .define_method("add_two_byte_limited_count_header", class.clone())? .param( "variation", shared.variation_enum.clone(), "Variation to ask for", )? .param("count", Primitive::U16, "Maximum number of events")? - .doc("Add a two-byte limited count variation header for use with a READ request")? - .build()?; - - let add_time_and_interval = lib - .define_method("add_time_and_interval", request.clone())? - .param( - "time", - Primitive::U64, - "DNP3 48-bit timestamp representing count of milliseconds since epoch UTC", - )? - .param( - "interval_ms", - Primitive::U32, - "Interval expressed in milliseconds", - )? - .doc( - doc("Add a single g51v1 time-and-interval") - .details("This is useful when constructing freeze-at-time requests"), - )? + .doc("Add a two-byte limited count header")? .build()?; - let request = lib - .define_class(&request)? - .constructor(constructor)? - .destructor(destructor)? - .static_method(request_new_class_fn)? - .static_method(request_new_all_objects_fn)? - .static_method(request_new_one_byte_range_fn)? - .static_method(request_new_two_byte_range_fn)? - .static_method(request_new_one_byte_limited_count_fn)? - .static_method(request_new_two_byte_limited_count_fn)? - .method(add_one_byte_range_header)? - .method(add_two_byte_range_header)? - .method(add_all_objects_header)? - .method(add_one_byte_limited_count_header)? - .method(add_two_byte_limited_count_header)? - .method(add_time_and_interval)? - .method(add_specific_attribute_fn)? - .method(add_string_attribute_fn)? - .method(add_uint_attribute_fn)? - .doc( - doc("Custom request") - .details("Whenever a method takes a request as a parameter, the request is internally copied. Therefore, it is possible to reuse the same requests over and over.") - )? - .build()?; - - Ok(request) + Ok(vec![ + add_one_byte_range_header, + add_two_byte_range_header, + add_all_objects_header, + add_one_byte_limited_count_header, + add_two_byte_limited_count_header, + ]) } diff --git a/ffi/dnp3-schema/src/variation.rs b/ffi/dnp3-schema/src/variation.rs index 7e3c3fda..bb68a24d 100644 --- a/ffi/dnp3-schema/src/variation.rs +++ b/ffi/dnp3-schema/src/variation.rs @@ -21,7 +21,7 @@ use oo_bindgen::model::{BackTraced, EnumHandle, LibraryBuilder}; pub(crate) fn define(lib: &mut LibraryBuilder) -> BackTraced { let variation = lib .define_enum("variation")? - .push("group0", "Device Attributes - Specific attribute (variations 1 to 253 and 255). Only reported in {struct:header_info}: it can't name the attribute, so a request that uses it fails with {enum:read_error.bad_encoding}. Read a specific attribute with {class:request.add_specific_attribute()} and all of them with {enum:variation.group0_var254}")? + .push("group0", "Device Attributes - Specific attribute (variations 1 to 253 and 255). Only reported in {struct:header_info}: it can't name the attribute, so a request that uses it fails with {enum:read_error.bad_encoding}. Read a specific attribute with {class:read_request.add_specific_attribute()} and all of them with {enum:variation.group0_var254}")? .push("group0_var254", "Device Attributes - All attributes request")? .push("group1_var0", "Binary Input - Any variation")? .push("group1_var1", "Binary Input - Packed format")? diff --git a/guide/docs/api/master/association_polls.mdx b/guide/docs/api/master/association_polls.mdx index c090c2ee..d59af31b 100644 --- a/guide/docs/api/master/association_polls.mdx +++ b/guide/docs/api/master/association_polls.mdx @@ -17,14 +17,17 @@ may need only the occasional integrity poll. ## Read requests -Polls and one-time reads both take a request that says what to read. It's a `ReadRequest` in Rust and a `Request` in the -bindings, and it can ask for: +Polls and one-time reads both take a `ReadRequest` that says what to read. It can ask for: * Classes (any of 0, 1, 2, 3) * A range of points of a variation * All the points of a variation +* A limited count of a variation * [Device attributes](./attributes.mdx) +A `ReadRequest` holds only what a READ can carry. Requests that freeze or write objects are a `Request`, sent with +`send_and_expect_empty_response`. + ## Polls Add a poll to an association with the request and the period. You usually add polls before calling From 1fb64e80e963b2e8bec706c3713a6e7f4d2a0922 Mon Sep 17 00:00:00 2001 From: jadamcrain Date: Thu, 26 Nov 2026 15:17:22 -0800 Subject: [PATCH 2/5] Build ReadRequest from an empty request in Rust and the bindings ReadRequest gets new() and add_classes, and loses its single-header constructors; the FFI read_request class has a constructor and add methods instead of static constructors. --- .../src/master/association/scheduler_tests.rs | 4 +- dnp3/src/master/builder.rs | 2 +- dnp3/src/master/poll.rs | 2 +- dnp3/src/master/request.rs | 241 +++++++----------- dnp3/src/master/tasks/mod.rs | 4 +- dnp3/src/master/tests/controls.rs | 4 +- dnp3/src/master/tests/link_frames.rs | 2 +- dnp3/src/master/tests/outcomes.rs | 23 +- dnp3/src/master/tests/read_errors.rs | 10 +- dnp3/src/master/tests/read_types.rs | 6 +- dnp3/src/master/tests/scheduling.rs | 8 +- dnp3/src/master/tests/shared_link.rs | 8 +- dnp3/src/master/tests/startup.rs | 7 +- dnp3/src/master/tests/time_sync.rs | 2 +- dnp3/src/no_panic_check/encode.rs | 21 +- dnp3/src/udp/lifecycle_tests.rs | 2 +- examples/master/src/main.rs | 17 +- ffi/bindings/c/master_example.c | 18 +- ffi/bindings/c/master_example.cpp | 18 +- ffi/bindings/c/smoke_test.c | 3 +- ffi/bindings/c/smoke_test.cpp | 3 +- ffi/bindings/dotnet/dnp3-tests/SmokeTest.cs | 4 +- .../dotnet/examples/master/Program.cs | 19 +- .../io/stepfunc/dnp3/tests/SmokeTest.java | 4 +- .../stepfunc/dnp3/examples/MasterExample.java | 23 +- ffi/dnp3-ffi/src/request.rs | 91 ++----- ffi/dnp3-schema/src/master/request.rs | 47 ++-- 27 files changed, 253 insertions(+), 340 deletions(-) diff --git a/dnp3/src/master/association/scheduler_tests.rs b/dnp3/src/master/association/scheduler_tests.rs index 45abcd97..36d9bdef 100644 --- a/dnp3/src/master/association/scheduler_tests.rs +++ b/dnp3/src/master/association/scheduler_tests.rs @@ -773,7 +773,7 @@ impl System { fn queue_request(&mut self, index: usize) { let (promise, reply) = Promise::one_shot(); - let task = SingleReadTask::new(ReadRequest::class_scan(Classes::all()), promise); + let task = SingleReadTask::new(ReadRequest::new().add_classes(Classes::all()), promise); self.association(index) .process_message(AssociationMsgType::QueueTask(Task::from(task).into()), true); self.requests.push(reply); @@ -927,7 +927,7 @@ async fn apply( let id = system .association(index) .polls - .add(ReadRequest::class_scan(Classes::all()), period); + .add(ReadRequest::new().add_classes(Classes::all()), period); system.polls[index].push(id); } } diff --git a/dnp3/src/master/builder.rs b/dnp3/src/master/builder.rs index 984ba069..af70c960 100644 --- a/dnp3/src/master/builder.rs +++ b/dnp3/src/master/builder.rs @@ -571,7 +571,7 @@ mod tests { let mut association = add_stream_association(&mut builder, address).unwrap(); let mut poll = association.add_poll( - ReadRequest::class_scan(crate::master::Classes::all()), + ReadRequest::new().add_classes(crate::master::Classes::all()), Duration::from_secs(5), ); let handle = association.into_handle(); diff --git a/dnp3/src/master/poll.rs b/dnp3/src/master/poll.rs index ffb3996a..3d3d216a 100644 --- a/dnp3/src/master/poll.rs +++ b/dnp3/src/master/poll.rs @@ -270,7 +270,7 @@ mod tests { use crate::master::Classes; fn request() -> ReadRequest { - ReadRequest::class_scan(Classes::all()) + ReadRequest::new().add_classes(Classes::all()) } #[test] diff --git a/dnp3/src/master/request.rs b/dnp3/src/master/request.rs index 251f22d1..82d26f5a 100644 --- a/dnp3/src/master/request.rs +++ b/dnp3/src/master/request.rs @@ -267,13 +267,27 @@ impl Classes { .into_iter() .filter_map(|(enabled, variation)| enabled.then_some(variation)) } + + fn read_headers(self) -> impl Iterator { + self.variations() + .map(|variation| ReadHeader::AllObjects { variation }) + } } /// The object headers of a READ, for one-time reads and polls /// /// Only headers that are valid in a READ can be added. A request that also writes or freezes -/// objects is a [`Request`]. -#[derive(Clone, Debug)] +/// objects is a [`Request`]. Each `add_*` method consumes the request and returns it, so calls +/// chain: +/// +/// ``` +/// # use dnp3::app::Variation; +/// # use dnp3::master::{Classes, ReadRequest}; +/// let request = ReadRequest::new() +/// .add_classes(Classes::class123()) +/// .add_all_objects(Variation::Group40Var0); +/// ``` +#[derive(Clone, Debug, Default)] pub struct ReadRequest { inner: ReadInner, } @@ -286,48 +300,29 @@ enum ReadInner { Multiple(Vec), } -impl ReadRequest { - /// Read the specified classes: events in classes 1, 2 and 3, then class 0 - pub fn class_scan(classes: Classes) -> Self { - Self::from_inner(ReadInner::ClassScan(classes)) - } - - /// Read every object of a variation, with an all objects header (0x06) - pub fn all_objects(variation: Variation) -> Self { - Self::single(ReadHeader::AllObjects { variation }) - } - - /// Read a range of a variation, with an 8-bit start/stop header (0x00) - pub fn one_byte_range(variation: Variation, start: u8, stop: u8) -> Self { - Self::single(ReadHeader::Range8 { - variation, - start, - stop, - }) - } - - /// Read a range of a variation, with a 16-bit start/stop header (0x01) - pub fn two_byte_range(variation: Variation, start: u16, stop: u16) -> Self { - Self::single(ReadHeader::Range16 { - variation, - start, - stop, - }) - } - - /// Read up to `count` objects of a variation, with an 8-bit limited count header (0x07) - pub fn one_byte_limited_count(variation: Variation, count: u8) -> Self { - Self::single(ReadHeader::LimitedCount8 { variation, count }) +impl Default for ReadInner { + fn default() -> Self { + ReadInner::Multiple(Vec::new()) } +} - /// Read up to `count` objects of a variation, with a 16-bit limited count header (0x08) - pub fn two_byte_limited_count(variation: Variation, count: u16) -> Self { - Self::single(ReadHeader::LimitedCount16 { variation, count }) +impl ReadRequest { + /// Construct a request with no headers + pub fn new() -> Self { + Default::default() } - /// Read a device attribute (group 0) of a set - pub fn device_attribute>(variation: T, set: AttrSet) -> Self { - Self::single(ReadHeader::device_attribute(variation.into(), set)) + /// Add headers for the specified classes: events in classes 1, 2 and 3, then class 0 + pub fn add_classes(self, classes: Classes) -> Self { + let inner = match self.inner { + ReadInner::Multiple(headers) if headers.is_empty() => ReadInner::ClassScan(classes), + inner => { + let mut headers = inner.into_headers(); + headers.extend(classes.read_headers()); + ReadInner::Multiple(headers) + } + }; + Self { inner } } /// Add an all objects header (0x06) with the specified variation @@ -387,25 +382,26 @@ impl ReadRequest { Ok(()) } - fn single(header: ReadHeader) -> Self { - Self::from_inner(ReadInner::Single(header)) - } - - fn from_inner(inner: ReadInner) -> Self { + fn add(self, header: ReadHeader) -> Self { + let inner = match self.inner { + ReadInner::Multiple(headers) if headers.is_empty() => ReadInner::Single(header), + inner => { + let mut headers = inner.into_headers(); + headers.push(header); + ReadInner::Multiple(headers) + } + }; Self { inner } } +} - fn add(self, header: ReadHeader) -> Self { - let mut headers = match self.inner { - ReadInner::Single(first) => vec![first], - ReadInner::ClassScan(classes) => classes - .variations() - .map(|variation| ReadHeader::AllObjects { variation }) - .collect(), +impl ReadInner { + fn into_headers(self) -> Vec { + match self { + ReadInner::Single(header) => vec![header], + ReadInner::ClassScan(classes) => classes.read_headers().collect(), ReadInner::Multiple(headers) => headers, - }; - headers.push(header); - Self::from_inner(ReadInner::Multiple(headers)) + } } } @@ -1207,13 +1203,13 @@ mod tests { const G0V0: Variation = Variation::Group0(0); let expected: Result<(), TaskErrorKind> = Err(BadEncoding::UndefinedVariation(G0V0).into()); - let valid = || ReadRequest::all_objects(Variation::Group60Var1); + let valid = || ReadRequest::new().add_all_objects(Variation::Group60Var1); for request in [ - ReadRequest::all_objects(G0V0), - ReadRequest::one_byte_range(G0V0, 1, 2), - ReadRequest::two_byte_range(G0V0, 1, 2), - ReadRequest::one_byte_limited_count(G0V0, 1), - ReadRequest::two_byte_limited_count(G0V0, 1), + ReadRequest::new().add_all_objects(G0V0), + ReadRequest::new().add_range_8(G0V0, 1, 2), + ReadRequest::new().add_range_16(G0V0, 1, 2), + ReadRequest::new().add_one_byte_limited_count(G0V0, 1), + ReadRequest::new().add_two_byte_limited_count(G0V0, 1), valid().add_all_objects(G0V0), valid().add_range_8(G0V0, 1, 2), valid().add_range_16(G0V0, 1, 2), @@ -1263,8 +1259,8 @@ mod tests { //! it doesn't, and rarely g0v0, in any header position, with groups 0, 110 and 111 no more //! likely than the others; one and two-byte ranges, with single indices and the ends more //! likely; one and two-byte counts, with 0, 1, 255 and the maximum more likely; READ - //! requests built from a single header, a class scan of any classes or a device attribute - //! read, then up to five headers or device attribute reads added to it; a `Request` of up + //! requests of up to six headers, device attribute reads and class scans of any classes, + //! added in any order to an empty request; a `Request` of up //! to five READ headers and g50v2 freeze times, with a time and interval of 0 or any value. //! //! Not generated: a group and variation that isn't a `Variation`, attribute headers in a @@ -1355,35 +1351,23 @@ mod tests { (variation.to_group_and_var(), qualifier) } - /// How a generated READ request starts: a single header, a device attribute or classes - #[derive(Clone, Debug)] - enum Start { - Read(ReadOp), - Classes(Classes), - } - - /// A header that a READ request starts with or adds + /// A header, or the headers for classes, that a READ request adds #[derive(Clone, Copy, Debug)] enum ReadOp { Header(ReadHeader), /// the variation and set of a device attribute read DeviceAttribute(u8, u8), + Classes(Classes), } - fn model_op(op: ReadOp) -> ModelHeader { + fn model_op(op: ReadOp) -> Vec { match op { - ReadOp::Header(header) => model_header(header), + ReadOp::Header(header) => vec![model_header(header)], ReadOp::DeviceAttribute(variation, set) => { - ((0, variation), Qualifier::Range8(set, set)) + vec![((0, variation), Qualifier::Range8(set, set))] } - } - } - - fn model_request(start: &Start, ops: &[ReadOp]) -> Vec { - let first: Vec = match start { - Start::Read(op) => vec![model_op(*op)], // the event classes first, then class 0 - Start::Classes(classes) => [ + ReadOp::Classes(classes) => [ (classes.events.class1, (60, 2)), (classes.events.class2, (60, 3)), (classes.events.class3, (60, 4)), @@ -1393,64 +1377,41 @@ mod tests { .filter(|(enabled, _)| *enabled) .map(|(_, group_var)| (group_var, Qualifier::AllObjects)) .collect(), - }; - first - .into_iter() - .chain(ops.iter().copied().map(model_op)) - .collect() + } } - /// the request built through the public constructor and add method for each header - fn build_request(start: &Start, ops: &[ReadOp]) -> ReadRequest { - let first = match *start { - Start::Classes(classes) => ReadRequest::class_scan(classes), - Start::Read(ReadOp::DeviceAttribute(variation, set)) => { - ReadRequest::device_attribute(variation, AttrSet::new(set)) - } - Start::Read(ReadOp::Header(header)) => match header { - ReadHeader::Range8 { + fn model_request(ops: &[ReadOp]) -> Vec { + ops.iter().copied().flat_map(model_op).collect() + } + + /// the request built through the public add method for each op + fn build_request(ops: &[ReadOp]) -> ReadRequest { + ops.iter() + .fold(ReadRequest::new(), |request, op| match *op { + ReadOp::Classes(classes) => request.add_classes(classes), + ReadOp::DeviceAttribute(variation, set) => { + request.add_device_attribute(variation, AttrSet::new(set)) + } + ReadOp::Header(ReadHeader::Range8 { variation, start, stop, - } => ReadRequest::one_byte_range(variation, start, stop), - ReadHeader::Range16 { + }) => request.add_range_8(variation, start, stop), + ReadOp::Header(ReadHeader::Range16 { variation, start, stop, - } => ReadRequest::two_byte_range(variation, start, stop), - ReadHeader::AllObjects { variation } => ReadRequest::all_objects(variation), - ReadHeader::LimitedCount8 { variation, count } => { - ReadRequest::one_byte_limited_count(variation, count) + }) => request.add_range_16(variation, start, stop), + ReadOp::Header(ReadHeader::AllObjects { variation }) => { + request.add_all_objects(variation) } - ReadHeader::LimitedCount16 { variation, count } => { - ReadRequest::two_byte_limited_count(variation, count) + ReadOp::Header(ReadHeader::LimitedCount8 { variation, count }) => { + request.add_one_byte_limited_count(variation, count) } - }, - }; - ops.iter().fold(first, |request, op| match *op { - ReadOp::DeviceAttribute(variation, set) => { - request.add_device_attribute(variation, AttrSet::new(set)) - } - ReadOp::Header(ReadHeader::Range8 { - variation, - start, - stop, - }) => request.add_range_8(variation, start, stop), - ReadOp::Header(ReadHeader::Range16 { - variation, - start, - stop, - }) => request.add_range_16(variation, start, stop), - ReadOp::Header(ReadHeader::AllObjects { variation }) => { - request.add_all_objects(variation) - } - ReadOp::Header(ReadHeader::LimitedCount8 { variation, count }) => { - request.add_one_byte_limited_count(variation, count) - } - ReadOp::Header(ReadHeader::LimitedCount16 { variation, count }) => { - request.add_two_byte_limited_count(variation, count) - } - }) + ReadOp::Header(ReadHeader::LimitedCount16 { variation, count }) => { + request.add_two_byte_limited_count(variation, count) + } + }) } fn model_bytes(&((group, var), qualifier): &ModelHeader) -> Vec { @@ -1583,20 +1544,13 @@ mod tests { fn read_op() -> impl Strategy { prop_oneof![ - 3 => read_header().prop_map(ReadOp::Header), + 4 => read_header().prop_map(ReadOp::Header), 1 => (count(vec![0, 254, 255]), any::()) .prop_map(|(variation, set)| ReadOp::DeviceAttribute(variation, set)), - ] - } - - fn read_request() -> impl Strategy)> { - let start = prop_oneof![ - 2 => read_op().prop_map(Start::Read), 1 => any::<[bool; 4]>().prop_map(|[class0, class1, class2, class3]| { - Start::Classes(Classes::new(class0, EventClasses::new(class1, class2, class3))) + ReadOp::Classes(Classes::new(class0, EventClasses::new(class1, class2, class3))) }), - ]; - (start, prop::collection::vec(read_op(), 0..6)) + ] } #[derive(Clone, Debug)] @@ -1661,7 +1615,8 @@ mod tests { let mut buffer = [0; 16]; let mut cursor = WriteCursor::new(&mut buffer); assert_eq!( - ReadRequest::device_attribute(0u8, AttrSet::Private(7)) + ReadRequest::new() + .add_device_attribute(0u8, AttrSet::Private(7)) .format(&mut HeaderWriter::new(&mut cursor)), Err(BadEncoding::UndefinedVariation(Variation::Group0(0)).into()) ); @@ -1676,12 +1631,12 @@ mod tests { /// variation with that qualifier. A request with a header for g0v0 in any position, /// which names no object, fails and writes nothing #[test] - fn read_requests_parse_to_the_headers_written((start, ops) in read_request()) { - let request = build_request(&start, &ops); + fn read_requests_parse_to_the_headers_written(ops in prop::collection::vec(read_op(), 0..7)) { + let request = build_request(&ops); let mut buffer = [0; 256]; let mut cursor = WriteCursor::new(&mut buffer); let result = request.format(&mut HeaderWriter::new(&mut cursor)); - let model = model_request(&start, &ops); + let model = model_request(&ops); if model.iter().any(|(group_var, _)| *group_var == (0, 0)) { prop_assert_eq!( result, diff --git a/dnp3/src/master/tasks/mod.rs b/dnp3/src/master/tasks/mod.rs index d089d174..a6be326d 100644 --- a/dnp3/src/master/tasks/mod.rs +++ b/dnp3/src/master/tasks/mod.rs @@ -696,12 +696,12 @@ mod test { ReadTask::StartupIntegrity(Classes::all()), ReadTask::PeriodicPoll(Poll::new( 0, - ReadRequest::class_scan(Classes::class123()), + ReadRequest::new().add_classes(Classes::class123()), Duration::from_secs(1), )), ReadTask::EventScan(EventClasses::all()), ReadTask::SingleRead(SingleReadTask::new( - ReadRequest::class_scan(Classes::all()), + ReadRequest::new().add_classes(Classes::all()), Promise::null(), )), ] diff --git a/dnp3/src/master/tests/controls.rs b/dnp3/src/master/tests/controls.rs index ccfcd5b2..16ec2dc0 100644 --- a/dnp3/src/master/tests/controls.rs +++ b/dnp3/src/master/tests/controls.rs @@ -139,7 +139,7 @@ async fn operate_no_ack_does_not_delay_the_next_task() { let mut association = harness.association.clone(); let read = tokio::spawn(async move { association - .read(ReadRequest::class_scan(Classes::class0())) + .read(ReadRequest::new().add_classes(Classes::class0())) .await }); harness @@ -185,7 +185,7 @@ async fn queued_tasks_run_back_to_back_after_operate_no_ack_and_ignore_its_seque harness .association .send_task(SingleReadTask::new( - ReadRequest::class_scan(Classes::class0()), + ReadRequest::new().add_classes(Classes::class0()), promise, )) .await diff --git a/dnp3/src/master/tests/link_frames.rs b/dnp3/src/master/tests/link_frames.rs index a437673d..b04dc49c 100644 --- a/dnp3/src/master/tests/link_frames.rs +++ b/dnp3/src/master/tests/link_frames.rs @@ -164,7 +164,7 @@ impl Kind { let result = match self { Kind::Read => { association - .read(ReadRequest::class_scan(Classes::class0())) + .read(ReadRequest::new().add_classes(Classes::class0())) .await } Kind::NonRead => association.cold_restart().await.map(|_| ()), diff --git a/dnp3/src/master/tests/outcomes.rs b/dnp3/src/master/tests/outcomes.rs index b3303f14..6a4d9ee6 100644 --- a/dnp3/src/master/tests/outcomes.rs +++ b/dnp3/src/master/tests/outcomes.rs @@ -132,7 +132,7 @@ impl Kind { match self { Kind::Read => Reply::Read( association - .read(ReadRequest::class_scan(Classes::class0())) + .read(ReadRequest::new().add_classes(Classes::class0())) .await, ), Kind::DirectOperate => Reply::Command( @@ -796,7 +796,7 @@ async fn every_task_fails_with_a_link_error_when_the_connection_drops() { .harness .association .send_task(SingleReadTask::new( - ReadRequest::class_scan(Classes::class0()), + ReadRequest::new().add_classes(Classes::class0()), promise, )) .await @@ -862,7 +862,7 @@ async fn running_and_queued_tasks_complete_their_promises_on_shutdown() { harness .association .send_task(SingleReadTask::new( - ReadRequest::class_scan(Classes::class0()), + ReadRequest::new().add_classes(Classes::class0()), promise, )) .await @@ -953,7 +953,7 @@ async fn queued_tasks_fail_with_no_such_association_when_the_association_is_remo harness .association .send_task(SingleReadTask::new( - ReadRequest::class_scan(Classes::class0()), + ReadRequest::new().add_classes(Classes::class0()), promise, )) .await @@ -1066,7 +1066,7 @@ async fn requests_to_a_removed_association_fail_with_no_such_association() { } let poll = stale .add_poll( - ReadRequest::class_scan(Classes::class0()), + ReadRequest::new().add_classes(Classes::class0()), Duration::from_secs(1), ) .await; @@ -1093,7 +1093,9 @@ async fn requests_to_a_removed_association_fail_with_no_such_association() { .unwrap(); harness.set_source(OTHER); let read = tokio::spawn(async move { - other.read(ReadRequest::class_scan(Classes::class0())).await + other + .read(ReadRequest::new().add_classes(Classes::class0())) + .await }); next_request(&mut harness, 0, FunctionCode::Read).await; respond(&mut harness, empty_response(Sequence::new(0))).await; @@ -1376,7 +1378,7 @@ async fn read_callbacks_and_sequence_numbers_follow_the_fragments_in_order() { let read = tokio::spawn(async move { association - .read(ReadRequest::class_scan(Classes::class0())) + .read(ReadRequest::new().add_classes(Classes::class0())) .await }); next_request(&mut harness, 0, FunctionCode::Read).await; @@ -1616,7 +1618,7 @@ async fn reading_group0_var0_sends_nothing() { assert_eq!( harness .association - .read(ReadRequest::all_objects(g0v0)) + .read(ReadRequest::new().add_all_objects(g0v0)) .await, Err(err) ); @@ -1636,7 +1638,10 @@ async fn reading_group0_var0_sends_nothing() { let mut poll = harness .association - .add_poll(ReadRequest::all_objects(g0v0), Duration::from_secs(3600)) + .add_poll( + ReadRequest::new().add_all_objects(g0v0), + Duration::from_secs(3600), + ) .await .unwrap(); harness.assoc_events.pop(); diff --git a/dnp3/src/master/tests/read_errors.rs b/dnp3/src/master/tests/read_errors.rs index 9ca06ffc..9c636b24 100644 --- a/dnp3/src/master/tests/read_errors.rs +++ b/dnp3/src/master/tests/read_errors.rs @@ -54,7 +54,7 @@ async fn read_with_iin2_and_data_delivers_the_data_and_succeeds() { let mut association = harness.association.clone(); let read = tokio::spawn(async move { association - .read(ReadRequest::class_scan(Classes::class0())) + .read(ReadRequest::new().add_classes(Classes::class0())) .await }); @@ -90,7 +90,7 @@ async fn read_with_iin2_and_no_data_fails() { let mut association = harness.association.clone(); let read = tokio::spawn(async move { association - .read(ReadRequest::class_scan(Classes::class0())) + .read(ReadRequest::new().add_classes(Classes::class0())) .await }); @@ -123,7 +123,7 @@ async fn multi_fragment_read_with_iin2_in_the_first_fragment_reads_every_fragmen let mut association = harness.association.clone(); let read = tokio::spawn(async move { association - .read(ReadRequest::class_scan(Classes::class0())) + .read(ReadRequest::new().add_classes(Classes::class0())) .await }); @@ -160,7 +160,7 @@ async fn start_read( let mut association = harness.association.clone(); let read = tokio::spawn(async move { association - .read(ReadRequest::class_scan(Classes::class0())) + .read(ReadRequest::new().add_classes(Classes::class0())) .await }); harness @@ -262,7 +262,7 @@ async fn periodic_poll_with_iin2_and_no_data_fails() { let mut association = harness.association.clone(); let _poll = association .add_poll( - ReadRequest::class_scan(Classes::class0()), + ReadRequest::new().add_classes(Classes::class0()), std::time::Duration::from_secs(1), ) .await diff --git a/dnp3/src/master/tests/read_types.rs b/dnp3/src/master/tests/read_types.rs index f4bebe3d..1e1c33b0 100644 --- a/dnp3/src/master/tests/read_types.rs +++ b/dnp3/src/master/tests/read_types.rs @@ -114,7 +114,7 @@ async fn periodic_poll_reports_periodic_poll() { let mut association = harness.association.clone(); let _poll = association .add_poll( - ReadRequest::class_scan(Classes::class0()), + ReadRequest::new().add_classes(Classes::class0()), std::time::Duration::from_secs(1), ) .await @@ -146,7 +146,7 @@ async fn single_read_reports_single_poll() { let mut association = harness.association.clone(); let read = tokio::spawn(async move { association - .read(ReadRequest::class_scan(Classes::class0())) + .read(ReadRequest::new().add_classes(Classes::class0())) .await }); harness @@ -179,7 +179,7 @@ async fn single_read_with_custom_handler_reports_single_poll_to_that_handler_onl let read = tokio::spawn(async move { association .read_with_handler( - ReadRequest::class_scan(Classes::class0()), + ReadRequest::new().add_classes(Classes::class0()), Box::new(handler), ) .await diff --git a/dnp3/src/master/tests/scheduling.rs b/dnp3/src/master/tests/scheduling.rs index c0d3fe70..79626b1b 100644 --- a/dnp3/src/master/tests/scheduling.rs +++ b/dnp3/src/master/tests/scheduling.rs @@ -231,7 +231,11 @@ fn spawn_read( classes: Classes, ) -> JoinHandle> { let mut association = association.clone(); - tokio::spawn(async move { association.read(ReadRequest::class_scan(classes)).await }) + tokio::spawn(async move { + association + .read(ReadRequest::new().add_classes(classes)) + .await + }) } async fn add_poll( @@ -240,7 +244,7 @@ async fn add_poll( period: Duration, ) -> PollHandle { association - .add_poll(ReadRequest::class_scan(classes), period) + .add_poll(ReadRequest::new().add_classes(classes), period) .await .unwrap() } diff --git a/dnp3/src/master/tests/shared_link.rs b/dnp3/src/master/tests/shared_link.rs index 039ee8ea..4c481cf4 100644 --- a/dnp3/src/master/tests/shared_link.rs +++ b/dnp3/src/master/tests/shared_link.rs @@ -65,7 +65,11 @@ async fn response_from_another_outstation_during_any_task_refreshes_its_own_keep let task = tokio::spawn(async move { match kind { Kind::NonRead => other.cold_restart().await.map(|_| ()), - Kind::Read => other.read(ReadRequest::class_scan(Classes::class0())).await, + Kind::Read => { + other + .read(ReadRequest::new().add_classes(Classes::class0())) + .await + } Kind::LinkStatus => other.check_link_status().await, } }); @@ -87,7 +91,7 @@ async fn response_from_another_outstation_during_any_task_refreshes_its_own_keep let mut association = harness.association.clone(); let read = tokio::spawn(async move { association - .read(ReadRequest::class_scan(Classes::class0())) + .read(ReadRequest::new().add_classes(Classes::class0())) .await }); harness diff --git a/dnp3/src/master/tests/startup.rs b/dnp3/src/master/tests/startup.rs index 99cca33c..0c56ea5c 100644 --- a/dnp3/src/master/tests/startup.rs +++ b/dnp3/src/master/tests/startup.rs @@ -343,8 +343,11 @@ async fn detect_restart_in_read_response() { // Spawn a task that sends an integrity scan let mut assoc = harness.association.clone(); - let read_task = - tokio::spawn(async move { assoc.read(ReadRequest::class_scan(Classes::all())).await }); + let read_task = tokio::spawn(async move { + assoc + .read(ReadRequest::new().add_classes(Classes::all())) + .await + }); // expect the integrity scan and respond with DEVICE_RESTART harness diff --git a/dnp3/src/master/tests/time_sync.rs b/dnp3/src/master/tests/time_sync.rs index 348a4aa2..33a7419e 100644 --- a/dnp3/src/master/tests/time_sync.rs +++ b/dnp3/src/master/tests/time_sync.rs @@ -685,7 +685,7 @@ fn class_3() -> Classes { async fn add_class_3_poll(harness: &mut TestHarness, period: Duration) -> PollHandle { harness .association - .add_poll(ReadRequest::class_scan(class_3()), period) + .add_poll(ReadRequest::new().add_classes(class_3()), period) .await .unwrap() } diff --git a/dnp3/src/no_panic_check/encode.rs b/dnp3/src/no_panic_check/encode.rs index 4402b38a..fa7e3f22 100644 --- a/dnp3/src/no_panic_check/encode.rs +++ b/dnp3/src/no_panic_check/encode.rs @@ -228,20 +228,6 @@ fn variation(source: &mut Source) -> Variation { Variation::lookup(source.u8(), source.u8()).unwrap_or(Variation::Group0(0)) } -/// a request of one header, a device attribute read or a class scan -fn read_start(source: &mut Source) -> ReadRequest { - let variation = variation(source); - match source.u8() % 7 { - 0 => ReadRequest::one_byte_range(variation, source.u8(), source.u8()), - 1 => ReadRequest::two_byte_range(variation, source.u16(), source.u16()), - 2 => ReadRequest::all_objects(variation), - 3 => ReadRequest::one_byte_limited_count(variation, source.u8()), - 4 => ReadRequest::two_byte_limited_count(variation, source.u16()), - 5 => ReadRequest::device_attribute(source.u8(), AttrSet::new(source.u8())), - _ => ReadRequest::class_scan(classes(source)), - } -} - fn event_classes(source: &mut Source) -> EventClasses { EventClasses::new(source.bool(), source.bool(), source.bool()) } @@ -252,15 +238,16 @@ fn classes(source: &mut Source) -> Classes { fn read(source: &mut Source) -> ReadRequest { let len = source.len(); - (0..len).fold(read_start(source), |request, _| { + (0..len).fold(ReadRequest::new(), |request, _| { let variation = variation(source); - match source.u8() % 6 { + match source.u8() % 7 { 0 => request.add_all_objects(variation), 1 => request.add_range_8(variation, source.u8(), source.u8()), 2 => request.add_range_16(variation, source.u16(), source.u16()), 3 => request.add_one_byte_limited_count(variation, source.u8()), 4 => request.add_two_byte_limited_count(variation, source.u16()), - _ => request.add_device_attribute(source.u8(), AttrSet::new(source.u8())), + 5 => request.add_device_attribute(source.u8(), AttrSet::new(source.u8())), + _ => request.add_classes(classes(source)), } }) } diff --git a/dnp3/src/udp/lifecycle_tests.rs b/dnp3/src/udp/lifecycle_tests.rs index c0cfe64b..aa6ace6d 100644 --- a/dnp3/src/udp/lifecycle_tests.rs +++ b/dnp3/src/udp/lifecycle_tests.rs @@ -394,7 +394,7 @@ async fn spawn_associated_master( } fn class0_read() -> ReadRequest { - ReadRequest::class_scan(Classes::class0()) + ReadRequest::new().add_classes(Classes::class0()) } #[tokio::test] diff --git a/examples/master/src/main.rs b/examples/master/src/main.rs index 8bb0670f..ee4d4384 100644 --- a/examples/master/src/main.rs +++ b/examples/master/src/main.rs @@ -66,7 +66,7 @@ async fn main() -> Result<(), Box> { // ANCHOR: add_poll let poll = association .add_poll( - ReadRequest::class_scan(Classes::class123()), + ReadRequest::new().add_classes(Classes::class123()), Duration::from_secs(5), ) .await?; @@ -453,13 +453,14 @@ impl CliHandler { } "rao" => { self.association - .read(ReadRequest::all_objects(Variation::Group40Var0)) + .read(ReadRequest::new().add_all_objects(Variation::Group40Var0)) .await?; } "rmo" => { self.association .read( - ReadRequest::all_objects(Variation::Group10Var0) + ReadRequest::new() + .add_all_objects(Variation::Group10Var0) .add_all_objects(Variation::Group40Var0), ) .await?; @@ -467,7 +468,8 @@ impl CliHandler { "rco" => { self.association .read( - ReadRequest::all_objects(Variation::Group20Var0) + ReadRequest::new() + .add_all_objects(Variation::Group20Var0) .add_all_objects(Variation::Group21Var0), ) .await?; @@ -548,10 +550,7 @@ impl CliHandler { "rda" => { // ANCHOR: read_attributes self.association - .read(ReadRequest::device_attribute( - AllAttributes, - AttrSet::Default, - )) + .read(ReadRequest::new().add_device_attribute(AllAttributes, AttrSet::Default)) .await?; // ANCHOR_END: read_attributes } @@ -567,7 +566,7 @@ impl CliHandler { } "ral" => { self.association - .read(ReadRequest::device_attribute( + .read(ReadRequest::new().add_device_attribute( VariationListAttr::ListOfVariations, AttrSet::Default, )) diff --git a/ffi/bindings/c/master_example.c b/ffi/bindings/c/master_example.c index 41c6fd33..64d23e2c 100644 --- a/ffi/bindings/c/master_example.c +++ b/ffi/bindings/c/master_example.c @@ -294,7 +294,8 @@ int run_channel(dnp3_master_channel_t *channel, dnp3_association_id_t associatio { // create an event poll // ANCHOR: add_poll - dnp3_read_request_t *poll_request = dnp3_read_request_new_class_scan(false, true, true, true); + dnp3_read_request_t *poll_request = dnp3_read_request_create(); + dnp3_read_request_add_classes(poll_request, false, true, true, true); dnp3_poll_id_t poll_id; dnp3_param_error_t err = dnp3_master_channel_add_poll(channel, association_id, poll_request, 5000, &poll_id); dnp3_read_request_destroy(poll_request); @@ -347,7 +348,8 @@ void run_command(dnp3_master_channel_t *channel, dnp3_association_id_t associati print_outcome("dlv", dnp3_master_channel_set_decode_level(channel, level), "success"); } else if (strcmp(cmd, "rao") == 0) { - dnp3_read_request_t *request = dnp3_read_request_new_all_objects(DNP3_VARIATION_GROUP40_VAR0); + dnp3_read_request_t *request = dnp3_read_request_create(); + dnp3_read_request_add_all_objects_header(request, DNP3_VARIATION_GROUP40_VAR0); dnp3_read_task_callback_t cb = { .on_complete = &on_read_complete, .on_failure = &on_read_failure, @@ -359,7 +361,8 @@ void run_command(dnp3_master_channel_t *channel, dnp3_association_id_t associati print_outcome("rao", err, NULL); } else if (strcmp(cmd, "rmo") == 0) { - dnp3_read_request_t *request = dnp3_read_request_new_all_objects(DNP3_VARIATION_GROUP10_VAR0); + dnp3_read_request_t *request = dnp3_read_request_create(); + dnp3_read_request_add_all_objects_header(request, DNP3_VARIATION_GROUP10_VAR0); dnp3_read_request_add_all_objects_header(request, DNP3_VARIATION_GROUP40_VAR0); dnp3_read_task_callback_t cb = { .on_complete = &on_read_complete, @@ -372,7 +375,8 @@ void run_command(dnp3_master_channel_t *channel, dnp3_association_id_t associati print_outcome("rmo", err, NULL); } else if (strcmp(cmd, "rco") == 0) { - dnp3_read_request_t *request = dnp3_read_request_new_all_objects(DNP3_VARIATION_GROUP20_VAR0); + dnp3_read_request_t *request = dnp3_read_request_create(); + dnp3_read_request_add_all_objects_header(request, DNP3_VARIATION_GROUP20_VAR0); dnp3_read_request_add_all_objects_header(request, DNP3_VARIATION_GROUP21_VAR0); dnp3_read_task_callback_t cb = { .on_complete = &on_read_complete, @@ -513,7 +517,8 @@ void run_command(dnp3_master_channel_t *channel, dnp3_association_id_t associati } else if (strcmp(cmd, "rda") == 0) { // ANCHOR: read_attributes - dnp3_read_request_t *request = dnp3_read_request_new_specific_attribute(DNP3_ATTRIBUTE_VARIATIONS_ALL_ATTRIBUTES_REQUEST, 0); + dnp3_read_request_t *request = dnp3_read_request_create(); + dnp3_read_request_add_specific_attribute(request, DNP3_ATTRIBUTE_VARIATIONS_ALL_ATTRIBUTES_REQUEST, 0); dnp3_read_task_callback_t cb = { .on_complete = &on_read_complete, @@ -545,7 +550,8 @@ void run_command(dnp3_master_channel_t *channel, dnp3_association_id_t associati print_outcome("wda", err, NULL); } else if (strcmp(cmd, "ral") == 0) { - dnp3_read_request_t *request = dnp3_read_request_new_specific_attribute(DNP3_ATTRIBUTE_VARIATIONS_LIST_OF_VARIATIONS, 0); + dnp3_read_request_t *request = dnp3_read_request_create(); + dnp3_read_request_add_specific_attribute(request, DNP3_ATTRIBUTE_VARIATIONS_LIST_OF_VARIATIONS, 0); dnp3_read_task_callback_t cb = { .on_complete = &on_read_complete, .on_failure = &on_read_failure, diff --git a/ffi/bindings/c/master_example.cpp b/ffi/bindings/c/master_example.cpp index 71e14041..43be5d03 100644 --- a/ffi/bindings/c/master_example.cpp +++ b/ffi/bindings/c/master_example.cpp @@ -226,7 +226,8 @@ void run_channel(dnp3::MasterChannel &channel, dnp3::AssociationId assoc) { // create an event poll // ANCHOR: add_poll - auto event_scan = dnp3::ReadRequest::class_scan(false, true, true, true); + dnp3::ReadRequest event_scan; + event_scan.add_classes(false, true, true, true); const auto event_poll = channel.add_poll(assoc, event_scan, std::chrono::seconds(5)); // ANCHOR_END: add_poll @@ -281,16 +282,19 @@ void run_command(const std::string &cmd, dnp3::MasterChannel &channel, dnp3::Ass std::cout << "dlv: success" << std::endl; } else if (cmd == "rao") { - auto request = dnp3::ReadRequest::all_objects(dnp3::Variation::group40_var0); + dnp3::ReadRequest request; + request.add_all_objects_header(dnp3::Variation::group40_var0); channel.read(assoc, request, create_read_callback("rao")); } else if (cmd == "rmo") { - auto request = dnp3::ReadRequest::all_objects(dnp3::Variation::group10_var0); + dnp3::ReadRequest request; + request.add_all_objects_header(dnp3::Variation::group10_var0); request.add_all_objects_header(dnp3::Variation::group40_var0); channel.read(assoc, request, create_read_callback("rmo")); } else if (cmd == "rco") { - auto request = dnp3::ReadRequest::all_objects(dnp3::Variation::group20_var0); + dnp3::ReadRequest request; + request.add_all_objects_header(dnp3::Variation::group20_var0); request.add_all_objects_header(dnp3::Variation::group21_var0); channel.read(assoc, request, create_read_callback("rco")); } @@ -351,7 +355,8 @@ void run_command(const std::string &cmd, dnp3::MasterChannel &channel, dnp3::Ass } else if (cmd == "rda") { // ANCHOR: read_attributes - auto request = dnp3::ReadRequest::specific_attribute(dnp3::attribute_variations::all_attributes_request, 0); + dnp3::ReadRequest request; + request.add_specific_attribute(dnp3::attribute_variations::all_attributes_request, 0); channel.read(assoc, request, create_read_callback("rda")); // ANCHOR_END: read_attributes } @@ -363,7 +368,8 @@ void run_command(const std::string &cmd, dnp3::MasterChannel &channel, dnp3::Ass // ANCHOR_END: write_attribute } else if (cmd == "ral") { - auto request = dnp3::ReadRequest::specific_attribute(dnp3::attribute_variations::list_of_variations, 0); + dnp3::ReadRequest request; + request.add_specific_attribute(dnp3::attribute_variations::list_of_variations, 0); channel.read(assoc, request, create_read_callback("ral")); } else if (cmd == "crt") { diff --git a/ffi/bindings/c/smoke_test.c b/ffi/bindings/c/smoke_test.c index 6f210a47..df636488 100644 --- a/ffi/bindings/c/smoke_test.c +++ b/ffi/bindings/c/smoke_test.c @@ -300,7 +300,8 @@ static bool read_class0(dnp3_master_channel_t *channel, dnp3_association_id_t as .on_failure = &on_read_failure, .ctx = state, }; - dnp3_read_request_t *request = dnp3_read_request_new_class_scan(true, false, false, false); + dnp3_read_request_t *request = dnp3_read_request_create(); + dnp3_read_request_add_classes(request, true, false, false, false); dnp3_param_error_t err = dnp3_master_channel_read(channel, association, request, callback); dnp3_read_request_destroy(request); if (!check_param(err, "start the read") || !wait_for(state, &read_done, "the read")) { diff --git a/ffi/bindings/c/smoke_test.cpp b/ffi/bindings/c/smoke_test.cpp index 67bb0638..91c17242 100644 --- a/ffi/bindings/c/smoke_test.cpp +++ b/ffi/bindings/c/smoke_test.cpp @@ -286,7 +286,8 @@ void run(State &state) state.wait_for([&]() { return state.connected; }, "the master to connect"); // a class 0 read returns the outstation's values - auto request = dnp3::ReadRequest::class_scan(true, false, false, false); + dnp3::ReadRequest request; + request.add_classes(true, false, false, false); channel.read(association, request, std::make_unique(state)); state.wait_for([&]() { return state.read_result != Result::pending; }, "the read"); { diff --git a/ffi/bindings/dotnet/dnp3-tests/SmokeTest.cs b/ffi/bindings/dotnet/dnp3-tests/SmokeTest.cs index 598e0038..c3a10ce9 100644 --- a/ffi/bindings/dotnet/dnp3-tests/SmokeTest.cs +++ b/ffi/bindings/dotnet/dnp3-tests/SmokeTest.cs @@ -219,7 +219,9 @@ public async Task MasterReadsAndOperatesOutstation() await connected.Task.WaitAsync(WaitTimeout); // a class 0 read returns the outstation's values - await channel.Read(association, ReadRequest.ClassScan(true, false, false, false)).WaitAsync(WaitTimeout); + var request = new ReadRequest(); + request.AddClasses(true, false, false, false); + await channel.Read(association, request).WaitAsync(WaitTimeout); Assert.AreEqual(true, readHandler.BinaryValue); Assert.AreEqual(42.0, readHandler.AnalogValue); diff --git a/ffi/bindings/dotnet/examples/master/Program.cs b/ffi/bindings/dotnet/examples/master/Program.cs index 5fcf7308..2b01408a 100644 --- a/ffi/bindings/dotnet/examples/master/Program.cs +++ b/ffi/bindings/dotnet/examples/master/Program.cs @@ -73,7 +73,9 @@ public static async Task Main(string[] args) // create an event poll // ANCHOR: add_poll - var poll = channel.AddPoll(association, ReadRequest.ClassScan(false, true, true, true), TimeSpan.FromSeconds(5)); + var eventScan = new ReadRequest(); + eventScan.AddClasses(false, true, true, true); + var poll = channel.AddPoll(association, eventScan, TimeSpan.FromSeconds(5)); // ANCHOR_END: add_poll // enable communications @@ -237,20 +239,23 @@ private static async Task RunOneCommand(MasterChannel channel, Associati } case "rao": { - var request = ReadRequest.AllObjects(Variation.Group40Var0); + var request = new ReadRequest(); + request.AddAllObjectsHeader(Variation.Group40Var0); await channel.Read(association, request); return Success; } case "rmo": { - var request = ReadRequest.AllObjects(Variation.Group10Var0); + var request = new ReadRequest(); + request.AddAllObjectsHeader(Variation.Group10Var0); request.AddAllObjectsHeader(Variation.Group40Var0); await channel.Read(association, request); return Success; } case "rco": { - var request = ReadRequest.AllObjects(Variation.Group20Var0); + var request = new ReadRequest(); + request.AddAllObjectsHeader(Variation.Group20Var0); request.AddAllObjectsHeader(Variation.Group21Var0); await channel.Read(association, request); return Success; @@ -331,7 +336,8 @@ private static async Task RunOneCommand(MasterChannel channel, Associati case "rda": { // ANCHOR: read_attributes - var request = ReadRequest.SpecificAttribute(AttributeVariations.AllAttributesRequest, 0); + var request = new ReadRequest(); + request.AddSpecificAttribute(AttributeVariations.AllAttributesRequest, 0); await channel.Read(association, request); // ANCHOR_END: read_attributes return Success; @@ -347,7 +353,8 @@ private static async Task RunOneCommand(MasterChannel channel, Associati } case "ral": { - var request = ReadRequest.SpecificAttribute(AttributeVariations.ListOfVariations, 0); + var request = new ReadRequest(); + request.AddSpecificAttribute(AttributeVariations.ListOfVariations, 0); await channel.Read(association, request); return Success; } diff --git a/ffi/bindings/java/dnp3-tests/src/test/java/io/stepfunc/dnp3/tests/SmokeTest.java b/ffi/bindings/java/dnp3-tests/src/test/java/io/stepfunc/dnp3/tests/SmokeTest.java index 27868139..dfea62f1 100644 --- a/ffi/bindings/java/dnp3-tests/src/test/java/io/stepfunc/dnp3/tests/SmokeTest.java +++ b/ffi/bindings/java/dnp3-tests/src/test/java/io/stepfunc/dnp3/tests/SmokeTest.java @@ -276,8 +276,10 @@ void masterReadsAndOperatesOutstation() throws Exception { connected.get(WAIT_TIMEOUT_SECONDS, TimeUnit.SECONDS); // a class 0 read returns the outstation's values + ReadRequest request = new ReadRequest(); + request.addClasses(true, false, false, false); channel - .read(association, ReadRequest.classScan(true, false, false, false)) + .read(association, request) .toCompletableFuture() .get(WAIT_TIMEOUT_SECONDS, TimeUnit.SECONDS); assertEquals(Boolean.TRUE, readHandler.getBinaryValue()); diff --git a/ffi/bindings/java/examples/src/main/java/io/stepfunc/dnp3/examples/MasterExample.java b/ffi/bindings/java/examples/src/main/java/io/stepfunc/dnp3/examples/MasterExample.java index b7c80dd0..2b32b0ff 100644 --- a/ffi/bindings/java/examples/src/main/java/io/stepfunc/dnp3/examples/MasterExample.java +++ b/ffi/bindings/java/examples/src/main/java/io/stepfunc/dnp3/examples/MasterExample.java @@ -91,9 +91,9 @@ private static void run(Runtime runtime, String[] args) throws IOException { // create an event poll // ANCHOR: add_poll - PollId poll = - channel.addPoll( - association, ReadRequest.classScan(false, true, true, true), Duration.ofSeconds(5)); + ReadRequest eventScan = new ReadRequest(); + eventScan.addClasses(false, true, true, true); + PollId poll = channel.addPoll(association, eventScan, Duration.ofSeconds(5)); // ANCHOR_END: add_poll // enable communications @@ -297,20 +297,23 @@ private static String runOneCommand(MasterChannel channel, AssociationId associa return success; case "rao": { - ReadRequest request = ReadRequest.allObjects(Variation.GROUP40_VAR0); + ReadRequest request = new ReadRequest(); + request.addAllObjectsHeader(Variation.GROUP40_VAR0); channel.read(association, request).toCompletableFuture().get(); return success; } case "rmo": { - ReadRequest request = ReadRequest.allObjects(Variation.GROUP10_VAR0); + ReadRequest request = new ReadRequest(); + request.addAllObjectsHeader(Variation.GROUP10_VAR0); request.addAllObjectsHeader(Variation.GROUP40_VAR0); channel.read(association, request).toCompletableFuture().get(); return success; } case "rco": { - ReadRequest request = ReadRequest.allObjects(Variation.GROUP20_VAR0); + ReadRequest request = new ReadRequest(); + request.addAllObjectsHeader(Variation.GROUP20_VAR0); request.addAllObjectsHeader(Variation.GROUP21_VAR0); channel.read(association, request).toCompletableFuture().get(); return success; @@ -390,8 +393,8 @@ private static String runOneCommand(MasterChannel channel, AssociationId associa case "rda": { // ANCHOR: read_attributes - ReadRequest request = - ReadRequest.specificAttribute(AttributeVariations.ALL_ATTRIBUTES_REQUEST, ubyte(0)); + ReadRequest request = new ReadRequest(); + request.addSpecificAttribute(AttributeVariations.ALL_ATTRIBUTES_REQUEST, ubyte(0)); channel.read(association, request).toCompletableFuture().get(); // ANCHOR_END: read_attributes return success; @@ -407,8 +410,8 @@ private static String runOneCommand(MasterChannel channel, AssociationId associa } case "ral": { - ReadRequest request = - ReadRequest.specificAttribute(AttributeVariations.LIST_OF_VARIATIONS, ubyte(0)); + ReadRequest request = new ReadRequest(); + request.addSpecificAttribute(AttributeVariations.LIST_OF_VARIATIONS, ubyte(0)); channel.read(association, request).toCompletableFuture().get(); return success; } diff --git a/ffi/dnp3-ffi/src/request.rs b/ffi/dnp3-ffi/src/request.rs index 51ab8888..1888ca2d 100644 --- a/ffi/dnp3-ffi/src/request.rs +++ b/ffi/dnp3-ffi/src/request.rs @@ -20,16 +20,9 @@ impl ReadRequest { self.inner.clone() } - fn create(inner: dnp3::master::ReadRequest) -> *mut ReadRequest { - Box::into_raw(Box::new(ReadRequest { inner })) - } - /// replace the request with `f` of it, since its add methods take it by value fn update(&mut self, f: impl FnOnce(dnp3::master::ReadRequest) -> dnp3::master::ReadRequest) { - // a single header, which doesn't allocate, stands in until `f` returns - let placeholder = dnp3::master::ReadRequest::all_objects(Variation::Group60Var1); - let request = std::mem::replace(&mut self.inner, placeholder); - self.inner = f(request); + self.inner = f(std::mem::take(&mut self.inner)); } } @@ -52,71 +45,10 @@ impl Request { } } -pub unsafe fn read_request_new_class_scan( - class0: bool, - class1: bool, - class2: bool, - class3: bool, -) -> *mut ReadRequest { - ReadRequest::create(dnp3::master::ReadRequest::class_scan(Classes::new( - class0, - EventClasses::new(class1, class2, class3), - ))) -} - -pub unsafe fn read_request_new_specific_attribute(variation: u8, set: u8) -> *mut ReadRequest { - ReadRequest::create(dnp3::master::ReadRequest::device_attribute( - variation, - AttrSet::new(set), - )) -} - -pub unsafe fn read_request_new_all_objects(variation: ffi::Variation) -> *mut ReadRequest { - ReadRequest::create(dnp3::master::ReadRequest::all_objects(variation.into())) -} - -pub unsafe fn read_request_new_one_byte_range( - variation: ffi::Variation, - start: u8, - stop: u8, -) -> *mut ReadRequest { - ReadRequest::create(dnp3::master::ReadRequest::one_byte_range( - variation.into(), - start, - stop, - )) -} - -pub unsafe fn read_request_new_two_byte_range( - variation: ffi::Variation, - start: u16, - stop: u16, -) -> *mut ReadRequest { - ReadRequest::create(dnp3::master::ReadRequest::two_byte_range( - variation.into(), - start, - stop, - )) -} - -pub unsafe fn read_request_new_one_byte_limited_count( - variation: ffi::Variation, - count: u8, -) -> *mut ReadRequest { - ReadRequest::create(dnp3::master::ReadRequest::one_byte_limited_count( - variation.into(), - count, - )) -} - -pub unsafe fn read_request_new_two_byte_limited_count( - variation: ffi::Variation, - count: u16, -) -> *mut ReadRequest { - ReadRequest::create(dnp3::master::ReadRequest::two_byte_limited_count( - variation.into(), - count, - )) +pub unsafe fn read_request_create() -> *mut ReadRequest { + Box::into_raw(Box::new(ReadRequest { + inner: dnp3::master::ReadRequest::new(), + })) } pub unsafe fn read_request_destroy(request: *mut ReadRequest) { @@ -125,6 +57,19 @@ pub unsafe fn read_request_destroy(request: *mut ReadRequest) { } } +pub(crate) unsafe fn read_request_add_classes( + request: *mut ReadRequest, + class0: bool, + class1: bool, + class2: bool, + class3: bool, +) { + if let Some(request) = request.as_mut() { + let classes = Classes::new(class0, EventClasses::new(class1, class2, class3)); + request.update(|r| r.add_classes(classes)); + } +} + pub(crate) unsafe fn read_request_add_specific_attribute( request: *mut ReadRequest, variation: u8, diff --git a/ffi/dnp3-schema/src/master/request.rs b/ffi/dnp3-schema/src/master/request.rs index 0ee8a909..9aad1b08 100644 --- a/ffi/dnp3-schema/src/master/request.rs +++ b/ffi/dnp3-schema/src/master/request.rs @@ -29,37 +29,26 @@ fn define_read_request( lib: &mut LibraryBuilder, shared: &SharedDefinitions, ) -> BackTraced { - const NAME: &str = "read_request"; - let read_request = lib.declare_class(NAME)?; + let read_request = lib.declare_class("read_request")?; - let class_scan_fn = lib - .define_function("read_request_new_class_scan")? + let constructor = lib + .define_constructor(read_request.clone())? + .doc("Create a new read request with no headers")? + .build()?; + + let destructor = lib.define_destructor(read_request.clone(), "Destroy a read request")?; + + let add_classes_fn = lib + .define_method("add_classes", read_request.clone())? .param("class0", Primitive::Bool, "Ask for class 0 (static data)")? .param("class1", Primitive::Bool, "Ask for class 1 events")? .param("class2", Primitive::Bool, "Ask for class 2 events")? .param("class3", Primitive::Bool, "Ask for class 3 events")? - .returns(read_request.clone(), "Handle to the created request")? .doc( - doc("Create a new read request asking for classes") - .details("The request asks for events in classes 1, 2 and 3, then class 0."), - )? - .build_static("class_scan")?; - - let specific_attribute_fn = lib - .define_function("read_request_new_specific_attribute")? - .param( - "variation", - Primitive::U8, - "Variation of the device attribute, 1 to 255 (254 reads every attribute of the set)", + doc("Add headers asking for classes") + .details("The headers ask for events in classes 1, 2 and 3, then class 0."), )? - .param( - "set", - Primitive::U8, - "The set (point) to which the attribute belongs", - )? - .returns(read_request.clone(), "Handle to the created request")? - .doc("Create a new read request asking for a specific device attribute (group 0)")? - .build_static("specific_attribute")?; + .build()?; let add_specific_attribute_fn = lib .define_method("add_specific_attribute", read_request.clone())? @@ -76,19 +65,13 @@ fn define_read_request( .doc("Add a header that reads a specific device attribute (group 0)")? .build()?; - let destructor = lib.define_destructor(read_request.clone(), "Destroy a read request")?; - - let constructors = define_single_header_constructors(lib, shared, &read_request, NAME)?; let header_methods = define_header_methods(lib, shared, &read_request)?; let mut builder = lib .define_class(&read_request)? + .constructor(constructor)? .destructor(destructor)? - .static_method(class_scan_fn)? - .static_method(specific_attribute_fn)?; - for method in constructors { - builder = builder.static_method(method)?; - } + .method(add_classes_fn)?; for method in header_methods { builder = builder.method(method)?; } From 95142f44e86fc2679a34fa2636e966a3c4a4866e Mon Sep 17 00:00:00 2001 From: jadamcrain Date: Thu, 26 Nov 2026 17:48:23 -0800 Subject: [PATCH 3/5] Build Request from an empty request in the bindings and add add_classes The FFI request class drops its static constructors. Both request types gain add_classes, ReadRequest's empty state is explicit, and the docs say what ReadRequest does and doesn't check. --- dnp3/src/master/handler.rs | 3 + dnp3/src/master/request.rs | 60 ++++++++---- ffi/dnp3-ffi/src/request.rs | 81 ++++------------ ffi/dnp3-schema/src/master/mod.rs | 1 + ffi/dnp3-schema/src/master/request.rs | 130 +++----------------------- 5 files changed, 73 insertions(+), 202 deletions(-) diff --git a/dnp3/src/master/handler.rs b/dnp3/src/master/handler.rs index 1ddf0fe7..0c4ba503 100644 --- a/dnp3/src/master/handler.rs +++ b/dnp3/src/master/handler.rs @@ -307,6 +307,9 @@ impl AssociationHandle { /// This is useful for constructing various types of WRITE and FREEZE operations where /// an empty response is expected from the outstation, and the only indication of success /// are bits in IIN.2 + /// + /// The request is sent with whatever function code is given. Reads go through + /// [`AssociationHandle::read`] with a [`ReadRequest`], which can't carry values. pub async fn send_and_expect_empty_response( &mut self, function: FunctionCode, diff --git a/dnp3/src/master/request.rs b/dnp3/src/master/request.rs index 82d26f5a..55894e10 100644 --- a/dnp3/src/master/request.rs +++ b/dnp3/src/master/request.rs @@ -276,9 +276,12 @@ impl Classes { /// The object headers of a READ, for one-time reads and polls /// -/// Only headers that are valid in a READ can be added. A request that also writes or freezes -/// objects is a [`Request`]. Each `add_*` method consumes the request and returns it, so calls -/// chain: +/// It holds only headers that name objects without carrying values, as a READ does. A request +/// that writes or freezes objects is a [`Request`]. The variation and qualifier of each header +/// aren't checked against what an outstation accepts in a READ, so a master can test how an +/// outstation answers any read. +/// +/// Each `add_*` method consumes the request and returns it, so calls chain: /// /// ``` /// # use dnp3::app::Variation; @@ -293,19 +296,15 @@ pub struct ReadRequest { } /// Single headers and class scans don't allocate, since polls clone their request every period -#[derive(Clone, Debug)] +#[derive(Clone, Debug, Default)] enum ReadInner { + #[default] + Empty, Single(ReadHeader), ClassScan(Classes), Multiple(Vec), } -impl Default for ReadInner { - fn default() -> Self { - ReadInner::Multiple(Vec::new()) - } -} - impl ReadRequest { /// Construct a request with no headers pub fn new() -> Self { @@ -315,7 +314,7 @@ impl ReadRequest { /// Add headers for the specified classes: events in classes 1, 2 and 3, then class 0 pub fn add_classes(self, classes: Classes) -> Self { let inner = match self.inner { - ReadInner::Multiple(headers) if headers.is_empty() => ReadInner::ClassScan(classes), + ReadInner::Empty => ReadInner::ClassScan(classes), inner => { let mut headers = inner.into_headers(); headers.extend(classes.read_headers()); @@ -365,6 +364,7 @@ impl ReadRequest { pub(crate) fn format(&self, writer: &mut HeaderWriter) -> Result<(), TaskErrorKind> { match &self.inner { + ReadInner::Empty => {} ReadInner::Single(header) => { header.validate()?; header.format(writer)?; @@ -384,7 +384,7 @@ impl ReadRequest { fn add(self, header: ReadHeader) -> Self { let inner = match self.inner { - ReadInner::Multiple(headers) if headers.is_empty() => ReadInner::Single(header), + ReadInner::Empty => ReadInner::Single(header), inner => { let mut headers = inner.into_headers(); headers.push(header); @@ -398,6 +398,7 @@ impl ReadRequest { impl ReadInner { fn into_headers(self) -> Vec { match self { + ReadInner::Empty => Vec::new(), ReadInner::Single(header) => vec![header], ReadInner::ClassScan(classes) => classes.read_headers().collect(), ReadInner::Multiple(headers) => headers, @@ -427,6 +428,13 @@ impl Request { Default::default() } + /// Add headers for the specified classes: events in classes 1, 2 and 3, then class 0 + pub fn add_classes(mut self, classes: Classes) -> Self { + self.headers + .extend(classes.read_headers().map(Header::Read)); + self + } + /// Add an all objects header (0x06) with the specified variation pub fn add_all_objects(self, variation: Variation) -> Self { self.add(Header::Read(ReadHeader::AllObjects { variation })) @@ -1260,8 +1268,8 @@ mod tests { //! likely than the others; one and two-byte ranges, with single indices and the ends more //! likely; one and two-byte counts, with 0, 1, 255 and the maximum more likely; READ //! requests of up to six headers, device attribute reads and class scans of any classes, - //! added in any order to an empty request; a `Request` of up - //! to five READ headers and g50v2 freeze times, with a time and interval of 0 or any value. + //! added in any order to an empty request; a `Request` of up to five READ headers, class + //! headers and g50v2 freeze times, with a time and interval of 0 or any value. //! //! Not generated: a group and variation that isn't a `Variation`, attribute headers in a //! `Request` (see `app/attr.rs` and the attribute example above), and requests @@ -1556,6 +1564,7 @@ mod tests { #[derive(Clone, Debug)] enum Item { Read(ReadHeader), + Classes(Classes), /// the time and interval of a g50v2 Freeze(u64, u32), } @@ -1563,6 +1572,12 @@ mod tests { fn item() -> impl Strategy { prop_oneof![ read_header().prop_map(Item::Read), + any::<[bool; 4]>().prop_map(|[class0, class1, class2, class3]| { + Item::Classes(Classes::new( + class0, + EventClasses::new(class1, class2, class3), + )) + }), ( prop_oneof![Just(0), 0..=Timestamp::MAX_VALUE], prop_oneof![Just(0), any::()], @@ -1592,6 +1607,7 @@ mod tests { Item::Read(ReadHeader::LimitedCount16 { variation, count }) => { request.add_two_byte_limited_count(variation, count) } + Item::Classes(classes) => request.add_classes(classes), Item::Freeze(time, interval) => { request.add_time_and_interval(Timestamp::new(time), interval) } @@ -1631,7 +1647,9 @@ mod tests { /// variation with that qualifier. A request with a header for g0v0 in any position, /// which names no object, fails and writes nothing #[test] - fn read_requests_parse_to_the_headers_written(ops in prop::collection::vec(read_op(), 0..7)) { + fn read_requests_parse_to_the_headers_written( + ops in prop::collection::vec(read_op(), 0..7) + ) { let request = build_request(&ops); let mut buffer = [0; 256]; let mut cursor = WriteCursor::new(&mut buffer); @@ -1660,10 +1678,10 @@ mod tests { prop_assert_eq!(parse_read(written), expected); } - /// A `Request` is written as the READ-style headers and g50v2 freeze times - /// they hold, in order, and each g50v2 parses back to its time and interval. Headers - /// with a READ of g0v0 in any position fail and write nothing. Attribute headers aren't - /// generated: `app/attr.rs` tests their values, and + /// A `Request` is written as the READ-style headers, class headers and g50v2 freeze + /// times it holds, in order, and each g50v2 parses back to its time and interval. + /// Headers with a READ of g0v0 in any position fail and write nothing. Attribute + /// headers aren't generated: `app/attr.rs` tests their values, and /// `attribute_with_a_variation_that_cannot_carry_a_value_leaves_the_cursor_untouched` /// the header #[test] @@ -1689,6 +1707,10 @@ mod tests { .iter() .flat_map(|item| match *item { Item::Read(header) => model_bytes(&model_header(header)), + Item::Classes(classes) => model_op(ReadOp::Classes(classes)) + .iter() + .flat_map(model_bytes) + .collect(), Item::Freeze(time, interval) => freeze_bytes(time, interval), }) .collect(); diff --git a/ffi/dnp3-ffi/src/request.rs b/ffi/dnp3-ffi/src/request.rs index 1888ca2d..5a7d225a 100644 --- a/ffi/dnp3-ffi/src/request.rs +++ b/ffi/dnp3-ffi/src/request.rs @@ -5,7 +5,7 @@ // Directive (EU) 2019/790 Art. 4(3), subject to LICENSE.txt Section 3.3. use dnp3::app::attr::*; -use dnp3::app::{Timestamp, Variation}; +use dnp3::app::Timestamp; use dnp3::master::{Classes, EventClasses}; use std::ffi::CStr; @@ -35,10 +35,6 @@ impl Request { self.inner.clone() } - fn create(inner: dnp3::master::Request) -> *mut Request { - Box::into_raw(Box::new(Request { inner })) - } - /// replace the request with `f` of it, since its add methods take it by value fn update(&mut self, f: impl FnOnce(dnp3::master::Request) -> dnp3::master::Request) { self.inner = f(std::mem::take(&mut self.inner)); @@ -132,72 +128,27 @@ pub(crate) unsafe fn read_request_add_two_byte_limited_count_header( } pub unsafe fn request_create() -> *mut Request { - Request::create(dnp3::master::Request::new()) + Box::into_raw(Box::new(Request { + inner: dnp3::master::Request::new(), + })) +} + +pub unsafe fn request_destroy(request: *mut Request) { + if !request.is_null() { + drop(Box::from_raw(request)); + } } -pub unsafe fn request_new_class( +pub(crate) unsafe fn request_add_classes( + request: *mut Request, class0: bool, class1: bool, class2: bool, class3: bool, -) -> *mut Request { - // the event classes first, then class 0, as a class scan writes them - let classes = [ - (class1, Variation::Group60Var2), - (class2, Variation::Group60Var3), - (class3, Variation::Group60Var4), - (class0, Variation::Group60Var1), - ]; - let request = classes - .into_iter() - .filter(|(enabled, _)| *enabled) - .fold(dnp3::master::Request::new(), |request, (_, variation)| { - request.add_all_objects(variation) - }); - Request::create(request) -} - -pub unsafe fn request_new_all_objects(variation: ffi::Variation) -> *mut Request { - Request::create(dnp3::master::Request::new().add_all_objects(variation.into())) -} - -pub unsafe fn request_new_one_byte_range( - variation: ffi::Variation, - start: u8, - stop: u8, -) -> *mut Request { - Request::create(dnp3::master::Request::new().add_range_8(variation.into(), start, stop)) -} - -pub unsafe fn request_new_two_byte_range( - variation: ffi::Variation, - start: u16, - stop: u16, -) -> *mut Request { - Request::create(dnp3::master::Request::new().add_range_16(variation.into(), start, stop)) -} - -pub unsafe fn request_new_one_byte_limited_count( - variation: ffi::Variation, - count: u8, -) -> *mut Request { - Request::create( - dnp3::master::Request::new().add_one_byte_limited_count(variation.into(), count), - ) -} - -pub unsafe fn request_new_two_byte_limited_count( - variation: ffi::Variation, - count: u16, -) -> *mut Request { - Request::create( - dnp3::master::Request::new().add_two_byte_limited_count(variation.into(), count), - ) -} - -pub unsafe fn request_destroy(request: *mut Request) { - if !request.is_null() { - drop(Box::from_raw(request)); +) { + if let Some(request) = request.as_mut() { + let classes = Classes::new(class0, EventClasses::new(class1, class2, class3)); + request.update(|r| r.add_classes(classes)); } } diff --git a/ffi/dnp3-schema/src/master/mod.rs b/ffi/dnp3-schema/src/master/mod.rs index 995ef7ef..e5a986d1 100644 --- a/ffi/dnp3-schema/src/master/mod.rs +++ b/ffi/dnp3-schema/src/master/mod.rs @@ -454,6 +454,7 @@ pub(crate) fn define(lib: &mut LibraryBuilder, shared: &SharedDefinitions) -> Ba doc("Send the specified request to the association using the supplied function and collection of request headers") .details("This is useful for constructing various types of WRITE and FREEZE operations where an empty response is expected from the outstation, and the only indication of success are bits in IIN.2.") .details("The request will fail if 1) The response contains object headers or 2) One of the error bits in IIN.2 is set.") + .details("The request is sent with whatever function code is given. Reads take a {class:read_request}, which can't carry values.") )? .build()?; diff --git a/ffi/dnp3-schema/src/master/request.rs b/ffi/dnp3-schema/src/master/request.rs index 9aad1b08..8b9ccbf1 100644 --- a/ffi/dnp3-schema/src/master/request.rs +++ b/ffi/dnp3-schema/src/master/request.rs @@ -88,35 +88,29 @@ fn define_read_request( } fn define_request(lib: &mut LibraryBuilder, shared: &SharedDefinitions) -> BackTraced { - const NAME: &str = "request"; - let request = lib.declare_class(NAME)?; + let request = lib.declare_class("request")?; let constructor = lib .define_constructor(request.clone())? .doc("Create a new request with no headers")? .build()?; - let request_new_class_fn = lib - .define_function("request_new_class")? + let destructor = lib.define_destructor( + request.clone(), + "Destroy a request created with {class:request.[constructor]}", + )?; + + let add_classes_fn = lib + .define_method("add_classes", request.clone())? .param("class0", Primitive::Bool, "Ask for class 0 (static data)")? .param("class1", Primitive::Bool, "Ask for class 1 events")? .param("class2", Primitive::Bool, "Ask for class 2 events")? .param("class3", Primitive::Bool, "Ask for class 3 events")? - .returns( - request.clone(), - "Handle to the created request", - )? .doc( - doc("Create a new request asking for classes") - .details("An identical request can be created manually with {class:request.add_all_objects_header()} and variations {enum:variation.group60_var1}, {enum:variation.group60_var2}, {enum:variation.group60_var3} and {enum:variation.group60_var4}.") + doc("Add headers naming classes") + .details("The headers name events in classes 1, 2 and 3, then class 0."), )? - .build_static("class_request")?; - - let destructor = lib - .define_destructor( - request.clone(), - "Destroy a request created with {class:request.[constructor]} or {class:request.class_request()}." - )?; + .build()?; let add_string_attribute_fn = lib .define_method("add_string_attribute", request.clone())? @@ -164,17 +158,13 @@ fn define_request(lib: &mut LibraryBuilder, shared: &SharedDefinitions) -> BackT )? .build()?; - let constructors = define_single_header_constructors(lib, shared, &request, NAME)?; let header_methods = define_header_methods(lib, shared, &request)?; let mut builder = lib .define_class(&request)? .constructor(constructor)? .destructor(destructor)? - .static_method(request_new_class_fn)?; - for method in constructors { - builder = builder.static_method(method)?; - } + .method(add_classes_fn)?; for method in header_methods { builder = builder.method(method)?; } @@ -192,102 +182,6 @@ fn define_request(lib: &mut LibraryBuilder, shared: &SharedDefinitions) -> BackT Ok(request) } -/// The static methods that create a request of a single header, for both request classes -fn define_single_header_constructors( - lib: &mut LibraryBuilder, - shared: &SharedDefinitions, - class: &ClassDeclarationHandle, - name: &str, -) -> BackTraced>> { - let more = |method: &str| { - format!("More headers can be added to it with {{class:{name}.{method}()}} and the other add methods.") - }; - - let all_objects = lib - .define_function(format!("{name}_new_all_objects"))? - .param( - "variation", - shared.variation_enum.clone(), - "Variation to ask for", - )? - .returns(class.clone(), "Handle to the created request")? - .doc( - doc("Create a new request asking for all objects of a particular variation.") - .details(more("add_all_objects_header")), - )? - .build_static("all_objects")?; - - let one_byte_range = lib - .define_function(format!("{name}_new_one_byte_range"))? - .param( - "variation", - shared.variation_enum.clone(), - "Variation to ask for", - )? - .param("start", Primitive::U8, "Start index to ask")? - .param("stop", Primitive::U8, "Stop index to ask (inclusive)")? - .returns(class.clone(), "Handle to the created request")? - .doc( - doc("Create a new request asking for range of objects (using 8-bit start/stop).") - .details(more("add_one_byte_range_header")), - )? - .build_static("one_byte_range")?; - - let two_byte_range = lib - .define_function(format!("{name}_new_two_byte_range"))? - .param( - "variation", - shared.variation_enum.clone(), - "Variation to ask for", - )? - .param("start", Primitive::U16, "Start index to ask")? - .param("stop", Primitive::U16, "Stop index to ask (inclusive)")? - .returns(class.clone(), "Handle to the created request")? - .doc( - doc("Create a new request asking for range of objects (using 16-bit start/stop).") - .details(more("add_two_byte_range_header")), - )? - .build_static("two_byte_range")?; - - let one_byte_limited_count = lib - .define_function(format!("{name}_new_one_byte_limited_count"))? - .param( - "variation", - shared.variation_enum.clone(), - "Variation to ask for", - )? - .param("count", Primitive::U8, "Maximum number of events")? - .returns(class.clone(), "Handle to the created request")? - .doc( - doc("Create a new request asking for a limited count of objects (using an 8-bit count).") - .details(more("add_one_byte_limited_count_header")), - )? - .build_static("one_byte_limited_count")?; - - let two_byte_limited_count = lib - .define_function(format!("{name}_new_two_byte_limited_count"))? - .param( - "variation", - shared.variation_enum.clone(), - "Variation to ask for", - )? - .param("count", Primitive::U16, "Maximum number of events")? - .returns(class.clone(), "Handle to the created request")? - .doc( - doc("Create a new request asking for a limited count of objects (using a 16-bit count).") - .details(more("add_two_byte_limited_count_header")), - )? - .build_static("two_byte_limited_count")?; - - Ok(vec![ - all_objects, - one_byte_range, - two_byte_range, - one_byte_limited_count, - two_byte_limited_count, - ]) -} - /// The methods that add a READ-style header, for both request classes fn define_header_methods( lib: &mut LibraryBuilder, From 430aeeb2730082d6c5d5eb897bb376aa711241e9 Mon Sep 17 00:00:00 2001 From: jadamcrain Date: Thu, 26 Nov 2026 18:00:00 -0800 Subject: [PATCH 4/5] Use the same header method names in Rust and the bindings add_one_byte_range and add_two_byte_range replace add_range_8 and add_range_16; the FFI drops the _header suffix and renames add_specific_attribute to add_device_attribute. --- dnp3/src/master/request.rs | 28 ++++++++-------- dnp3/src/no_panic_check/encode.rs | 8 ++--- ffi/bindings/c/master_example.c | 20 +++++------ ffi/bindings/c/master_example.cpp | 20 +++++------ .../dotnet/examples/master/Program.cs | 20 +++++------ .../stepfunc/dnp3/examples/MasterExample.java | 20 +++++------ ffi/dnp3-ffi/src/request.rs | 33 +++++++++---------- ffi/dnp3-schema/src/master/request.rs | 16 ++++----- ffi/dnp3-schema/src/variation.rs | 2 +- 9 files changed, 82 insertions(+), 85 deletions(-) diff --git a/dnp3/src/master/request.rs b/dnp3/src/master/request.rs index 55894e10..b58c6f1e 100644 --- a/dnp3/src/master/request.rs +++ b/dnp3/src/master/request.rs @@ -330,7 +330,7 @@ impl ReadRequest { } /// Add an 8-bit start/stop header (0x00) with the specified variation - pub fn add_range_8(self, variation: Variation, start: u8, stop: u8) -> Self { + pub fn add_one_byte_range(self, variation: Variation, start: u8, stop: u8) -> Self { self.add(ReadHeader::Range8 { variation, start, @@ -339,7 +339,7 @@ impl ReadRequest { } /// Add a 16-bit start/stop header (0x01) with the specified variation - pub fn add_range_16(self, variation: Variation, start: u16, stop: u16) -> Self { + pub fn add_two_byte_range(self, variation: Variation, start: u16, stop: u16) -> Self { self.add(ReadHeader::Range16 { variation, start, @@ -441,7 +441,7 @@ impl Request { } /// Add an 8-bit start/stop header (0x00) with the specified variation - pub fn add_range_8(self, variation: Variation, start: u8, stop: u8) -> Self { + pub fn add_one_byte_range(self, variation: Variation, start: u8, stop: u8) -> Self { self.add(Header::Read(ReadHeader::Range8 { variation, start, @@ -450,7 +450,7 @@ impl Request { } /// Add a 16-bit start/stop header (0x01) with the specified variation - pub fn add_range_16(self, variation: Variation, start: u16, stop: u16) -> Self { + pub fn add_two_byte_range(self, variation: Variation, start: u16, stop: u16) -> Self { self.add(Header::Read(ReadHeader::Range16 { variation, start, @@ -1214,13 +1214,13 @@ mod tests { let valid = || ReadRequest::new().add_all_objects(Variation::Group60Var1); for request in [ ReadRequest::new().add_all_objects(G0V0), - ReadRequest::new().add_range_8(G0V0, 1, 2), - ReadRequest::new().add_range_16(G0V0, 1, 2), + ReadRequest::new().add_one_byte_range(G0V0, 1, 2), + ReadRequest::new().add_two_byte_range(G0V0, 1, 2), ReadRequest::new().add_one_byte_limited_count(G0V0, 1), ReadRequest::new().add_two_byte_limited_count(G0V0, 1), valid().add_all_objects(G0V0), - valid().add_range_8(G0V0, 1, 2), - valid().add_range_16(G0V0, 1, 2), + valid().add_one_byte_range(G0V0, 1, 2), + valid().add_two_byte_range(G0V0, 1, 2), valid().add_one_byte_limited_count(G0V0, 1), valid().add_two_byte_limited_count(G0V0, 1), ] { @@ -1238,8 +1238,8 @@ mod tests { let valid = || Request::new().add_all_objects(Variation::Group60Var1); for request in [ valid().add_all_objects(G0V0), - valid().add_range_8(G0V0, 1, 2), - valid().add_range_16(G0V0, 1, 2), + valid().add_one_byte_range(G0V0, 1, 2), + valid().add_two_byte_range(G0V0, 1, 2), valid().add_one_byte_limited_count(G0V0, 1), valid().add_two_byte_limited_count(G0V0, 1), ] { @@ -1404,12 +1404,12 @@ mod tests { variation, start, stop, - }) => request.add_range_8(variation, start, stop), + }) => request.add_one_byte_range(variation, start, stop), ReadOp::Header(ReadHeader::Range16 { variation, start, stop, - }) => request.add_range_16(variation, start, stop), + }) => request.add_two_byte_range(variation, start, stop), ReadOp::Header(ReadHeader::AllObjects { variation }) => { request.add_all_objects(variation) } @@ -1592,12 +1592,12 @@ mod tests { variation, start, stop, - }) => request.add_range_8(variation, start, stop), + }) => request.add_one_byte_range(variation, start, stop), Item::Read(ReadHeader::Range16 { variation, start, stop, - }) => request.add_range_16(variation, start, stop), + }) => request.add_two_byte_range(variation, start, stop), Item::Read(ReadHeader::AllObjects { variation }) => { request.add_all_objects(variation) } diff --git a/dnp3/src/no_panic_check/encode.rs b/dnp3/src/no_panic_check/encode.rs index fa7e3f22..fb89fb5c 100644 --- a/dnp3/src/no_panic_check/encode.rs +++ b/dnp3/src/no_panic_check/encode.rs @@ -242,8 +242,8 @@ fn read(source: &mut Source) -> ReadRequest { let variation = variation(source); match source.u8() % 7 { 0 => request.add_all_objects(variation), - 1 => request.add_range_8(variation, source.u8(), source.u8()), - 2 => request.add_range_16(variation, source.u16(), source.u16()), + 1 => request.add_one_byte_range(variation, source.u8(), source.u8()), + 2 => request.add_two_byte_range(variation, source.u16(), source.u16()), 3 => request.add_one_byte_limited_count(variation, source.u8()), 4 => request.add_two_byte_limited_count(variation, source.u16()), 5 => request.add_device_attribute(source.u8(), AttrSet::new(source.u8())), @@ -280,8 +280,8 @@ fn request(source: &mut Source) -> Request { let variation = variation(source); match source.u8() % 7 { 0 => request.add_all_objects(variation), - 1 => request.add_range_8(variation, source.u8(), source.u8()), - 2 => request.add_range_16(variation, source.u16(), source.u16()), + 1 => request.add_one_byte_range(variation, source.u8(), source.u8()), + 2 => request.add_two_byte_range(variation, source.u16(), source.u16()), 3 => request.add_one_byte_limited_count(variation, source.u8()), 4 => request.add_two_byte_limited_count(variation, source.u16()), 5 => request.add_freeze_interval(FreezeInterval::new( diff --git a/ffi/bindings/c/master_example.c b/ffi/bindings/c/master_example.c index 64d23e2c..cffcc004 100644 --- a/ffi/bindings/c/master_example.c +++ b/ffi/bindings/c/master_example.c @@ -349,7 +349,7 @@ void run_command(dnp3_master_channel_t *channel, dnp3_association_id_t associati } else if (strcmp(cmd, "rao") == 0) { dnp3_read_request_t *request = dnp3_read_request_create(); - dnp3_read_request_add_all_objects_header(request, DNP3_VARIATION_GROUP40_VAR0); + dnp3_read_request_add_all_objects(request, DNP3_VARIATION_GROUP40_VAR0); dnp3_read_task_callback_t cb = { .on_complete = &on_read_complete, .on_failure = &on_read_failure, @@ -362,8 +362,8 @@ void run_command(dnp3_master_channel_t *channel, dnp3_association_id_t associati } else if (strcmp(cmd, "rmo") == 0) { dnp3_read_request_t *request = dnp3_read_request_create(); - dnp3_read_request_add_all_objects_header(request, DNP3_VARIATION_GROUP10_VAR0); - dnp3_read_request_add_all_objects_header(request, DNP3_VARIATION_GROUP40_VAR0); + dnp3_read_request_add_all_objects(request, DNP3_VARIATION_GROUP10_VAR0); + dnp3_read_request_add_all_objects(request, DNP3_VARIATION_GROUP40_VAR0); dnp3_read_task_callback_t cb = { .on_complete = &on_read_complete, .on_failure = &on_read_failure, @@ -376,8 +376,8 @@ void run_command(dnp3_master_channel_t *channel, dnp3_association_id_t associati } else if (strcmp(cmd, "rco") == 0) { dnp3_read_request_t *request = dnp3_read_request_create(); - dnp3_read_request_add_all_objects_header(request, DNP3_VARIATION_GROUP20_VAR0); - dnp3_read_request_add_all_objects_header(request, DNP3_VARIATION_GROUP21_VAR0); + dnp3_read_request_add_all_objects(request, DNP3_VARIATION_GROUP20_VAR0); + dnp3_read_request_add_all_objects(request, DNP3_VARIATION_GROUP21_VAR0); dnp3_read_task_callback_t cb = { .on_complete = &on_read_complete, .on_failure = &on_read_failure, @@ -467,7 +467,7 @@ void run_command(dnp3_master_channel_t *channel, dnp3_association_id_t associati else if (strcmp(cmd, "ifz") == 0) { // copy every counter to its frozen counter dnp3_request_t *request = dnp3_request_create(); - dnp3_request_add_all_objects_header(request, DNP3_VARIATION_GROUP20_VAR0); + dnp3_request_add_all_objects(request, DNP3_VARIATION_GROUP20_VAR0); dnp3_empty_response_callback_t cb = { .on_complete = &on_empty_response_complete, .on_failure = &on_empty_response_failure, @@ -482,7 +482,7 @@ void run_command(dnp3_master_channel_t *channel, dnp3_association_id_t associati else if (strcmp(cmd, "fcl") == 0) { // copy every counter to its frozen counter, then clear the counter dnp3_request_t *request = dnp3_request_create(); - dnp3_request_add_all_objects_header(request, DNP3_VARIATION_GROUP20_VAR0); + dnp3_request_add_all_objects(request, DNP3_VARIATION_GROUP20_VAR0); dnp3_empty_response_callback_t cb = { .on_complete = &on_empty_response_complete, .on_failure = &on_empty_response_failure, @@ -500,7 +500,7 @@ void run_command(dnp3_master_channel_t *channel, dnp3_association_id_t associati // freeze all the counters once per day relative to the beginning of the current hour dnp3_request_add_time_and_interval(request, 0, 86400000); // apply this schedule to all counters - dnp3_request_add_all_objects_header(request, DNP3_VARIATION_GROUP20_VAR0); + dnp3_request_add_all_objects(request, DNP3_VARIATION_GROUP20_VAR0); dnp3_empty_response_callback_t cb = { .on_complete = &on_empty_response_complete, @@ -518,7 +518,7 @@ void run_command(dnp3_master_channel_t *channel, dnp3_association_id_t associati else if (strcmp(cmd, "rda") == 0) { // ANCHOR: read_attributes dnp3_read_request_t *request = dnp3_read_request_create(); - dnp3_read_request_add_specific_attribute(request, DNP3_ATTRIBUTE_VARIATIONS_ALL_ATTRIBUTES_REQUEST, 0); + dnp3_read_request_add_device_attribute(request, DNP3_ATTRIBUTE_VARIATIONS_ALL_ATTRIBUTES_REQUEST, 0); dnp3_read_task_callback_t cb = { .on_complete = &on_read_complete, @@ -551,7 +551,7 @@ void run_command(dnp3_master_channel_t *channel, dnp3_association_id_t associati } else if (strcmp(cmd, "ral") == 0) { dnp3_read_request_t *request = dnp3_read_request_create(); - dnp3_read_request_add_specific_attribute(request, DNP3_ATTRIBUTE_VARIATIONS_LIST_OF_VARIATIONS, 0); + dnp3_read_request_add_device_attribute(request, DNP3_ATTRIBUTE_VARIATIONS_LIST_OF_VARIATIONS, 0); dnp3_read_task_callback_t cb = { .on_complete = &on_read_complete, .on_failure = &on_read_failure, diff --git a/ffi/bindings/c/master_example.cpp b/ffi/bindings/c/master_example.cpp index 43be5d03..912761c2 100644 --- a/ffi/bindings/c/master_example.cpp +++ b/ffi/bindings/c/master_example.cpp @@ -283,19 +283,19 @@ void run_command(const std::string &cmd, dnp3::MasterChannel &channel, dnp3::Ass } else if (cmd == "rao") { dnp3::ReadRequest request; - request.add_all_objects_header(dnp3::Variation::group40_var0); + request.add_all_objects(dnp3::Variation::group40_var0); channel.read(assoc, request, create_read_callback("rao")); } else if (cmd == "rmo") { dnp3::ReadRequest request; - request.add_all_objects_header(dnp3::Variation::group10_var0); - request.add_all_objects_header(dnp3::Variation::group40_var0); + request.add_all_objects(dnp3::Variation::group10_var0); + request.add_all_objects(dnp3::Variation::group40_var0); channel.read(assoc, request, create_read_callback("rmo")); } else if (cmd == "rco") { dnp3::ReadRequest request; - request.add_all_objects_header(dnp3::Variation::group20_var0); - request.add_all_objects_header(dnp3::Variation::group21_var0); + request.add_all_objects(dnp3::Variation::group20_var0); + request.add_all_objects(dnp3::Variation::group21_var0); channel.read(assoc, request, create_read_callback("rco")); } else if (cmd == "cmd") { @@ -334,13 +334,13 @@ void run_command(const std::string &cmd, dnp3::MasterChannel &channel, dnp3::Ass else if (cmd == "ifz") { // copy every counter to its frozen counter dnp3::Request request; - request.add_all_objects_header(dnp3::Variation::group20_var0); + request.add_all_objects(dnp3::Variation::group20_var0); channel.send_and_expect_empty_response(assoc, dnp3::FunctionCode::immediate_freeze, request, create_empty_response_callback("ifz")); } else if (cmd == "fcl") { // copy every counter to its frozen counter, then clear the counter dnp3::Request request; - request.add_all_objects_header(dnp3::Variation::group20_var0); + request.add_all_objects(dnp3::Variation::group20_var0); channel.send_and_expect_empty_response(assoc, dnp3::FunctionCode::freeze_clear, request, create_empty_response_callback("fcl")); } else if (cmd == "fat") { @@ -349,14 +349,14 @@ void run_command(const std::string &cmd, dnp3::MasterChannel &channel, dnp3::Ass // freeze all the counters once per day relative to the beginning of the current hour request.add_time_and_interval(0, 86400000); // apply this schedule to all counters - request.add_all_objects_header(dnp3::Variation::group20_var0); + request.add_all_objects(dnp3::Variation::group20_var0); channel.send_and_expect_empty_response(assoc, dnp3::FunctionCode::freeze_at_time, request, create_empty_response_callback("fat")); // ANCHOR_END: freeze_at_time } else if (cmd == "rda") { // ANCHOR: read_attributes dnp3::ReadRequest request; - request.add_specific_attribute(dnp3::attribute_variations::all_attributes_request, 0); + request.add_device_attribute(dnp3::attribute_variations::all_attributes_request, 0); channel.read(assoc, request, create_read_callback("rda")); // ANCHOR_END: read_attributes } @@ -369,7 +369,7 @@ void run_command(const std::string &cmd, dnp3::MasterChannel &channel, dnp3::Ass } else if (cmd == "ral") { dnp3::ReadRequest request; - request.add_specific_attribute(dnp3::attribute_variations::list_of_variations, 0); + request.add_device_attribute(dnp3::attribute_variations::list_of_variations, 0); channel.read(assoc, request, create_read_callback("ral")); } else if (cmd == "crt") { diff --git a/ffi/bindings/dotnet/examples/master/Program.cs b/ffi/bindings/dotnet/examples/master/Program.cs index 2b01408a..156b2f6e 100644 --- a/ffi/bindings/dotnet/examples/master/Program.cs +++ b/ffi/bindings/dotnet/examples/master/Program.cs @@ -240,23 +240,23 @@ private static async Task RunOneCommand(MasterChannel channel, Associati case "rao": { var request = new ReadRequest(); - request.AddAllObjectsHeader(Variation.Group40Var0); + request.AddAllObjects(Variation.Group40Var0); await channel.Read(association, request); return Success; } case "rmo": { var request = new ReadRequest(); - request.AddAllObjectsHeader(Variation.Group10Var0); - request.AddAllObjectsHeader(Variation.Group40Var0); + request.AddAllObjects(Variation.Group10Var0); + request.AddAllObjects(Variation.Group40Var0); await channel.Read(association, request); return Success; } case "rco": { var request = new ReadRequest(); - request.AddAllObjectsHeader(Variation.Group20Var0); - request.AddAllObjectsHeader(Variation.Group21Var0); + request.AddAllObjects(Variation.Group20Var0); + request.AddAllObjects(Variation.Group21Var0); await channel.Read(association, request); return Success; } @@ -312,7 +312,7 @@ private static async Task RunOneCommand(MasterChannel channel, Associati // freeze all the counters once per day relative to the beginning of the current hour request.AddTimeAndInterval(0, 86400000); // apply this schedule to all counters - request.AddAllObjectsHeader(Variation.Group20Var0); + request.AddAllObjects(Variation.Group20Var0); await channel.SendAndExpectEmptyResponse(association, FunctionCode.FreezeAtTime, request); // ANCHOR_END: freeze_at_time return Success; @@ -321,7 +321,7 @@ private static async Task RunOneCommand(MasterChannel channel, Associati { // copy every counter to its frozen counter var request = new Request(); - request.AddAllObjectsHeader(Variation.Group20Var0); + request.AddAllObjects(Variation.Group20Var0); await channel.SendAndExpectEmptyResponse(association, FunctionCode.ImmediateFreeze, request); return Success; } @@ -329,7 +329,7 @@ private static async Task RunOneCommand(MasterChannel channel, Associati { // copy every counter to its frozen counter, then clear the counter var request = new Request(); - request.AddAllObjectsHeader(Variation.Group20Var0); + request.AddAllObjects(Variation.Group20Var0); await channel.SendAndExpectEmptyResponse(association, FunctionCode.FreezeClear, request); return Success; } @@ -337,7 +337,7 @@ private static async Task RunOneCommand(MasterChannel channel, Associati { // ANCHOR: read_attributes var request = new ReadRequest(); - request.AddSpecificAttribute(AttributeVariations.AllAttributesRequest, 0); + request.AddDeviceAttribute(AttributeVariations.AllAttributesRequest, 0); await channel.Read(association, request); // ANCHOR_END: read_attributes return Success; @@ -354,7 +354,7 @@ private static async Task RunOneCommand(MasterChannel channel, Associati case "ral": { var request = new ReadRequest(); - request.AddSpecificAttribute(AttributeVariations.ListOfVariations, 0); + request.AddDeviceAttribute(AttributeVariations.ListOfVariations, 0); await channel.Read(association, request); return Success; } diff --git a/ffi/bindings/java/examples/src/main/java/io/stepfunc/dnp3/examples/MasterExample.java b/ffi/bindings/java/examples/src/main/java/io/stepfunc/dnp3/examples/MasterExample.java index 2b32b0ff..8ba2d658 100644 --- a/ffi/bindings/java/examples/src/main/java/io/stepfunc/dnp3/examples/MasterExample.java +++ b/ffi/bindings/java/examples/src/main/java/io/stepfunc/dnp3/examples/MasterExample.java @@ -298,23 +298,23 @@ private static String runOneCommand(MasterChannel channel, AssociationId associa case "rao": { ReadRequest request = new ReadRequest(); - request.addAllObjectsHeader(Variation.GROUP40_VAR0); + request.addAllObjects(Variation.GROUP40_VAR0); channel.read(association, request).toCompletableFuture().get(); return success; } case "rmo": { ReadRequest request = new ReadRequest(); - request.addAllObjectsHeader(Variation.GROUP10_VAR0); - request.addAllObjectsHeader(Variation.GROUP40_VAR0); + request.addAllObjects(Variation.GROUP10_VAR0); + request.addAllObjects(Variation.GROUP40_VAR0); channel.read(association, request).toCompletableFuture().get(); return success; } case "rco": { ReadRequest request = new ReadRequest(); - request.addAllObjectsHeader(Variation.GROUP20_VAR0); - request.addAllObjectsHeader(Variation.GROUP21_VAR0); + request.addAllObjects(Variation.GROUP20_VAR0); + request.addAllObjects(Variation.GROUP21_VAR0); channel.read(association, request).toCompletableFuture().get(); return success; } @@ -369,7 +369,7 @@ private static String runOneCommand(MasterChannel channel, AssociationId associa // freeze all the counters once per day relative to the beginning of the current hour request.addTimeAndInterval(ulong(0), uint(86400000)); // apply this schedule to all counters - request.addAllObjectsHeader(Variation.GROUP20_VAR0); + request.addAllObjects(Variation.GROUP20_VAR0); channel.sendAndExpectEmptyResponse(association, FunctionCode.FREEZE_AT_TIME, request).toCompletableFuture().get(); // ANCHOR_END: freeze_at_time return success; @@ -378,7 +378,7 @@ private static String runOneCommand(MasterChannel channel, AssociationId associa { // copy every counter to its frozen counter Request request = new Request(); - request.addAllObjectsHeader(Variation.GROUP20_VAR0); + request.addAllObjects(Variation.GROUP20_VAR0); channel.sendAndExpectEmptyResponse(association, FunctionCode.IMMEDIATE_FREEZE, request).toCompletableFuture().get(); return success; } @@ -386,7 +386,7 @@ private static String runOneCommand(MasterChannel channel, AssociationId associa { // copy every counter to its frozen counter, then clear the counter Request request = new Request(); - request.addAllObjectsHeader(Variation.GROUP20_VAR0); + request.addAllObjects(Variation.GROUP20_VAR0); channel.sendAndExpectEmptyResponse(association, FunctionCode.FREEZE_CLEAR, request).toCompletableFuture().get(); return success; } @@ -394,7 +394,7 @@ private static String runOneCommand(MasterChannel channel, AssociationId associa { // ANCHOR: read_attributes ReadRequest request = new ReadRequest(); - request.addSpecificAttribute(AttributeVariations.ALL_ATTRIBUTES_REQUEST, ubyte(0)); + request.addDeviceAttribute(AttributeVariations.ALL_ATTRIBUTES_REQUEST, ubyte(0)); channel.read(association, request).toCompletableFuture().get(); // ANCHOR_END: read_attributes return success; @@ -411,7 +411,7 @@ private static String runOneCommand(MasterChannel channel, AssociationId associa case "ral": { ReadRequest request = new ReadRequest(); - request.addSpecificAttribute(AttributeVariations.LIST_OF_VARIATIONS, ubyte(0)); + request.addDeviceAttribute(AttributeVariations.LIST_OF_VARIATIONS, ubyte(0)); channel.read(association, request).toCompletableFuture().get(); return success; } diff --git a/ffi/dnp3-ffi/src/request.rs b/ffi/dnp3-ffi/src/request.rs index 5a7d225a..2cfcc6f3 100644 --- a/ffi/dnp3-ffi/src/request.rs +++ b/ffi/dnp3-ffi/src/request.rs @@ -66,7 +66,7 @@ pub(crate) unsafe fn read_request_add_classes( } } -pub(crate) unsafe fn read_request_add_specific_attribute( +pub(crate) unsafe fn read_request_add_device_attribute( request: *mut ReadRequest, variation: u8, set: u8, @@ -76,29 +76,29 @@ pub(crate) unsafe fn read_request_add_specific_attribute( } } -pub(crate) unsafe fn read_request_add_one_byte_range_header( +pub(crate) unsafe fn read_request_add_one_byte_range( request: *mut ReadRequest, variation: ffi::Variation, start: u8, stop: u8, ) { if let Some(request) = request.as_mut() { - request.update(|r| r.add_range_8(variation.into(), start, stop)); + request.update(|r| r.add_one_byte_range(variation.into(), start, stop)); } } -pub(crate) unsafe fn read_request_add_two_byte_range_header( +pub(crate) unsafe fn read_request_add_two_byte_range( request: *mut ReadRequest, variation: ffi::Variation, start: u16, stop: u16, ) { if let Some(request) = request.as_mut() { - request.update(|r| r.add_range_16(variation.into(), start, stop)); + request.update(|r| r.add_two_byte_range(variation.into(), start, stop)); } } -pub(crate) unsafe fn read_request_add_all_objects_header( +pub(crate) unsafe fn read_request_add_all_objects( request: *mut ReadRequest, variation: ffi::Variation, ) { @@ -107,7 +107,7 @@ pub(crate) unsafe fn read_request_add_all_objects_header( } } -pub(crate) unsafe fn read_request_add_one_byte_limited_count_header( +pub(crate) unsafe fn read_request_add_one_byte_limited_count( request: *mut ReadRequest, variation: ffi::Variation, count: u8, @@ -117,7 +117,7 @@ pub(crate) unsafe fn read_request_add_one_byte_limited_count_header( } } -pub(crate) unsafe fn read_request_add_two_byte_limited_count_header( +pub(crate) unsafe fn read_request_add_two_byte_limited_count( request: *mut ReadRequest, variation: ffi::Variation, count: u16, @@ -184,38 +184,35 @@ pub(crate) unsafe fn request_add_uint_attribute( } } -pub(crate) unsafe fn request_add_one_byte_range_header( +pub(crate) unsafe fn request_add_one_byte_range( request: *mut Request, variation: ffi::Variation, start: u8, stop: u8, ) { if let Some(request) = request.as_mut() { - request.update(|r| r.add_range_8(variation.into(), start, stop)); + request.update(|r| r.add_one_byte_range(variation.into(), start, stop)); } } -pub(crate) unsafe fn request_add_two_byte_range_header( +pub(crate) unsafe fn request_add_two_byte_range( request: *mut Request, variation: ffi::Variation, start: u16, stop: u16, ) { if let Some(request) = request.as_mut() { - request.update(|r| r.add_range_16(variation.into(), start, stop)); + request.update(|r| r.add_two_byte_range(variation.into(), start, stop)); } } -pub(crate) unsafe fn request_add_all_objects_header( - request: *mut Request, - variation: ffi::Variation, -) { +pub(crate) unsafe fn request_add_all_objects(request: *mut Request, variation: ffi::Variation) { if let Some(request) = request.as_mut() { request.update(|r| r.add_all_objects(variation.into())); } } -pub(crate) unsafe fn request_add_one_byte_limited_count_header( +pub(crate) unsafe fn request_add_one_byte_limited_count( request: *mut Request, variation: ffi::Variation, count: u8, @@ -225,7 +222,7 @@ pub(crate) unsafe fn request_add_one_byte_limited_count_header( } } -pub(crate) unsafe fn request_add_two_byte_limited_count_header( +pub(crate) unsafe fn request_add_two_byte_limited_count( request: *mut Request, variation: ffi::Variation, count: u16, diff --git a/ffi/dnp3-schema/src/master/request.rs b/ffi/dnp3-schema/src/master/request.rs index 8b9ccbf1..1bfe8d6e 100644 --- a/ffi/dnp3-schema/src/master/request.rs +++ b/ffi/dnp3-schema/src/master/request.rs @@ -50,8 +50,8 @@ fn define_read_request( )? .build()?; - let add_specific_attribute_fn = lib - .define_method("add_specific_attribute", read_request.clone())? + let add_device_attribute_fn = lib + .define_method("add_device_attribute", read_request.clone())? .param( "variation", Primitive::U8, @@ -76,7 +76,7 @@ fn define_read_request( builder = builder.method(method)?; } let read_request = builder - .method(add_specific_attribute_fn)? + .method(add_device_attribute_fn)? .doc( doc("The object headers of a READ, for one-time reads and polls") .details("Only headers that are valid in a READ can be added. A request that writes or freezes objects is a {class:request}.") @@ -189,7 +189,7 @@ fn define_header_methods( class: &ClassDeclarationHandle, ) -> BackTraced>> { let add_one_byte_range_header = lib - .define_method("add_one_byte_range_header", class.clone())? + .define_method("add_one_byte_range", class.clone())? .param( "variation", shared.variation_enum.clone(), @@ -201,7 +201,7 @@ fn define_header_methods( .build()?; let add_two_byte_range_header = lib - .define_method("add_two_byte_range_header", class.clone())? + .define_method("add_two_byte_range", class.clone())? .param( "variation", shared.variation_enum.clone(), @@ -213,7 +213,7 @@ fn define_header_methods( .build()?; let add_all_objects_header = lib - .define_method("add_all_objects_header", class.clone())? + .define_method("add_all_objects", class.clone())? .param( "variation", shared.variation_enum.clone(), @@ -223,7 +223,7 @@ fn define_header_methods( .build()?; let add_one_byte_limited_count_header = lib - .define_method("add_one_byte_limited_count_header", class.clone())? + .define_method("add_one_byte_limited_count", class.clone())? .param( "variation", shared.variation_enum.clone(), @@ -234,7 +234,7 @@ fn define_header_methods( .build()?; let add_two_byte_limited_count_header = lib - .define_method("add_two_byte_limited_count_header", class.clone())? + .define_method("add_two_byte_limited_count", class.clone())? .param( "variation", shared.variation_enum.clone(), diff --git a/ffi/dnp3-schema/src/variation.rs b/ffi/dnp3-schema/src/variation.rs index bb68a24d..f5c218b5 100644 --- a/ffi/dnp3-schema/src/variation.rs +++ b/ffi/dnp3-schema/src/variation.rs @@ -21,7 +21,7 @@ use oo_bindgen::model::{BackTraced, EnumHandle, LibraryBuilder}; pub(crate) fn define(lib: &mut LibraryBuilder) -> BackTraced { let variation = lib .define_enum("variation")? - .push("group0", "Device Attributes - Specific attribute (variations 1 to 253 and 255). Only reported in {struct:header_info}: it can't name the attribute, so a request that uses it fails with {enum:read_error.bad_encoding}. Read a specific attribute with {class:read_request.add_specific_attribute()} and all of them with {enum:variation.group0_var254}")? + .push("group0", "Device Attributes - Specific attribute (variations 1 to 253 and 255). Only reported in {struct:header_info}: it can't name the attribute, so a request that uses it fails with {enum:read_error.bad_encoding}. Read a specific attribute with {class:read_request.add_device_attribute()} and all of them with {enum:variation.group0_var254}")? .push("group0_var254", "Device Attributes - All attributes request")? .push("group1_var0", "Binary Input - Any variation")? .push("group1_var1", "Binary Input - Packed format")? From a52642ea30f006577da01abf08675666df3d2816 Mon Sep 17 00:00:00 2001 From: jadamcrain Date: Thu, 26 Nov 2026 19:05:12 -0800 Subject: [PATCH 5/5] Name the C example's poll request event_scan, as the other languages do --- ffi/bindings/c/master_example.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/ffi/bindings/c/master_example.c b/ffi/bindings/c/master_example.c index cffcc004..ea130665 100644 --- a/ffi/bindings/c/master_example.c +++ b/ffi/bindings/c/master_example.c @@ -294,11 +294,11 @@ int run_channel(dnp3_master_channel_t *channel, dnp3_association_id_t associatio { // create an event poll // ANCHOR: add_poll - dnp3_read_request_t *poll_request = dnp3_read_request_create(); - dnp3_read_request_add_classes(poll_request, false, true, true, true); + dnp3_read_request_t *event_scan = dnp3_read_request_create(); + dnp3_read_request_add_classes(event_scan, false, true, true, true); dnp3_poll_id_t poll_id; - dnp3_param_error_t err = dnp3_master_channel_add_poll(channel, association_id, poll_request, 5000, &poll_id); - dnp3_read_request_destroy(poll_request); + dnp3_param_error_t err = dnp3_master_channel_add_poll(channel, association_id, event_scan, 5000, &poll_id); + dnp3_read_request_destroy(event_scan); // ANCHOR_END: add_poll if (err) { printf("unable to add poll: %s\n", dnp3_param_error_to_string(err));