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..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::ClassScan(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::ClassScan(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 b7925e27..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::ClassScan(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/handler.rs b/dnp3/src/master/handler.rs index 444d0124..0c4ba503 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; @@ -307,13 +307,16 @@ 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, - 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..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::ClassScan(Classes::all()) + ReadRequest::new().add_classes(Classes::all()) } #[test] diff --git a/dnp3/src/master/request.rs b/dnp3/src/master/request.rs index 379d241e..b58c6f1e 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,168 @@ 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(()) } -} -impl OneByteRangeScan { - /// construct a `OneByteRangeScan` from its fields - pub fn new(variation: Variation, start: u8, stop: u8) -> Self { - Self { - variation, - start, - stop, - } + /// 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)) } - pub(crate) fn write(self, writer: &mut HeaderWriter) -> Result<(), scursor::WriteError> { - writer.write_range_only(self.variation, self.start, self.stop) + fn read_headers(self) -> impl Iterator { + self.variations() + .map(|variation| ReadHeader::AllObjects { variation }) } } -impl TwoByteRangeScan { - /// construct a `TwoByteRangeScan` from its fields - pub fn new(variation: Variation, start: u16, stop: u16) -> Self { - Self { - variation, - start, - stop, - } - } - - pub(crate) fn write(self, writer: &mut HeaderWriter) -> Result<(), scursor::WriteError> { - writer.write_range_only(self.variation, self.start, self.stop) - } +/// The object headers of a READ, for one-time reads and polls +/// +/// 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; +/// # 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, } -impl AllObjectsScan { - /// construct an `AllObjectsScan` from the variation - pub fn new(variation: Variation) -> Self { - Self { variation } - } - - pub(crate) fn write(self, writer: &mut HeaderWriter) -> Result<(), scursor::WriteError> { - writer.write_all_objects_header(self.variation) - } +/// Single headers and class scans don't allocate, since polls clone their request every period +#[derive(Clone, Debug, Default)] +enum ReadInner { + #[default] + Empty, + Single(ReadHeader), + ClassScan(Classes), + Multiple(Vec), } -impl OneByteLimitedCountScan { - /// construct an [`OneByteLimitedCountScan`] from the variation - pub fn new(variation: Variation, count: u8) -> Self { - Self { variation, count } +impl ReadRequest { + /// Construct a request with no headers + pub fn new() -> Self { + Default::default() } - pub(crate) fn write(self, writer: &mut HeaderWriter) -> Result<(), scursor::WriteError> { - writer.write_limited_count(self.variation, self.count) + /// 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::Empty => ReadInner::ClassScan(classes), + inner => { + let mut headers = inner.into_headers(); + headers.extend(classes.read_headers()); + ReadInner::Multiple(headers) + } + }; + Self { inner } } -} -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) - } -} - -/// 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 an 8-bit start/stop header (0x00) with the specified variation + pub fn add_one_byte_range(self, variation: Variation, start: u8, stop: u8) -> Self { + self.add(ReadHeader::Range8 { + 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 a 16-bit start/stop header (0x01) with the specified variation + pub fn add_two_byte_range(self, variation: Variation, start: u16, stop: u16) -> Self { + self.add(ReadHeader::Range16 { + variation, + start, + stop, + }) } - /// construct an all objects [`ReadHeader`] - pub fn all_objects(variation: Variation) -> Self { - ReadHeader::AllObjects(AllObjectsScan::new(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::LimitedCount8 { 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 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 two byte limited count scan [`ReadHeader`] - pub fn two_byte_limited_count(variation: Variation, count: u16) -> Self { - ReadHeader::LimitedCount16(TwoByteLimitedCountScan::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)) } - 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, + pub(crate) fn format(&self, writer: &mut HeaderWriter) -> Result<(), TaskErrorKind> { + match &self.inner { + ReadInner::Empty => {} + 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(()) } - /// 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 add(self, header: ReadHeader) -> Self { + let inner = match self.inner { + ReadInner::Empty => ReadInner::Single(header), + inner => { + let mut headers = inner.into_headers(); + headers.push(header); + ReadInner::Multiple(headers) + } + }; + Self { inner } } +} - pub(crate) fn format(self, writer: &mut HeaderWriter) -> Result<(), scursor::WriteError> { +impl ReadInner { + fn into_headers(self) -> Vec { 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), + ReadInner::Empty => Vec::new(), + ReadInner::Single(header) => vec![header], + ReadInner::ClassScan(classes) => classes.read_headers().collect(), + ReadInner::Multiple(headers) => 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 +422,53 @@ 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 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(ReadHeader::all_objects(variation).into()) + self.add(Header::Read(ReadHeader::AllObjects { variation })) } - /// Add 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()) + /// Add an 8-bit start/stop header (0x00) with the specified variation + pub fn add_one_byte_range(self, variation: Variation, start: u8, stop: u8) -> Self { + self.add(Header::Read(ReadHeader::Range8 { + variation, + start, + stop, + })) } - /// Add 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()) + /// Add a 16-bit start/stop header (0x01) with the specified variation + pub fn add_two_byte_range(self, variation: Variation, start: u16, stop: u16) -> Self { + 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 +510,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 +1169,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 +1189,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 +1197,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 +1210,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::new().add_all_objects(Variation::Group60Var1); + for request in [ + ReadRequest::new().add_all_objects(G0V0), + 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_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), ] { - 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_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), + ] { 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 +1266,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 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, 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 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 +1338,44 @@ 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() + /// 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) -> Vec { + match op { + ReadOp::Header(header) => vec![model_header(header)], + ReadOp::DeviceAttribute(variation, set) => { + vec![((0, variation), Qualifier::Range8(set, set))] } // the event classes first, then class 0 - ReadRequest::ClassScan(classes) => [ + ReadOp::Classes(classes) => [ (classes.events.class1, (60, 2)), (classes.events.class2, (60, 3)), (classes.events.class3, (60, 4)), @@ -1408,6 +1388,40 @@ mod tests { } } + 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, + }) => request.add_one_byte_range(variation, start, stop), + ReadOp::Header(ReadHeader::Range16 { + variation, + start, + stop, + }) => request.add_two_byte_range(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 { [vec![group, var], qualifier.bytes()].concat() } @@ -1508,34 +1522,41 @@ 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)) + 4 => read_header().prop_map(ReadOp::Header), + 1 => (count(vec![0, 254, 255]), any::()) + .prop_map(|(variation, set)| ReadOp::DeviceAttribute(variation, set)), + 1 => any::<[bool; 4]>().prop_map(|[class0, class1, class2, class3]| { + ReadOp::Classes(Classes::new(class0, EventClasses::new(class1, class2, class3))) }), ] } @@ -1543,6 +1564,7 @@ mod tests { #[derive(Clone, Debug)] enum Item { Read(ReadHeader), + Classes(Classes), /// the time and interval of a g50v2 Freeze(u64, u32), } @@ -1550,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::()], @@ -1558,23 +1586,30 @@ 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_one_byte_range(variation, start, stop), + Item::Read(ReadHeader::Range16 { + variation, + start, + stop, + }) => request.add_two_byte_range(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::Classes(classes) => request.add_classes(classes), Item::Freeze(time, interval) => { - headers.add_time_and_interval(Timestamp::new(time), interval) + request.add_time_and_interval(Timestamp::new(time), interval) } } } @@ -1596,7 +1631,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()) ); @@ -1611,11 +1647,14 @@ 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( + 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(&request); + let model = model_request(&ops); if model.iter().any(|(group_var, _)| *group_var == (0, 0)) { prop_assert_eq!( result, @@ -1639,18 +1678,18 @@ mod tests { prop_assert_eq!(parse_read(written), expected); } - /// Generic request headers are written as the READ 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] 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() @@ -1668,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/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/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 fd70a9e7..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::ClassScan(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 a173a708..6a4d9ee6 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::new().add_classes(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::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::ClassScan(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::ClassScan(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::ClassScan(Classes::class0()), + ReadRequest::new().add_classes(Classes::class0()), Duration::from_secs(1), ) .await; @@ -1092,10 +1092,11 @@ 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::new().add_classes(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 +1378,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::new().add_classes(Classes::class0())) .await }); next_request(&mut harness, 0, FunctionCode::Read).await; @@ -1589,7 +1590,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), @@ -1617,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) ); @@ -1628,7 +1629,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) @@ -1637,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 af7bbb6c..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::ClassScan(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::ClassScan(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::ClassScan(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::ClassScan(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::ClassScan(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 3ed4761a..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::ClassScan(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::ClassScan(Classes::class0())) + .read(ReadRequest::new().add_classes(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::new().add_classes(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..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::ClassScan(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::ClassScan(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 f2e7ea1a..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::ClassScan(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::ClassScan(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 6bb0d769..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::ClassScan(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 20baf10d..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::ClassScan(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 5d7875de..fb89fb5c 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,17 +228,6 @@ fn variation(source: &mut Source) -> Variation { Variation::lookup(source.u8(), source.u8()).unwrap_or(Variation::Group0(0)) } -fn read_header(source: &mut Source) -> ReadHeader { - 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()), - } -} - fn event_classes(source: &mut Source) -> EventClasses { EventClasses::new(source.bool(), source.bool(), source.bool()) } @@ -248,11 +237,19 @@ 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(ReadRequest::new(), |request, _| { + let variation = variation(source); + match source.u8() % 7 { + 0 => request.add_all_objects(variation), + 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())), + _ => request.add_classes(classes(source)), + } + }) } fn attr_value(source: &mut Source) -> OwnedAttrValue { @@ -277,21 +274,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_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( Timestamp::new(source.u64()), source.u32(), )), - _ => headers.add_attribute(attribute(source)), + _ => request.add_attribute(attribute(source)), } }) } @@ -502,7 +499,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/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 1bd830d5..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::ClassScan(Classes::class123()), + ReadRequest::new().add_classes(Classes::class123()), Duration::from_secs(5), ) .await?; @@ -453,23 +453,25 @@ 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::multiple_headers(&[ - ReadHeader::all_objects(Variation::Group10Var0), - ReadHeader::all_objects(Variation::Group40Var0), - ])) + .read( + ReadRequest::new() + .add_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::new() + .add_all_objects(Variation::Group20Var0) + .add_all_objects(Variation::Group21Var0), + ) .await?; } "cmd" => { @@ -520,54 +522,51 @@ 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" => { // 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 } "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 } "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 5f779f9b..ea130665 100644 --- a/ffi/bindings/c/master_example.c +++ b/ffi/bindings/c/master_example.c @@ -294,10 +294,11 @@ 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 *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_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)); @@ -347,8 +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_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_create(); + 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, @@ -356,13 +357,13 @@ 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_create(); + 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, @@ -370,13 +371,13 @@ 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_create(); + 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, @@ -384,7 +385,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) { @@ -466,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, @@ -481,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, @@ -499,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, @@ -516,8 +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_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_create(); + 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, @@ -527,7 +528,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 +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_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_create(); + 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, @@ -558,7 +559,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..912761c2 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::Request::class_request(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,20 +282,20 @@ 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); + dnp3::ReadRequest request; + request.add_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); - request.add_all_objects_header(dnp3::Variation::group40_var0); + dnp3::ReadRequest request; + 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::Request request; - request.add_all_objects_header(dnp3::Variation::group20_var0); - request.add_all_objects_header(dnp3::Variation::group21_var0); + dnp3::ReadRequest request; + 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") { @@ -333,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") { @@ -348,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::Request request; - request.add_specific_attribute(dnp3::attribute_variations::all_attributes_request, 0); + dnp3::ReadRequest request; + request.add_device_attribute(dnp3::attribute_variations::all_attributes_request, 0); channel.read(assoc, request, create_read_callback("rda")); // ANCHOR_END: read_attributes } @@ -367,8 +368,8 @@ 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); + dnp3::ReadRequest request; + 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/c/smoke_test.c b/ffi/bindings/c/smoke_test.c index 02c53874..df636488 100644 --- a/ffi/bindings/c/smoke_test.c +++ b/ffi/bindings/c/smoke_test.c @@ -300,9 +300,10 @@ 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_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_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..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::Request::class_request(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 5c0de5bc..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, Request.ClassRequest(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 63d0a814..156b2f6e 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, Request.ClassRequest(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,24 +239,24 @@ private static async Task RunOneCommand(MasterChannel channel, Associati } case "rao": { - var request = new Request(); - request.AddAllObjectsHeader(Variation.Group40Var0); + var request = new ReadRequest(); + request.AddAllObjects(Variation.Group40Var0); await channel.Read(association, request); return Success; } case "rmo": { - var request = new Request(); - request.AddAllObjectsHeader(Variation.Group10Var0); - request.AddAllObjectsHeader(Variation.Group40Var0); + var request = new ReadRequest(); + request.AddAllObjects(Variation.Group10Var0); + request.AddAllObjects(Variation.Group40Var0); await channel.Read(association, request); return Success; } case "rco": { - var request = new Request(); - request.AddAllObjectsHeader(Variation.Group20Var0); - request.AddAllObjectsHeader(Variation.Group21Var0); + var request = new ReadRequest(); + request.AddAllObjects(Variation.Group20Var0); + request.AddAllObjects(Variation.Group21Var0); await channel.Read(association, request); return Success; } @@ -310,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; @@ -319,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; } @@ -327,15 +329,15 @@ 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; } case "rda": { // ANCHOR: read_attributes - var request = new Request(); - request.AddSpecificAttribute(AttributeVariations.AllAttributesRequest, 0); + var request = new ReadRequest(); + request.AddDeviceAttribute(AttributeVariations.AllAttributesRequest, 0); await channel.Read(association, request); // ANCHOR_END: read_attributes return Success; @@ -351,8 +353,8 @@ private static async Task RunOneCommand(MasterChannel channel, Associati } case "ral": { - var request = new Request(); - request.AddSpecificAttribute(AttributeVariations.ListOfVariations, 0); + var request = new ReadRequest(); + request.AddDeviceAttribute(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..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, Request.classRequest(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 1a7b832c..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 @@ -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, Request.classRequest(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,24 +297,24 @@ private static String runOneCommand(MasterChannel channel, AssociationId associa return success; case "rao": { - Request request = new Request(); - request.addAllObjectsHeader(Variation.GROUP40_VAR0); + ReadRequest request = new ReadRequest(); + request.addAllObjects(Variation.GROUP40_VAR0); channel.read(association, request).toCompletableFuture().get(); return success; } case "rmo": { - Request request = new Request(); - request.addAllObjectsHeader(Variation.GROUP10_VAR0); - request.addAllObjectsHeader(Variation.GROUP40_VAR0); + ReadRequest request = new ReadRequest(); + request.addAllObjects(Variation.GROUP10_VAR0); + request.addAllObjects(Variation.GROUP40_VAR0); channel.read(association, request).toCompletableFuture().get(); return success; } case "rco": { - Request request = new Request(); - request.addAllObjectsHeader(Variation.GROUP20_VAR0); - request.addAllObjectsHeader(Variation.GROUP21_VAR0); + ReadRequest request = new ReadRequest(); + 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,15 +386,15 @@ 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; } case "rda": { // ANCHOR: read_attributes - Request request = new Request(); - request.addSpecificAttribute(AttributeVariations.ALL_ATTRIBUTES_REQUEST, ubyte(0)); + ReadRequest request = new ReadRequest(); + request.addDeviceAttribute(AttributeVariations.ALL_ATTRIBUTES_REQUEST, ubyte(0)); channel.read(association, request).toCompletableFuture().get(); // ANCHOR_END: read_attributes return success; @@ -410,8 +410,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 = new ReadRequest(); + request.addDeviceAttribute(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..2cfcc6f3 100644 --- a/ffi/dnp3-ffi/src/request.rs +++ b/ffi/dnp3-ffi/src/request.rs @@ -5,127 +5,132 @@ // 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::master::{Headers, ReadHeader, ReadRequest}; -use dnp3::outstation::FreezeInterval; +use dnp3::app::Timestamp; +use dnp3::master::{Classes, EventClasses}; use std::ffi::CStr; use crate::ffi; -pub struct Request { - headers: Headers, +pub struct ReadRequest { + inner: dnp3::master::ReadRequest, } -impl Request { - fn new() -> Self { - Self { - headers: Default::default(), - } +impl ReadRequest { + pub(crate) fn clone_inner(&self) -> dnp3::master::ReadRequest { + self.inner.clone() } - 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::ReadRequest) -> dnp3::master::ReadRequest) { + self.inner = f(std::mem::take(&mut self.inner)); } +} - pub(crate) fn add_attribute(&mut self, attr: OwnedAttribute) { - self.headers.push_attr(attr); - } +pub struct Request { + inner: dnp3::master::Request, +} - pub(crate) fn add_time_and_interval(&mut self, time: Timestamp, interval: u32) { - self.headers - .push_freeze_interval(FreezeInterval::new(time, interval)); +impl Request { + pub(crate) fn clone_inner(&self) -> dnp3::master::Request { + self.inner.clone() } - pub(crate) fn build_read_request(&self) -> ReadRequest { - self.headers.to_read_request() + /// 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(crate) fn build_headers(&self) -> Headers { - self.headers.clone() - } +pub unsafe fn read_request_create() -> *mut ReadRequest { + Box::into_raw(Box::new(ReadRequest { + inner: dnp3::master::ReadRequest::new(), + })) } -pub unsafe fn request_create() -> *mut Request { - let request = Box::new(Request::new()); - Box::into_raw(request) +pub unsafe fn read_request_destroy(request: *mut ReadRequest) { + if !request.is_null() { + drop(Box::from_raw(request)); + } } -pub unsafe fn request_new_class( +pub(crate) unsafe fn read_request_add_classes( + request: *mut ReadRequest, class0: bool, class1: bool, 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)); +) { + if let Some(request) = request.as_mut() { + let classes = Classes::new(class0, EventClasses::new(class1, class2, class3)); + request.update(|r| r.add_classes(classes)); } - - let request = Box::new(request); - Box::into_raw(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) +pub(crate) unsafe fn read_request_add_device_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 unsafe fn request_new_one_byte_range( +pub(crate) unsafe fn read_request_add_one_byte_range( + request: *mut ReadRequest, variation: ffi::Variation, 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) +) { + if let Some(request) = request.as_mut() { + request.update(|r| r.add_one_byte_range(variation.into(), start, stop)); + } } -pub unsafe fn request_new_two_byte_range( +pub(crate) unsafe fn read_request_add_two_byte_range( + request: *mut ReadRequest, variation: ffi::Variation, start: u16, stop: u16, -) -> *mut Request { - let mut request = Request::new(); - request.add_read_header(ReadHeader::two_byte_range(variation.into(), start, stop)); +) { + if let Some(request) = request.as_mut() { + request.update(|r| r.add_two_byte_range(variation.into(), start, stop)); + } +} - let request = Box::new(request); - Box::into_raw(request) +pub(crate) unsafe fn read_request_add_all_objects( + request: *mut ReadRequest, + variation: ffi::Variation, +) { + if let Some(request) = request.as_mut() { + request.update(|r| r.add_all_objects(variation.into())); + } } -pub unsafe fn request_new_one_byte_limited_count( +pub(crate) unsafe fn read_request_add_one_byte_limited_count( + request: *mut ReadRequest, 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) +) { + if let Some(request) = request.as_mut() { + request.update(|r| r.add_one_byte_limited_count(variation.into(), count)); + } } -pub unsafe fn request_new_two_byte_limited_count( +pub(crate) unsafe fn read_request_add_two_byte_limited_count( + request: *mut ReadRequest, variation: ffi::Variation, count: u16, -) -> *mut Request { - let mut request = Request::new(); - request.add_read_header(ReadHeader::two_byte_limited_count(variation.into(), count)); +) { + if let Some(request) = request.as_mut() { + request.update(|r| r.add_two_byte_limited_count(variation.into(), count)); + } +} - let request = Box::new(request); - Box::into_raw(request) +pub unsafe fn request_create() -> *mut Request { + Box::into_raw(Box::new(Request { + inner: dnp3::master::Request::new(), + })) } pub unsafe fn request_destroy(request: *mut Request) { @@ -134,107 +139,105 @@ pub unsafe fn request_destroy(request: *mut Request) { } } -pub(crate) unsafe fn request_add_one_byte_range_header( +pub(crate) unsafe fn request_add_classes( 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, + class0: bool, + class1: bool, + class2: bool, + class3: bool, ) { if let Some(request) = request.as_mut() { - request.add_read_header(ReadHeader::one_byte_range( - Variation::Group0(variation), - set, - set, - )); + let classes = Classes::new(class0, EventClasses::new(class1, class2, class3)); + request.update(|r| r.add_classes(classes)); } } 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_two_byte_range_header( +pub(crate) unsafe fn request_add_one_byte_range( request: *mut Request, variation: ffi::Variation, - start: u16, - stop: u16, + start: u8, + stop: u8, ) { if let Some(request) = request.as_mut() { - request.add_read_header(ReadHeader::two_byte_range(variation.into(), start, stop)); + request.update(|r| r.add_one_byte_range(variation.into(), start, stop)); } } -pub(crate) unsafe fn request_add_all_objects_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.add_read_header(ReadHeader::all_objects(variation.into())); + request.update(|r| r.add_two_byte_range(variation.into(), start, stop)); } } -pub unsafe fn request_add_one_byte_limited_count_header( +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( 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( 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..e5a986d1 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())? @@ -454,13 +454,14 @@ 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()?; 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..1bfe8d6e 100644 --- a/ffi/dnp3-schema/src/master/request.rs +++ b/ffi/dnp3-schema/src/master/request.rs @@ -8,145 +8,108 @@ 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")?; + let read_request = lib.declare_class("read_request")?; let constructor = lib - .define_constructor(request.clone())? - .doc("Create a new request")? + .define_constructor(read_request.clone())? + .doc("Create a new read request with no headers")? .build()?; - let request_new_class_fn = lib - .define_function("request_new_class")? + 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( - 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 asking for classes") + .details("The headers ask for events in classes 1, 2 and 3, then class 0."), )? - .build_static("class_request")?; + .build()?; - let request_new_all_objects_fn = lib - .define_function("request_new_all_objects")? + let add_device_attribute_fn = lib + .define_method("add_device_attribute", read_request.clone())? .param( "variation", - shared.variation_enum.clone(), - "Variation to ask for", - )? - .returns( - request.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()}.") + Primitive::U8, + "Variation of the device attribute, 1 to 255 (254 reads every attribute of the set)", )? - .build_static("all_objects")?; - - let request_new_one_byte_range_fn = lib - .define_function("request_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( - request.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()}.") + "set", + Primitive::U8, + "The set (point) to which the attribute belongs", )? - .build_static("one_byte_range")?; + .doc("Add a header that reads a specific device attribute (group 0)")? + .build()?; - let request_new_two_byte_range_fn = lib - .define_function("request_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( - request.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()}.") - )? - .build_static("two_byte_range")?; + let header_methods = define_header_methods(lib, shared, &read_request)?; - let request_new_one_byte_limited_count_fn = lib - .define_function("request_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", - )? + let mut builder = lib + .define_class(&read_request)? + .constructor(constructor)? + .destructor(destructor)? + .method(add_classes_fn)?; + for method in header_methods { + builder = builder.method(method)?; + } + let read_request = builder + .method(add_device_attribute_fn)? .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("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_static("one_byte_limited_count")?; + .build()?; - let request_new_two_byte_limited_count_fn = lib - .define_function("request_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", - )? - .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()}.") - )? - .build_static("two_byte_limited_count")?; + Ok(read_request) +} - let destructor = lib - .define_destructor( - request.clone(), - "Destroy a request created with {class:request.[constructor]} or {class:request.class_request()}." - )?; +fn define_request(lib: &mut LibraryBuilder, shared: &SharedDefinitions) -> BackTraced { + let request = lib.declare_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", + let constructor = lib + .define_constructor(request.clone())? + .doc("Create a new request with no headers")? + .build()?; + + 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")? + .doc( + doc("Add headers naming classes") + .details("The headers name events in classes 1, 2 and 3, then class 0."), )? - .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 @@ -177,8 +140,56 @@ pub(crate) fn define( ))? .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 header_methods = define_header_methods(lib, shared, &request)?; + + let mut builder = lib + .define_class(&request)? + .constructor(constructor)? + .destructor(destructor)? + .method(add_classes_fn)?; + 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 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", class.clone())? .param( "variation", shared.variation_enum.clone(), @@ -186,11 +197,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", class.clone())? .param( "variation", shared.variation_enum.clone(), @@ -198,83 +209,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", 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", 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", 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"), - )? - .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.") - )? + .doc("Add a two-byte limited count header")? .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..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: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")? 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