1mod codec;
4mod configuration;
5mod control;
6mod diagnostics;
7mod identity;
8mod information;
9mod process;
10mod text;
11
12use alloc::vec::Vec;
13
14use thiserror::Error;
15
16use crate::{
17 catalog::{OperationSafety, command_descriptor},
18 wire::{Address, Frame, FrameKind, PhysicalLayer, WireError},
19};
20
21pub use codec::{PayloadReader, PayloadWriter};
22pub use configuration::{
23 LoopConfiguration, PollingAddress, ReadLoopConfiguration, WriteLegacyPollingAddress,
24 WritePollingAddress,
25};
26pub use control::{
27 ActionCommand, AnalogTrim, EepromControl, FixedCurrent, RangeValues, SetDamping, SetRange,
28 WritePrimaryUnit, WriteTransferFunction,
29};
30pub use diagnostics::{AdditionalStatus, ReadAdditionalStatus};
31pub use identity::ReadIdentity;
32pub use identity::{DeviceIdentity, ReadDeviceIdentity};
33pub use information::{
34 ReadFinalAssemblyNumber, ReadOutputInformation, ReadTransducerInformation,
35 WriteFinalAssemblyNumber,
36};
37pub use process::{
38 DeviceVariable, DeviceVariables, DynamicValues, LoopSignal, MeasuredValue, PrimaryValue,
39 ReadDeviceVariables, ReadDynamicValues, ReadLoopSignal, ReadPrimaryValue,
40 ReadSelectedVariables, ReadVariableClassifications, SelectedVariable, VariableClassifications,
41};
42pub use text::{
43 DeviceDate, ReadLongTag, ReadMessage, ReadTagDescriptorDate, TagDescriptorDate, WriteLongTag,
44 WriteMessage, WriteTagDescriptorDate, pack_text, unpack_text,
45};
46
47#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
49pub struct CommandCode(u16);
50
51impl CommandCode {
52 pub const fn new(value: u16) -> Self {
54 Self(value)
55 }
56
57 pub const fn get(self) -> u16 {
59 self.0
60 }
61
62 pub const fn is_expanded(self) -> bool {
64 self.0 > u8::MAX as u16
65 }
66}
67
68impl From<u8> for CommandCode {
69 fn from(value: u8) -> Self {
70 Self(u16::from(value))
71 }
72}
73
74impl From<u16> for CommandCode {
75 fn from(value: u16) -> Self {
76 Self(value)
77 }
78}
79
80#[derive(Debug, Clone, PartialEq, Error)]
82pub enum OperationError {
83 #[error("expected command {expected}, received command {actual}")]
85 CommandMismatch {
86 expected: u16,
88 actual: u16,
90 },
91 #[error("device returned response code {code} and status 0x{status:02x}")]
93 DeviceStatus {
94 code: u8,
96 status: u8,
98 },
99 #[error("device reported communication status 0x{summary:02x} and status 0x{status:02x}")]
101 CommunicationStatus {
102 summary: u8,
104 status: u8,
106 },
107 #[error("field {field} is truncated at offset {offset}")]
109 Truncated {
110 field: &'static str,
112 offset: usize,
114 },
115 #[error("{0} unexpected bytes remain after decoding")]
117 TrailingBytes(usize),
118 #[error("field {0} is outside the allowed range")]
120 InvalidValue(&'static str),
121 #[error("command {command} does not accept a {actual}-byte request")]
123 RequestLength {
124 command: u16,
126 actual: usize,
128 },
129 #[error(transparent)]
131 Wire(#[from] WireError),
132}
133
134#[derive(Debug, Clone, PartialEq, Eq)]
136pub struct Request {
137 pub address: Address,
139 pub command: CommandCode,
141 pub data: Vec<u8>,
143 pub preambles: u8,
145 pub frame_expansion: Vec<u8>,
147 pub physical_layer: PhysicalLayer,
149 pub retry_safety: Option<OperationSafety>,
151}
152
153impl Request {
154 pub fn new(address: Address, command: impl Into<CommandCode>, data: Vec<u8>) -> Self {
156 Self {
157 address,
158 command: command.into(),
159 data,
160 preambles: 5,
161 frame_expansion: Vec::new(),
162 physical_layer: PhysicalLayer::Fsk,
163 retry_safety: None,
164 }
165 }
166
167 pub fn try_new(
169 address: Address,
170 command: impl Into<CommandCode>,
171 data: impl Into<Vec<u8>>,
172 ) -> Result<Self, OperationError> {
173 let request = Self::new(address, command, data.into());
174 request.validate()?;
175 Ok(request)
176 }
177
178 pub const fn with_preambles(mut self, preambles: u8) -> Self {
180 self.preambles = preambles;
181 self
182 }
183
184 pub const fn with_physical_layer(mut self, physical_layer: PhysicalLayer) -> Self {
186 self.physical_layer = physical_layer;
187 self
188 }
189
190 pub fn with_frame_expansion(
192 mut self,
193 expansion: impl Into<Vec<u8>>,
194 ) -> Result<Self, OperationError> {
195 let expansion = expansion.into();
196 if expansion.len() > 3 {
197 return Err(OperationError::InvalidValue("frame expansion length"));
198 }
199 self.frame_expansion = expansion;
200 Ok(self)
201 }
202
203 pub const fn with_retry_safety(mut self, safety: OperationSafety) -> Self {
205 self.retry_safety = Some(safety);
206 self
207 }
208
209 pub fn validate(&self) -> Result<(), OperationError> {
211 let service_bytes = usize::from(self.command.is_expanded()) * 2;
212 let payload_len = self.data.len().saturating_add(service_bytes);
213 if payload_len > usize::from(u8::MAX) {
214 return Err(OperationError::Wire(WireError::PayloadLength(payload_len)));
215 }
216 if self.frame_expansion.len() > 3 {
217 return Err(OperationError::Wire(WireError::ExpansionLength(
218 self.frame_expansion.len(),
219 )));
220 }
221 Ok(())
222 }
223
224 pub fn to_frame(&self) -> Result<Frame, OperationError> {
226 self.validate()?;
227 let (wire_command, payload) = if self.command.is_expanded() {
228 let mut payload = Vec::with_capacity(self.data.len() + 2);
229 payload.extend_from_slice(&self.command.get().to_be_bytes());
230 payload.extend_from_slice(&self.data);
231 (31, payload)
232 } else {
233 (
234 u8::try_from(self.command.get())
235 .map_err(|_| OperationError::InvalidValue("standard command number"))?,
236 self.data.clone(),
237 )
238 };
239 let frame = Frame {
240 preambles: self.preambles,
241 kind: FrameKind::Request,
242 physical_layer: self.physical_layer,
243 address: self.address,
244 expansion: self.frame_expansion.clone(),
245 wire_command,
246 payload,
247 repair: None,
248 };
249 frame.delimiter()?;
250 Ok(frame)
251 }
252}
253
254#[derive(Debug, Clone, PartialEq, Eq)]
256pub struct DeviceReply {
257 pub address: Address,
259 pub command: CommandCode,
261 pub response_code: u8,
263 pub device_status: u8,
265 pub data: Vec<u8>,
267 pub burst: bool,
269 pub physical_layer: PhysicalLayer,
271 pub response_preambles: u8,
273 pub frame_expansion: Vec<u8>,
275}
276
277impl DeviceReply {
278 pub fn from_frame(frame: Frame) -> Result<Self, OperationError> {
280 let Frame {
281 preambles,
282 kind,
283 physical_layer,
284 address,
285 expansion,
286 wire_command,
287 payload,
288 ..
289 } = frame;
290 if !matches!(kind, FrameKind::Response | FrameKind::Burst) {
291 return Err(OperationError::InvalidValue("response frame type"));
292 }
293 if payload.len() < 2 {
294 return Err(OperationError::Truncated {
295 field: "response code and status",
296 offset: payload.len(),
297 });
298 }
299 let response_code = payload[0];
300 let device_status = payload[1];
301 let (command, data_start) = if wire_command == 31 {
302 if payload.len() < 4 {
303 return Err(OperationError::Truncated {
304 field: "expanded command number",
305 offset: payload.len(),
306 });
307 }
308 (
309 CommandCode::new(u16::from_be_bytes([payload[2], payload[3]])),
310 4,
311 )
312 } else {
313 (CommandCode::from(wire_command), 2)
314 };
315 Ok(Self {
316 address,
317 command,
318 response_code,
319 device_status,
320 data: payload[data_start..].to_vec(),
321 burst: kind == FrameKind::Burst,
322 physical_layer,
323 response_preambles: preambles,
324 frame_expansion: expansion,
325 })
326 }
327
328 pub fn require_success(&self, expected: CommandCode) -> Result<(), OperationError> {
330 self.require_command(expected)?;
331 if self.response_code & 0x80 != 0 {
332 return Err(OperationError::CommunicationStatus {
333 summary: self.response_code,
334 status: self.device_status,
335 });
336 }
337 if self.response_code != 0 {
338 return Err(OperationError::DeviceStatus {
339 code: self.response_code,
340 status: self.device_status,
341 });
342 }
343 Ok(())
344 }
345
346 pub fn require_command(&self, expected: CommandCode) -> Result<(), OperationError> {
348 if self.command != expected {
349 return Err(OperationError::CommandMismatch {
350 expected: expected.get(),
351 actual: self.command.get(),
352 });
353 }
354 Ok(())
355 }
356
357 pub const fn has_communication_error(&self) -> bool {
359 self.response_code & 0x80 != 0
360 }
361
362 pub const fn is_success(&self) -> bool {
364 self.response_code == 0
365 }
366}
367
368#[derive(Debug, Clone, PartialEq)]
370pub struct CommandOutcome<T> {
371 pub value: T,
373 pub response_code: u8,
375 pub device_status: u8,
377}
378
379impl<T> CommandOutcome<T> {
380 pub const fn is_warning(&self) -> bool {
382 self.response_code != 0
383 }
384}
385
386pub trait Operation {
388 type Output;
390
391 fn command(&self) -> CommandCode;
393
394 fn retry_safety(&self) -> OperationSafety {
399 command_descriptor(self.command()).map_or(OperationSafety::Action, |entry| entry.safety)
400 }
401
402 fn encode_request(&self, writer: &mut PayloadWriter) -> Result<(), OperationError>;
404
405 fn decode_reply(&self, reply: &DeviceReply) -> Result<Self::Output, OperationError>;
407
408 fn decode_reply_accepting(
413 &self,
414 reply: &DeviceReply,
415 accepted_warnings: &[u8],
416 ) -> Result<CommandOutcome<Self::Output>, OperationError> {
417 reply.require_command(self.command())?;
418 if reply.has_communication_error() {
419 return Err(OperationError::CommunicationStatus {
420 summary: reply.response_code,
421 status: reply.device_status,
422 });
423 }
424 if reply.response_code != 0 && !accepted_warnings.contains(&reply.response_code) {
425 return Err(OperationError::DeviceStatus {
426 code: reply.response_code,
427 status: reply.device_status,
428 });
429 }
430 let mut accepted = reply.clone();
431 accepted.response_code = 0;
432 Ok(CommandOutcome {
433 value: self.decode_reply(&accepted)?,
434 response_code: reply.response_code,
435 device_status: reply.device_status,
436 })
437 }
438
439 fn request(&self, address: Address) -> Result<Request, OperationError> {
441 let mut writer = PayloadWriter::new();
442 self.encode_request(&mut writer)?;
443 Ok(Request::new(address, self.command(), writer.finish())
444 .with_retry_safety(self.retry_safety()))
445 }
446}
447
448#[derive(Debug, Clone, PartialEq, Eq)]
450pub struct RawOperation {
451 command: CommandCode,
452 data: Vec<u8>,
453 retry_safety: OperationSafety,
454}
455
456impl RawOperation {
457 pub fn new(command: impl Into<CommandCode>, data: impl Into<Vec<u8>>) -> Self {
459 Self {
460 command: command.into(),
461 data: data.into(),
462 retry_safety: OperationSafety::Action,
463 }
464 }
465
466 pub fn read(command: impl Into<CommandCode>, data: impl Into<Vec<u8>>) -> Self {
468 Self::new(command, data).with_retry_safety(OperationSafety::ReadOnly)
469 }
470
471 pub fn idempotent_write(command: impl Into<CommandCode>, data: impl Into<Vec<u8>>) -> Self {
473 Self::new(command, data).with_retry_safety(OperationSafety::IdempotentWrite)
474 }
475
476 pub fn action(command: impl Into<CommandCode>, data: impl Into<Vec<u8>>) -> Self {
478 Self::new(command, data)
479 }
480
481 pub const fn with_retry_safety(mut self, safety: OperationSafety) -> Self {
483 self.retry_safety = safety;
484 self
485 }
486}
487
488impl Operation for RawOperation {
489 type Output = DeviceReply;
490
491 fn command(&self) -> CommandCode {
492 self.command
493 }
494
495 fn retry_safety(&self) -> OperationSafety {
496 self.retry_safety
497 }
498
499 fn encode_request(&self, writer: &mut PayloadWriter) -> Result<(), OperationError> {
500 writer.bytes(&self.data);
501 Ok(())
502 }
503
504 fn request(&self, address: Address) -> Result<Request, OperationError> {
505 let maximum = if self.command.is_expanded() { 253 } else { 255 };
506 if self.data.len() > maximum {
507 return Err(OperationError::RequestLength {
508 command: self.command.get(),
509 actual: self.data.len(),
510 });
511 }
512 Ok(Request::new(address, self.command, self.data.clone())
513 .with_retry_safety(self.retry_safety))
514 }
515
516 fn decode_reply(&self, reply: &DeviceReply) -> Result<Self::Output, OperationError> {
517 if reply.command != self.command {
518 return Err(OperationError::CommandMismatch {
519 expected: self.command.get(),
520 actual: reply.command.get(),
521 });
522 }
523 Ok(reply.clone())
524 }
525}
526
527#[derive(Debug, Clone, PartialEq, Eq)]
529pub struct CheckedOperation {
530 command: CommandCode,
531 data: Vec<u8>,
532 retry_safety: OperationSafety,
533}
534
535impl CheckedOperation {
536 pub fn new(
538 command: impl Into<CommandCode>,
539 data: impl Into<Vec<u8>>,
540 ) -> Result<Self, OperationError> {
541 let command = command.into();
542 let data = data.into();
543 let fits_frame = if command.is_expanded() {
544 data.len() <= usize::from(u8::MAX) - 2
545 } else {
546 u8::try_from(data.len()).is_ok()
547 };
548 if !fits_frame || !crate::catalog::request_constraint(command).allows(data.len()) {
549 return Err(OperationError::RequestLength {
550 command: command.get(),
551 actual: data.len(),
552 });
553 }
554 let retry_safety = command_descriptor(command)
555 .map_or(OperationSafety::Action, |descriptor| descriptor.safety);
556 Ok(Self {
557 command,
558 data,
559 retry_safety,
560 })
561 }
562
563 pub const fn with_retry_safety(mut self, safety: OperationSafety) -> Self {
565 self.retry_safety = safety;
566 self
567 }
568}
569
570impl Operation for CheckedOperation {
571 type Output = DeviceReply;
572
573 fn command(&self) -> CommandCode {
574 self.command
575 }
576
577 fn retry_safety(&self) -> OperationSafety {
578 self.retry_safety
579 }
580
581 fn encode_request(&self, writer: &mut PayloadWriter) -> Result<(), OperationError> {
582 writer.bytes(&self.data);
583 Ok(())
584 }
585
586 fn decode_reply(&self, reply: &DeviceReply) -> Result<Self::Output, OperationError> {
587 if reply.command != self.command {
588 return Err(OperationError::CommandMismatch {
589 expected: self.command.get(),
590 actual: reply.command.get(),
591 });
592 }
593 Ok(reply.clone())
594 }
595}