1use crate::obis::ObisCode;
10use crate::types::BerError;
11
12pub mod acse;
13pub mod action;
14pub mod ciphering;
15pub mod error;
16pub mod gbt;
17pub mod general_ciphering;
18pub mod get;
19pub mod initiate;
20pub mod notification;
21pub mod set;
22
23pub mod tag {
25 pub const DATA_NOTIFICATION: u8 = 0x0F;
27 pub const GET_REQUEST: u8 = 0xC0;
29 pub const SET_REQUEST: u8 = 0xC1;
31 pub const EVENT_NOTIFICATION_REQUEST: u8 = 0xC2;
33 pub const ACTION_REQUEST: u8 = 0xC3;
35 pub const GET_RESPONSE: u8 = 0xC4;
37 pub const SET_RESPONSE: u8 = 0xC5;
39 pub const ACTION_RESPONSE: u8 = 0xC7;
41 pub const EXCEPTION_RESPONSE: u8 = 0xD8;
43 pub const CONFIRMED_SERVICE_ERROR: u8 = 0x0E;
45}
46
47pub mod data_access_result {
50 pub const SUCCESS: u8 = 0;
52 pub const HARDWARE_FAULT: u8 = 1;
54 pub const TEMPORARY_FAILURE: u8 = 2;
56 pub const READ_WRITE_DENIED: u8 = 3;
58 pub const OBJECT_UNDEFINED: u8 = 4;
60 pub const OBJECT_CLASS_INCONSISTENT: u8 = 9;
62 pub const OBJECT_UNAVAILABLE: u8 = 11;
64 pub const TYPE_UNMATCHED: u8 = 12;
66 pub const SCOPE_OF_ACCESS_VIOLATED: u8 = 13;
68 pub const DATA_BLOCK_UNAVAILABLE: u8 = 14;
70 pub const LONG_GET_ABORTED: u8 = 15;
72 pub const NO_LONG_GET_IN_PROGRESS: u8 = 16;
74 pub const LONG_SET_ABORTED: u8 = 17;
76 pub const NO_LONG_SET_IN_PROGRESS: u8 = 18;
78 pub const DATA_BLOCK_NUMBER_INVALID: u8 = 19;
80 pub const OTHER_REASON: u8 = 250;
82}
83
84#[derive(Debug, PartialEq, Eq)]
86pub enum ServiceError {
87 UnexpectedTag(u8),
89 UnexpectedType(u8),
91 Truncated,
93 InvalidData,
95}
96
97impl std::fmt::Display for ServiceError {
98 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
99 write!(f, "{self:?}")
100 }
101}
102
103impl std::error::Error for ServiceError {}
104
105impl From<ServiceError> for std::io::Error {
106 fn from(e: ServiceError) -> Self {
107 std::io::Error::new(std::io::ErrorKind::InvalidData, e)
108 }
109}
110
111impl From<BerError> for ServiceError {
112 fn from(_: BerError) -> Self {
113 ServiceError::InvalidData
114 }
115}
116
117pub fn invoke_id_and_priority(invoke_id: u8, confirmed: bool, high_priority: bool) -> u8 {
120 (invoke_id & 0x0F) | if confirmed { 0x40 } else { 0x00 } | if high_priority { 0x80 } else { 0x00 }
121}
122
123#[derive(Debug, Clone, PartialEq)]
127pub struct AttributeDescriptor {
128 pub class_id: u16,
130 pub instance_id: ObisCode,
132 pub attribute_id: i8,
134}
135
136impl AttributeDescriptor {
137 pub fn new(class_id: u16, instance_id: ObisCode, attribute_id: i8) -> Self {
139 AttributeDescriptor { class_id, instance_id, attribute_id }
140 }
141
142 pub fn encode(&self, buf: &mut Vec<u8>) {
144 buf.extend_from_slice(&self.class_id.to_be_bytes());
145 buf.extend_from_slice(&self.instance_id.to_bytes());
146 #[allow(clippy::cast_sign_loss)]
148 buf.push(self.attribute_id as u8);
149 }
150
151 pub fn decode(bytes: &[u8]) -> Result<(AttributeDescriptor, usize), ServiceError> {
153 if bytes.len() < 9 {
154 return Err(ServiceError::Truncated);
155 }
156 let class_id = u16::from_be_bytes([bytes[0], bytes[1]]);
157 let o = &bytes[2..8];
158 let instance_id = ObisCode::new(o[0], o[1], o[2], o[3], o[4], o[5]);
159 #[allow(clippy::cast_possible_wrap)]
161 let attribute_id = bytes[8] as i8;
162 Ok((AttributeDescriptor { class_id, instance_id, attribute_id }, 9))
163 }
164}
165
166#[derive(Debug, Clone, PartialEq)]
169pub struct MethodDescriptor {
170 pub class_id: u16,
172 pub instance_id: ObisCode,
174 pub method_id: i8,
176}
177
178impl MethodDescriptor {
179 pub fn new(class_id: u16, instance_id: ObisCode, method_id: i8) -> Self {
181 MethodDescriptor { class_id, instance_id, method_id }
182 }
183
184 pub fn encode(&self, buf: &mut Vec<u8>) {
186 buf.extend_from_slice(&self.class_id.to_be_bytes());
187 buf.extend_from_slice(&self.instance_id.to_bytes());
188 #[allow(clippy::cast_sign_loss)]
190 buf.push(self.method_id as u8);
191 }
192
193 pub fn decode(bytes: &[u8]) -> Result<(MethodDescriptor, usize), ServiceError> {
195 if bytes.len() < 9 {
196 return Err(ServiceError::Truncated);
197 }
198 let class_id = u16::from_be_bytes([bytes[0], bytes[1]]);
199 let o = &bytes[2..8];
200 let instance_id = ObisCode::new(o[0], o[1], o[2], o[3], o[4], o[5]);
201 #[allow(clippy::cast_possible_wrap)]
203 let method_id = bytes[8] as i8;
204 Ok((MethodDescriptor { class_id, instance_id, method_id }, 9))
205 }
206}
207
208#[derive(Debug, Clone, PartialEq, Eq)]
211pub struct DataBlockSa {
212 pub last_block: bool,
214 pub block_number: u32,
216 pub raw_data: Vec<u8>,
218}
219
220#[derive(Debug, Clone, PartialEq, Eq)]
225pub struct RawApdu {
226 pub tag: u8,
228 pub body: Vec<u8>,
230}
231
232impl RawApdu {
233 pub fn new(tag: u8, body: Vec<u8>) -> Self {
235 RawApdu { tag, body }
236 }
237
238 pub fn from_bytes(bytes: &[u8]) -> Result<Self, ServiceError> {
240 if bytes.is_empty() {
241 return Err(ServiceError::Truncated);
242 }
243 let tag = bytes[0];
244 let (len, header) = read_length(&bytes[1..])?;
245 let start = 1 + header;
246 let body = bytes.get(start..start + len).ok_or(ServiceError::Truncated)?.to_vec();
247 Ok(RawApdu { tag, body })
248 }
249
250 pub fn encode(&self) -> Vec<u8> {
252 let mut buf = Vec::with_capacity(2 + self.body.len());
253 buf.push(self.tag);
254 push_length(self.body.len(), &mut buf);
255 buf.extend_from_slice(&self.body);
256 buf
257 }
258
259 pub fn tag(&self) -> u8 {
261 self.tag
262 }
263
264 pub fn body(&self) -> &[u8] {
266 &self.body
267 }
268
269 pub fn body_mut(&mut self) -> &mut Vec<u8> {
271 &mut self.body
272 }
273
274 pub fn into_parts(self) -> (u8, Vec<u8>) {
276 (self.tag, self.body)
277 }
278}
279
280impl DataBlockSa {
281 pub fn encode(&self, buf: &mut Vec<u8>) {
283 buf.push(u8::from(self.last_block));
284 buf.extend_from_slice(&self.block_number.to_be_bytes());
285 push_length(self.raw_data.len(), buf);
286 buf.extend_from_slice(&self.raw_data);
287 }
288
289 pub fn decode(bytes: &[u8]) -> Result<(DataBlockSa, usize), ServiceError> {
291 let last_block = *bytes.first().ok_or(ServiceError::Truncated)? != 0;
292 let b = bytes.get(1..5).ok_or(ServiceError::Truncated)?;
293 let block_number = u32::from_be_bytes([b[0], b[1], b[2], b[3]]);
294 let (len, header) = read_length(&bytes[5..])?;
295 let start = 5 + header;
296 let raw_data = bytes.get(start..start + len).ok_or(ServiceError::Truncated)?.to_vec();
297 Ok((DataBlockSa { last_block, block_number, raw_data }, start + len))
298 }
299}
300
301#[allow(clippy::cast_possible_truncation)] pub(crate) fn push_length(length: usize, buf: &mut Vec<u8>) {
304 if length < 128 {
305 buf.push(length as u8);
306 } else {
307 let bytes = (length as u64).to_be_bytes();
308 let first = bytes.iter().position(|&b| b != 0).unwrap_or(7);
309 let n = 8 - first;
310 buf.push(0x80 | n as u8);
311 buf.extend_from_slice(&bytes[first..]);
312 }
313}
314
315pub(crate) fn read_length(bytes: &[u8]) -> Result<(usize, usize), ServiceError> {
317 let first = *bytes.first().ok_or(ServiceError::Truncated)?;
318 if first < 128 {
319 Ok((first as usize, 1))
320 } else {
321 let n = (first & 0x7F) as usize;
322 let slice = bytes.get(1..1 + n).ok_or(ServiceError::Truncated)?;
323 let mut len = 0usize;
324 for &b in slice {
325 len = (len << 8) | b as usize;
326 }
327 Ok((len, 1 + n))
328 }
329}
330
331#[cfg(test)]
332mod tests {
333 use super::*;
334
335 #[test]
336 fn invoke_id_and_priority_bits() {
337 assert_eq!(invoke_id_and_priority(1, true, true), 0xC1);
339 assert_eq!(invoke_id_and_priority(0, false, false), 0x00);
340 }
341
342 #[test]
343 fn attribute_descriptor_round_trips() {
344 let d = AttributeDescriptor::new(1, ObisCode::new(0, 0, 0x80, 0, 0, 0xFF), 2);
345 let mut buf = Vec::new();
346 d.encode(&mut buf);
347 assert_eq!(buf, vec![0x00, 0x01, 0x00, 0x00, 0x80, 0x00, 0x00, 0xFF, 0x02]);
349 let (decoded, n) = AttributeDescriptor::decode(&buf).unwrap();
350 assert_eq!(n, 9);
351 assert_eq!(decoded, d);
352 }
353
354 #[test]
355 fn method_descriptor_round_trips() {
356 let d = MethodDescriptor::new(70, ObisCode::new(0, 0, 96, 3, 10, 255), 1);
357 let mut buf = Vec::new();
358 d.encode(&mut buf);
359 let (decoded, n) = MethodDescriptor::decode(&buf).unwrap();
360 assert_eq!(n, 9);
361 assert_eq!(decoded, d);
362 }
363
364 #[test]
365 fn data_block_sa_round_trips() {
366 let block = DataBlockSa { last_block: true, block_number: 3, raw_data: vec![0x0A; 17] };
367 let mut buf = Vec::new();
368 block.encode(&mut buf);
369 assert_eq!(buf[..6], [0x01, 0x00, 0x00, 0x00, 0x03, 0x11]);
371 let (decoded, n) = DataBlockSa::decode(&buf).unwrap();
372 assert_eq!(n, buf.len());
373 assert_eq!(decoded, block);
374 }
375
376 #[test]
377 fn raw_apdu_encode_decode_round_trip() {
378 let raw = RawApdu::new(0xC0, vec![0x01, 0x02, 0x03]);
379 let encoded = raw.encode();
380 let decoded = RawApdu::from_bytes(&encoded).unwrap();
381 assert_eq!(decoded.tag(), 0xC0);
382 assert_eq!(decoded.body(), &[0x01, 0x02, 0x03]);
383 }
384
385 #[test]
386 fn raw_apdu_from_bytes_with_length() {
387 let bytes = vec![0xC1, 0x05, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA];
389 let raw = RawApdu::from_bytes(&bytes).unwrap();
390 assert_eq!(raw.tag(), 0xC1);
391 assert_eq!(raw.body(), &[0xAA; 5]);
392 }
393
394 #[test]
395 fn raw_apdu_empty_body() {
396 let raw = RawApdu::new(0xC2, vec![]);
397 let encoded = raw.encode();
398 assert_eq!(encoded, vec![0xC2, 0x00]);
399 let decoded = RawApdu::from_bytes(&encoded).unwrap();
400 assert!(decoded.body().is_empty());
401 }
402
403 #[test]
404 fn raw_apdu_truncated_returns_error() {
405 let bytes = vec![0xC0]; assert!(RawApdu::from_bytes(&bytes).is_err());
407 }
408
409 #[test]
410 fn raw_apdu_mutable_body() {
411 let mut raw = RawApdu::new(0xC3, vec![0x01]);
412 raw.body_mut().push(0x02);
413 assert_eq!(raw.body(), &[0x01, 0x02]);
414 }
415}