Skip to main content

hart_link/operation/
mod.rs

1//! Application-level requests and responses.
2
3mod 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/// Logical HART operation number.
48#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
49pub struct CommandCode(u16);
50
51impl CommandCode {
52    /// Creates a number in the full 16-bit command space.
53    pub const fn new(value: u16) -> Self {
54        Self(value)
55    }
56
57    /// Returns the numeric value.
58    pub const fn get(self) -> u16 {
59        self.0
60    }
61
62    /// Reports whether the number must be carried through Command 31.
63    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/// Application codec error.
81#[derive(Debug, Clone, PartialEq, Error)]
82pub enum OperationError {
83    /// The response names a different command.
84    #[error("expected command {expected}, received command {actual}")]
85    CommandMismatch {
86        /// Expected logical number.
87        expected: u16,
88        /// Actual logical number.
89        actual: u16,
90    },
91    /// The device returned an error or warning that prevents payload decoding.
92    #[error("device returned response code {code} and status 0x{status:02x}")]
93    DeviceStatus {
94        /// HART response code.
95        code: u8,
96        /// Device status bits.
97        status: u8,
98    },
99    /// The first response byte is a communication-error summary, not an application code.
100    #[error("device reported communication status 0x{summary:02x} and status 0x{status:02x}")]
101    CommunicationStatus {
102        /// Communication-error summary with its most significant bit set.
103        summary: u8,
104        /// Second status byte retained for diagnostics.
105        status: u8,
106    },
107    /// The payload is too short for the declared format.
108    #[error("field {field} is truncated at offset {offset}")]
109    Truncated {
110        /// Application field name.
111        field: &'static str,
112        /// Read offset.
113        offset: usize,
114    },
115    /// Unexpected data remains after decoding.
116    #[error("{0} unexpected bytes remain after decoding")]
117    TrailingBytes(usize),
118    /// A value cannot be represented by the protocol type.
119    #[error("field {0} is outside the allowed range")]
120    InvalidValue(&'static str),
121    /// The request length does not match the explicit command contract.
122    #[error("command {command} does not accept a {actual}-byte request")]
123    RequestLength {
124        /// Logical command number.
125        command: u16,
126        /// Actual length.
127        actual: usize,
128    },
129    /// Link-layer error.
130    #[error(transparent)]
131    Wire(#[from] WireError),
132}
133
134/// Request before conversion into a link-layer frame.
135#[derive(Debug, Clone, PartialEq, Eq)]
136pub struct Request {
137    /// Device address.
138    pub address: Address,
139    /// Logical command number.
140    pub command: CommandCode,
141    /// Request data without the expanded-command service number.
142    pub data: Vec<u8>,
143    /// Preamble count used for the initial transmission.
144    pub preambles: u8,
145    /// Link-layer header extension.
146    pub frame_expansion: Vec<u8>,
147    /// Physical mode of the generated frame.
148    pub physical_layer: PhysicalLayer,
149    /// Explicit automatic-retry safety, or `None` for registry lookup and conservative fallback.
150    pub retry_safety: Option<OperationSafety>,
151}
152
153impl Request {
154    /// Creates a request with five preambles.
155    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    /// Creates a request and immediately checks its wire-size constraints.
168    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    /// Sets the preamble count.
179    pub const fn with_preambles(mut self, preambles: u8) -> Self {
180        self.preambles = preambles;
181        self
182    }
183
184    /// Sets the physical mode of the frame.
185    pub const fn with_physical_layer(mut self, physical_layer: PhysicalLayer) -> Self {
186        self.physical_layer = physical_layer;
187        self
188    }
189
190    /// Sets up to three link-layer header-extension bytes.
191    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    /// Declares whether repeating this exact request can safely occur after an uncertain result.
204    pub const fn with_retry_safety(mut self, safety: OperationSafety) -> Self {
205        self.retry_safety = Some(safety);
206        self
207    }
208
209    /// Validates frame-size fields without cloning or encoding request data.
210    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    /// Converts the request into a link-layer frame.
225    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/// Validated device response with a normalized command number.
255#[derive(Debug, Clone, PartialEq, Eq)]
256pub struct DeviceReply {
257    /// Address carried by the response.
258    pub address: Address,
259    /// Logical command number.
260    pub command: CommandCode,
261    /// Operation result code.
262    pub response_code: u8,
263    /// Device status bits.
264    pub device_status: u8,
265    /// Application payload without service bytes.
266    pub data: Vec<u8>,
267    /// Whether the response was an unsolicited message.
268    pub burst: bool,
269    /// Physical mode of the received frame.
270    pub physical_layer: PhysicalLayer,
271    /// Preamble count of the received frame.
272    pub response_preambles: u8,
273    /// Link-layer header extension bytes.
274    pub frame_expansion: Vec<u8>,
275}
276
277impl DeviceReply {
278    /// Decodes a response or unsolicited frame.
279    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    /// Validates the command and ensures that the device reported no error.
329    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    /// Validates only the logical command, preserving every response status for the caller.
347    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    /// Reports whether the first status byte is a link communication-error summary.
358    pub const fn has_communication_error(&self) -> bool {
359        self.response_code & 0x80 != 0
360    }
361
362    /// Reports an exact successful application response.
363    pub const fn is_success(&self) -> bool {
364        self.response_code == 0
365    }
366}
367
368/// Typed value accompanied by the exact device result bytes that allowed its decoding.
369#[derive(Debug, Clone, PartialEq)]
370pub struct CommandOutcome<T> {
371    /// Decoded command-specific value.
372    pub value: T,
373    /// Original seven-bit application response code.
374    pub response_code: u8,
375    /// Original device-status byte.
376    pub device_status: u8,
377}
378
379impl<T> CommandOutcome<T> {
380    /// Reports whether the accepted result was accompanied by a warning.
381    pub const fn is_warning(&self) -> bool {
382        self.response_code != 0
383    }
384}
385
386/// Typed operation performed on a device.
387pub trait Operation {
388    /// Result of successful response decoding.
389    type Output;
390
391    /// Returns the logical command number.
392    fn command(&self) -> CommandCode;
393
394    /// Returns the retry semantics used when building a request.
395    ///
396    /// Unknown commands default to [`OperationSafety::Action`]. Vendor codecs should override
397    /// this method only when their exact operation semantics are known.
398    fn retry_safety(&self) -> OperationSafety {
399        command_descriptor(self.command()).map_or(OperationSafety::Action, |entry| entry.safety)
400    }
401
402    /// Encodes request data.
403    fn encode_request(&self, writer: &mut PayloadWriter) -> Result<(), OperationError>;
404
405    /// Decodes application response data.
406    fn decode_reply(&self, reply: &DeviceReply) -> Result<Self::Output, OperationError>;
407
408    /// Decodes a success or one of the explicitly accepted command-specific warning codes.
409    ///
410    /// Warning meaning is not inferred from a broad numeric range. Callers should obtain the
411    /// accepted list from the applicable command specification or exact-revision DeviceInfo.
412    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    /// Creates a complete request for the supplied address.
440    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/// Raw operation with no assumptions about the vendor payload format.
449#[derive(Debug, Clone, PartialEq, Eq)]
450pub struct RawOperation {
451    command: CommandCode,
452    data: Vec<u8>,
453    retry_safety: OperationSafety,
454}
455
456impl RawOperation {
457    /// Creates an arbitrary standard or expanded command.
458    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    /// Creates a read-only vendor command that may be retried and coalesced safely.
467    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    /// Creates an idempotent write that may be repeated after an uncertain result.
472    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    /// Creates a one-shot action that is never retried after a completed transmission.
477    pub fn action(command: impl Into<CommandCode>, data: impl Into<Vec<u8>>) -> Self {
478        Self::new(command, data)
479    }
480
481    /// Declares retry semantics for a vendor operation whose exact behavior is known.
482    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/// Raw command validated against a known request length.
528#[derive(Debug, Clone, PartialEq, Eq)]
529pub struct CheckedOperation {
530    command: CommandCode,
531    data: Vec<u8>,
532    retry_safety: OperationSafety,
533}
534
535impl CheckedOperation {
536    /// Validates the length against the explicit registry and preserves the original data.
537    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    /// Overrides retry semantics after validating them against the applicable specification.
564    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}