tpt_protocol_core/lib.rs
1//! Core traits for the TPT Protocol ecosystem: FrameParser, StateValidator, DataNormalizer.
2#![no_std]
3#![cfg_attr(docsrs, feature(doc_cfg))]
4
5extern crate alloc;
6
7pub use error::Error;
8
9pub mod error;
10
11/// Parses raw bytes into a protocol-specific frame.
12///
13/// # Examples
14///
15/// ```rust
16/// use tpt_protocol_core::{FrameParser, Error};
17///
18/// struct MyParser;
19///
20/// impl FrameParser for MyParser {
21/// type Frame = Vec<u8>;
22///
23/// fn parse(&self, bytes: &[u8]) -> Result<Self::Frame, Error> {
24/// if bytes.len() < 4 {
25/// return Err(Error::parse("too short"));
26/// }
27/// Ok(bytes.to_vec())
28/// }
29/// }
30///
31/// let parser = MyParser;
32/// let frame = parser.parse(b"test").unwrap();
33/// assert_eq!(&frame, b"test");
34/// ```
35pub trait FrameParser {
36 type Frame: core::fmt::Debug + Clone + PartialEq;
37
38 fn parse(&self, bytes: &[u8]) -> Result<Self::Frame, Error>;
39
40 fn try_parse(&self, bytes: &[u8]) -> Result<Option<(Self::Frame, usize)>, Error> {
41 self.parse(bytes).map(|f| Some((f, bytes.len())))
42 }
43}
44
45/// Validates the health/state of a protocol connection.
46///
47/// # Examples
48///
49/// ```rust
50/// use tpt_protocol_core::{StateValidator, Error};
51///
52/// struct MyValidator;
53///
54/// impl StateValidator for MyValidator {
55/// type State = bool;
56///
57/// fn validate(&self, state: &Self::State) -> Result<(), Error> {
58/// if *state { Ok(()) } else { Err(Error::state("disconnected")) }
59/// }
60/// }
61///
62/// let v = MyValidator;
63/// assert!(v.validate(&true).is_ok());
64/// assert!(v.validate(&false).is_err());
65/// ```
66pub trait StateValidator {
67 type State: core::fmt::Debug + Clone + PartialEq;
68
69 fn validate(&self, state: &Self::State) -> Result<(), Error>;
70}
71
72/// Normalizes a parsed protocol frame into a TUP DataPoint.
73///
74/// # Examples
75///
76/// ```rust
77/// use tpt_protocol_core::{DataNormalizer, Error};
78/// use tpt_protocol_tup::{DataPoint, Quality, SourceProtocol, TupValue};
79///
80/// struct MyNormalizer;
81///
82/// impl DataNormalizer for MyNormalizer {
83/// type Frame = f64;
84///
85/// fn normalize(&self, frame: &Self::Frame) -> Result<DataPoint, Error> {
86/// Ok(DataPoint::new(
87/// SourceProtocol::Modbus, "dev", "point",
88/// 1000, TupValue::Float(*frame), Quality::Good,
89/// ))
90/// }
91/// }
92///
93/// let n = MyNormalizer;
94/// let dp = n.normalize(&42.5).unwrap();
95/// assert_eq!(dp.device_id, "dev");
96/// ```
97///
98/// Normalizers have no clock, so they leave `timestamp` at 0 when the source
99/// carries no time. The ingesting caller stamps it. The daemon's replay path
100/// does this with the current time.
101pub trait DataNormalizer {
102 type Frame: core::fmt::Debug + Clone + PartialEq;
103
104 fn normalize(&self, frame: &Self::Frame) -> Result<tpt_protocol_tup::DataPoint, Error>;
105
106 /// Every data point one frame carries. A frame can hold several values
107 /// (for example, a Sparkplug payload with many metrics).
108 ///
109 /// The default is the single point from `normalize`. Override it when a
110 /// frame fans out.
111 fn normalize_all(
112 &self,
113 frame: &Self::Frame,
114 ) -> Result<alloc::vec::Vec<tpt_protocol_tup::DataPoint>, Error> {
115 Ok(alloc::vec![self.normalize(frame)?])
116 }
117
118 /// Normalizes a batch of frames into one vector of DataPoints. Each frame
119 /// contributes all of its points, from [`normalize_all`](Self::normalize_all).
120 fn normalize_batch(
121 &self,
122 frames: &[Self::Frame],
123 ) -> Result<alloc::vec::Vec<tpt_protocol_tup::DataPoint>, Error> {
124 let mut out = alloc::vec::Vec::new();
125 for frame in frames {
126 out.extend(self.normalize_all(frame)?);
127 }
128 Ok(out)
129 }
130}
131
132/// Encodes a frame back to wire bytes: the inverse of [`FrameParser::parse`].
133///
134/// Used for round-trip tests (encode, then parse, and compare) and for clients
135/// that send requests. An encoder must produce bytes that its parser accepts.
136///
137/// # Example
138///
139/// ```ignore
140/// let bytes = encoder.encode(&frame)?;
141/// assert_eq!(parser.parse(&bytes)?, frame);
142/// ```
143pub trait FrameEncoder {
144 /// The frame type this encoder writes.
145 type Frame;
146
147 /// Writes `frame` as wire bytes.
148 fn encode(&self, frame: &Self::Frame) -> Result<alloc::vec::Vec<u8>, Error>;
149}
150
151/// Protocol plugin trait for the daemon's plugin architecture.
152///
153/// Implementations produce a stream of TUP `DataPoint` values
154/// (from simulated or real hardware).
155#[cfg(feature = "std")]
156#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
157pub trait ProtocolPlugin: Send + 'static {
158 fn simulate(
159 self: alloc::boxed::Box<Self>,
160 ) -> core::pin::Pin<
161 alloc::boxed::Box<
162 dyn futures_util::stream::Stream<Item = tpt_protocol_tup::DataPoint> + Send,
163 >,
164 >;
165}
166
167#[cfg(test)]
168mod tests {
169 use super::*;
170 use tpt_protocol_tup::{DataPoint, Quality, SourceProtocol, TupValue};
171
172 #[derive(Debug, Clone, PartialEq)]
173 struct TestFrame {
174 value: f64,
175 point: &'static str,
176 }
177
178 struct TestParser;
179
180 impl FrameParser for TestParser {
181 type Frame = TestFrame;
182
183 fn parse(&self, bytes: &[u8]) -> Result<Self::Frame, Error> {
184 if bytes.len() < 4 {
185 return Err(Error::parse("too short"));
186 }
187 let val = f64::from(bytes[0]) + f64::from(bytes[1]) / 100.0;
188 Ok(TestFrame {
189 value: val,
190 point: "test:1",
191 })
192 }
193 }
194
195 struct TestNormalizer;
196
197 impl DataNormalizer for TestNormalizer {
198 type Frame = TestFrame;
199
200 fn normalize(&self, frame: &Self::Frame) -> Result<DataPoint, Error> {
201 Ok(DataPoint::new(
202 SourceProtocol::Modbus,
203 "test-device",
204 frame.point,
205 1753900000000,
206 TupValue::Float(frame.value),
207 Quality::Good,
208 ))
209 }
210 }
211
212 struct TestValidator;
213
214 impl StateValidator for TestValidator {
215 type State = bool;
216
217 fn validate(&self, state: &Self::State) -> Result<(), Error> {
218 if *state {
219 Ok(())
220 } else {
221 Err(Error::state("connection lost"))
222 }
223 }
224 }
225
226 #[test]
227 fn frame_parser_basic() {
228 let parser = TestParser;
229 let frame = parser.parse(&[42, 50, 0, 0]).unwrap();
230 assert!((frame.value - 42.5).abs() < 0.001);
231 assert_eq!(frame.point, "test:1");
232 }
233
234 #[test]
235 fn frame_parser_too_short() {
236 let parser = TestParser;
237 let result = parser.parse(&[42]);
238 assert!(result.is_err());
239 }
240
241 #[test]
242 fn data_normalizer_roundtrip() {
243 let parser = TestParser;
244 let normalizer = TestNormalizer;
245 let frame = parser.parse(&[68, 50, 0, 0]).unwrap();
246 let dp = normalizer.normalize(&frame).unwrap();
247 assert_eq!(dp.source_protocol, SourceProtocol::Modbus);
248 let diff: f64 = 68.5 - 68.5;
249 assert!(diff.abs() < 0.001);
250 }
251
252 #[test]
253 fn state_validator_ok() {
254 let validator = TestValidator;
255 assert!(validator.validate(&true).is_ok());
256 }
257
258 #[test]
259 fn state_validator_fail() {
260 let validator = TestValidator;
261 assert!(validator.validate(&false).is_err());
262 }
263}