1use crate::types::CosemDataType;
14
15use super::{tag, AttributeDescriptor, ServiceError};
16
17mod request_type {
19 pub const NORMAL: u8 = 1;
20 pub const NEXT: u8 = 2;
21 pub const WITH_LIST: u8 = 3;
22}
23
24mod response_type {
26 pub const NORMAL: u8 = 1;
27 pub const WITH_DATABLOCK: u8 = 2;
28 pub const WITH_LIST: u8 = 3;
29}
30
31#[derive(Debug, Clone, PartialEq)]
33pub struct AccessSelection {
34 pub selector: u8,
36 pub parameters: CosemDataType,
38}
39
40impl AccessSelection {
41 pub fn encode_into(this: &Option<AccessSelection>, buf: &mut Vec<u8>) -> Result<(), ServiceError> {
43 match this {
44 None => buf.push(0x00),
45 Some(sel) => {
46 buf.push(0x01);
47 buf.push(sel.selector);
48 sel.parameters.serialize_ber(buf)?;
49 }
50 }
51 Ok(())
52 }
53
54 pub fn decode_from(bytes: &[u8]) -> Result<(Option<AccessSelection>, usize), ServiceError> {
57 match bytes.first() {
58 Some(0x00) => Ok((None, 1)),
59 Some(0x01) => {
60 let selector = *bytes.get(1).ok_or(ServiceError::Truncated)?;
61 let (parameters, rest) = CosemDataType::deserialize_ber(&bytes[2..])?;
62 let consumed = 2 + (bytes.len() - 2 - rest.len());
63 Ok((Some(AccessSelection { selector, parameters }), consumed))
64 }
65 Some(&other) => Err(ServiceError::UnexpectedType(other)),
66 None => Err(ServiceError::Truncated),
67 }
68 }
69}
70
71#[derive(Debug, Clone, PartialEq)]
73pub enum GetRequest {
74 Normal {
76 invoke_id_and_priority: u8,
78 attribute: AttributeDescriptor,
80 access_selection: Option<AccessSelection>,
82 },
83 Next {
85 invoke_id_and_priority: u8,
87 block_number: u32,
89 },
90 WithList {
92 invoke_id_and_priority: u8,
94 attributes: Vec<(AttributeDescriptor, Option<AccessSelection>)>,
96 },
97}
98
99impl GetRequest {
100 pub fn encode(&self) -> Result<Vec<u8>, ServiceError> {
102 let mut buf = vec![tag::GET_REQUEST];
103 match self {
104 GetRequest::Normal { invoke_id_and_priority, attribute, access_selection } => {
105 buf.push(request_type::NORMAL);
106 buf.push(*invoke_id_and_priority);
107 attribute.encode(&mut buf);
108 AccessSelection::encode_into(access_selection, &mut buf)?;
109 }
110 GetRequest::Next { invoke_id_and_priority, block_number } => {
111 buf.push(request_type::NEXT);
112 buf.push(*invoke_id_and_priority);
113 buf.extend_from_slice(&block_number.to_be_bytes());
114 }
115 GetRequest::WithList { invoke_id_and_priority, attributes } => {
116 buf.push(request_type::WITH_LIST);
117 buf.push(*invoke_id_and_priority);
118 push_length(attributes.len(), &mut buf);
119 for (attribute, access_selection) in attributes {
120 attribute.encode(&mut buf);
121 AccessSelection::encode_into(access_selection, &mut buf)?;
122 }
123 }
124 }
125 Ok(buf)
126 }
127
128 pub fn decode(bytes: &[u8]) -> Result<GetRequest, ServiceError> {
130 if bytes.len() < 3 {
131 return Err(ServiceError::Truncated);
132 }
133 if bytes[0] != tag::GET_REQUEST {
134 return Err(ServiceError::UnexpectedTag(bytes[0]));
135 }
136 let invoke_id_and_priority = bytes[2];
137 match bytes[1] {
138 request_type::NORMAL => {
139 let (attribute, n) = AttributeDescriptor::decode(&bytes[3..])?;
140 let (access_selection, _) = AccessSelection::decode_from(&bytes[3 + n..])?;
141 Ok(GetRequest::Normal { invoke_id_and_priority, attribute, access_selection })
142 }
143 request_type::NEXT => {
144 let b = bytes.get(3..7).ok_or(ServiceError::Truncated)?;
145 let block_number = u32::from_be_bytes([b[0], b[1], b[2], b[3]]);
146 Ok(GetRequest::Next { invoke_id_and_priority, block_number })
147 }
148 request_type::WITH_LIST => {
149 let (count, header) = read_length(&bytes[3..])?;
150 let mut pos = 3 + header;
151 let mut attributes = Vec::with_capacity(count);
152 for _ in 0..count {
153 let (attribute, n) = AttributeDescriptor::decode(&bytes[pos..])?;
154 pos += n;
155 let (access_selection, m) = AccessSelection::decode_from(&bytes[pos..])?;
156 pos += m;
157 attributes.push((attribute, access_selection));
158 }
159 Ok(GetRequest::WithList { invoke_id_and_priority, attributes })
160 }
161 other => Err(ServiceError::UnexpectedType(other)),
162 }
163 }
164}
165
166#[derive(Debug, Clone, PartialEq)]
169pub enum GetDataResult {
170 Data(CosemDataType),
172 AccessResult(u8),
174}
175
176#[derive(Debug, Clone, PartialEq)]
178pub enum GetResponse {
179 Normal {
181 invoke_id_and_priority: u8,
183 result: GetDataResult,
185 },
186 WithDataBlock {
188 invoke_id_and_priority: u8,
190 last_block: bool,
192 block_number: u32,
194 raw_data: Result<Vec<u8>, u8>,
196 },
197 WithList {
199 invoke_id_and_priority: u8,
201 results: Vec<GetDataResult>,
203 },
204}
205
206impl GetResponse {
207 pub fn encode(&self) -> Result<Vec<u8>, ServiceError> {
209 let mut buf = vec![tag::GET_RESPONSE];
210 match self {
211 GetResponse::Normal { invoke_id_and_priority, result } => {
212 buf.push(response_type::NORMAL);
213 buf.push(*invoke_id_and_priority);
214 match result {
215 GetDataResult::Data(data) => {
216 buf.push(0x00);
217 data.serialize_ber(&mut buf)?;
218 }
219 GetDataResult::AccessResult(code) => {
220 buf.push(0x01);
221 buf.push(*code);
222 }
223 }
224 }
225 GetResponse::WithDataBlock { invoke_id_and_priority, last_block, block_number, raw_data } => {
226 buf.push(response_type::WITH_DATABLOCK);
227 buf.push(*invoke_id_and_priority);
228 buf.push(u8::from(*last_block));
229 buf.extend_from_slice(&block_number.to_be_bytes());
230 match raw_data {
231 Ok(data) => {
232 buf.push(0x00);
233 push_length(data.len(), &mut buf);
234 buf.extend_from_slice(data);
235 }
236 Err(code) => {
237 buf.push(0x01);
238 buf.push(*code);
239 }
240 }
241 }
242 GetResponse::WithList { invoke_id_and_priority, results } => {
243 buf.push(response_type::WITH_LIST);
244 buf.push(*invoke_id_and_priority);
245 push_length(results.len(), &mut buf);
246 for result in results {
247 match result {
248 GetDataResult::Data(data) => {
249 buf.push(0x00);
250 data.serialize_ber(&mut buf)?;
251 }
252 GetDataResult::AccessResult(code) => {
253 buf.push(0x01);
254 buf.push(*code);
255 }
256 }
257 }
258 }
259 }
260 Ok(buf)
261 }
262
263 pub fn decode(bytes: &[u8]) -> Result<GetResponse, ServiceError> {
265 if bytes.len() < 3 {
266 return Err(ServiceError::Truncated);
267 }
268 if bytes[0] != tag::GET_RESPONSE {
269 return Err(ServiceError::UnexpectedTag(bytes[0]));
270 }
271 let invoke_id_and_priority = bytes[2];
272 match bytes[1] {
273 response_type::NORMAL => {
274 let choice = *bytes.get(3).ok_or(ServiceError::Truncated)?;
275 let result = match choice {
276 0x00 => {
277 let (data, _) = CosemDataType::deserialize_ber(&bytes[4..])?;
278 GetDataResult::Data(data)
279 }
280 0x01 => GetDataResult::AccessResult(*bytes.get(4).ok_or(ServiceError::Truncated)?),
281 other => return Err(ServiceError::UnexpectedType(other)),
282 };
283 Ok(GetResponse::Normal { invoke_id_and_priority, result })
284 }
285 response_type::WITH_DATABLOCK => {
286 let last_block = *bytes.get(3).ok_or(ServiceError::Truncated)? != 0;
287 let b = bytes.get(4..8).ok_or(ServiceError::Truncated)?;
288 let block_number = u32::from_be_bytes([b[0], b[1], b[2], b[3]]);
289 let choice = *bytes.get(8).ok_or(ServiceError::Truncated)?;
290 let raw_data = match choice {
291 0x00 => {
292 let (len, header) = read_length(&bytes[9..])?;
293 let start = 9 + header;
294 let slice = bytes.get(start..start + len).ok_or(ServiceError::Truncated)?;
295 Ok(slice.to_vec())
296 }
297 0x01 => Err(*bytes.get(9).ok_or(ServiceError::Truncated)?),
298 other => return Err(ServiceError::UnexpectedType(other)),
299 };
300 Ok(GetResponse::WithDataBlock { invoke_id_and_priority, last_block, block_number, raw_data })
301 }
302 response_type::WITH_LIST => {
303 let (count, header) = read_length(&bytes[3..])?;
304 let mut pos = 3 + header;
305 let mut results = Vec::with_capacity(count);
306 for _ in 0..count {
307 let choice = *bytes.get(pos).ok_or(ServiceError::Truncated)?;
308 pos += 1;
309 match choice {
310 0x00 => {
311 let (data, rest) = CosemDataType::deserialize_ber(&bytes[pos..])?;
312 pos = bytes.len() - rest.len();
313 results.push(GetDataResult::Data(data));
314 }
315 0x01 => {
316 results.push(GetDataResult::AccessResult(*bytes.get(pos).ok_or(ServiceError::Truncated)?));
317 pos += 1;
318 }
319 other => return Err(ServiceError::UnexpectedType(other)),
320 }
321 }
322 Ok(GetResponse::WithList { invoke_id_and_priority, results })
323 }
324 other => Err(ServiceError::UnexpectedType(other)),
325 }
326 }
327}
328
329#[allow(clippy::cast_possible_truncation)] fn push_length(length: usize, buf: &mut Vec<u8>) {
332 if length < 128 {
333 buf.push(length as u8);
334 } else {
335 let bytes = (length as u64).to_be_bytes();
336 let first = bytes.iter().position(|&b| b != 0).unwrap_or(7);
337 let n = 8 - first;
338 buf.push(0x80 | n as u8);
339 buf.extend_from_slice(&bytes[first..]);
340 }
341}
342
343fn read_length(bytes: &[u8]) -> Result<(usize, usize), ServiceError> {
345 let first = *bytes.first().ok_or(ServiceError::Truncated)?;
346 if first < 128 {
347 Ok((first as usize, 1))
348 } else {
349 let n = (first & 0x7F) as usize;
350 let slice = bytes.get(1..1 + n).ok_or(ServiceError::Truncated)?;
351 let mut len = 0usize;
352 for &b in slice {
353 len = (len << 8) | b as usize;
354 }
355 Ok((len, 1 + n))
356 }
357}
358
359#[cfg(test)]
360mod tests {
361 use super::*;
362 use crate::obis::ObisCode;
363 use crate::service::invoke_id_and_priority;
364
365 #[test]
366 fn get_request_normal_matches_reference_bytes() {
367 let req = GetRequest::Normal {
369 invoke_id_and_priority: invoke_id_and_priority(1, true, true),
370 attribute: AttributeDescriptor::new(1, ObisCode::new(0, 0, 0x80, 0, 0, 0xFF), 2),
371 access_selection: None,
372 };
373 assert_eq!(
374 req.encode().unwrap(),
375 vec![0xC0, 0x01, 0xC1, 0x00, 0x01, 0x00, 0x00, 0x80, 0x00, 0x00, 0xFF, 0x02, 0x00]
376 );
377 assert_eq!(GetRequest::decode(&req.encode().unwrap()).unwrap(), req);
378 }
379
380 #[test]
381 fn get_request_next_round_trips() {
382 let req = GetRequest::Next { invoke_id_and_priority: 0xC1, block_number: 1 };
383 let bytes = req.encode().unwrap();
384 assert_eq!(bytes, vec![0xC0, 0x02, 0xC1, 0x00, 0x00, 0x00, 0x01]);
385 assert_eq!(GetRequest::decode(&bytes).unwrap(), req);
386 }
387
388 #[test]
389 fn get_response_normal_with_data_round_trips() {
390 let resp = GetResponse::Normal {
391 invoke_id_and_priority: 0xC1,
392 result: GetDataResult::Data(CosemDataType::LongUnsigned(0x1234)),
393 };
394 let bytes = resp.encode().unwrap();
395 assert_eq!(bytes, vec![0xC4, 0x01, 0xC1, 0x00, 0x12, 0x12, 0x34]);
397 assert_eq!(GetResponse::decode(&bytes).unwrap(), resp);
398 }
399
400 #[test]
401 fn get_response_normal_with_access_result_round_trips() {
402 let resp = GetResponse::Normal {
403 invoke_id_and_priority: 0xC1,
404 result: GetDataResult::AccessResult(super::super::data_access_result::OBJECT_UNDEFINED),
405 };
406 let bytes = resp.encode().unwrap();
407 assert_eq!(bytes, vec![0xC4, 0x01, 0xC1, 0x01, 0x04]);
408 assert_eq!(GetResponse::decode(&bytes).unwrap(), resp);
409 }
410
411 #[test]
412 fn get_request_with_list_round_trips() {
413 let req = GetRequest::WithList {
414 invoke_id_and_priority: 0xC1,
415 attributes: vec![
416 (AttributeDescriptor::new(1, ObisCode::new(0, 0, 0x80, 0, 0, 0xFF), 2), None),
417 (AttributeDescriptor::new(8, ObisCode::new(0, 0, 1, 0, 0, 0xFF), 2), None),
418 ],
419 };
420 let bytes = req.encode().unwrap();
421 assert_eq!(bytes[..4], [0xC0, 0x03, 0xC1, 0x02]);
423 assert_eq!(GetRequest::decode(&bytes).unwrap(), req);
424 }
425
426 #[test]
427 fn get_response_with_list_round_trips() {
428 let resp = GetResponse::WithList {
429 invoke_id_and_priority: 0xC1,
430 results: vec![
431 GetDataResult::Data(CosemDataType::LongUnsigned(0x1234)),
432 GetDataResult::AccessResult(super::super::data_access_result::OBJECT_UNDEFINED),
433 ],
434 };
435 let bytes = resp.encode().unwrap();
436 assert_eq!(bytes, vec![0xC4, 0x03, 0xC1, 0x02, 0x00, 0x12, 0x12, 0x34, 0x01, 0x04]);
438 assert_eq!(GetResponse::decode(&bytes).unwrap(), resp);
439 }
440
441 #[test]
442 fn get_response_with_datablock_round_trips() {
443 let resp = GetResponse::WithDataBlock {
444 invoke_id_and_priority: 0xC1,
445 last_block: false,
446 block_number: 1,
447 raw_data: Ok(vec![0x02, 0x00, 0x09]),
448 };
449 let bytes = resp.encode().unwrap();
450 assert_eq!(bytes, vec![0xC4, 0x02, 0xC1, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x03, 0x02, 0x00, 0x09]);
452 assert_eq!(GetResponse::decode(&bytes).unwrap(), resp);
453 }
454}