1use crate::types::CosemDataType;
15
16use super::get::GetDataResult;
17use super::{push_length, read_length, tag, DataBlockSa, MethodDescriptor, ServiceError};
18
19mod request_type {
20 pub const NORMAL: u8 = 1;
21 pub const NEXT_PBLOCK: u8 = 2;
22 pub const WITH_LIST: u8 = 3;
23 pub const WITH_FIRST_PBLOCK: u8 = 4;
24 pub const WITH_PBLOCK: u8 = 6;
25}
26
27mod response_type {
28 pub const NORMAL: u8 = 1;
29 pub const WITH_PBLOCK: u8 = 2;
30 pub const WITH_LIST: u8 = 3;
31 pub const NEXT_PBLOCK: u8 = 4;
32}
33
34#[derive(Debug, Clone, PartialEq)]
36pub enum ActionRequest {
37 Normal {
39 invoke_id_and_priority: u8,
41 method: MethodDescriptor,
43 parameters: Option<CosemDataType>,
45 },
46 NextPblock {
48 invoke_id_and_priority: u8,
50 block_number: u32,
52 },
53 WithFirstPblock {
56 invoke_id_and_priority: u8,
58 method: MethodDescriptor,
60 datablock: DataBlockSa,
62 },
63 WithPblock {
65 invoke_id_and_priority: u8,
67 datablock: DataBlockSa,
69 },
70 WithList {
74 invoke_id_and_priority: u8,
76 methods: Vec<MethodDescriptor>,
78 parameters: Vec<CosemDataType>,
80 },
81}
82
83impl ActionRequest {
84 pub fn encode(&self) -> Result<Vec<u8>, ServiceError> {
86 let mut buf = vec![tag::ACTION_REQUEST];
87 match self {
88 ActionRequest::Normal { invoke_id_and_priority, method, parameters } => {
89 buf.push(request_type::NORMAL);
90 buf.push(*invoke_id_and_priority);
91 method.encode(&mut buf);
92 match parameters {
93 None => buf.push(0x00),
94 Some(data) => {
95 buf.push(0x01);
96 data.serialize_ber(&mut buf)?;
97 }
98 }
99 }
100 ActionRequest::NextPblock { invoke_id_and_priority, block_number } => {
101 buf.push(request_type::NEXT_PBLOCK);
102 buf.push(*invoke_id_and_priority);
103 buf.extend_from_slice(&block_number.to_be_bytes());
104 }
105 ActionRequest::WithFirstPblock { invoke_id_and_priority, method, datablock } => {
106 buf.push(request_type::WITH_FIRST_PBLOCK);
107 buf.push(*invoke_id_and_priority);
108 method.encode(&mut buf);
109 datablock.encode(&mut buf);
110 }
111 ActionRequest::WithPblock { invoke_id_and_priority, datablock } => {
112 buf.push(request_type::WITH_PBLOCK);
113 buf.push(*invoke_id_and_priority);
114 datablock.encode(&mut buf);
115 }
116 ActionRequest::WithList { invoke_id_and_priority, methods, parameters } => {
117 buf.push(request_type::WITH_LIST);
118 buf.push(*invoke_id_and_priority);
119 push_length(methods.len(), &mut buf);
120 for method in methods {
121 method.encode(&mut buf);
122 }
123 push_length(parameters.len(), &mut buf);
124 for data in parameters {
125 data.serialize_ber(&mut buf)?;
126 }
127 }
128 }
129 Ok(buf)
130 }
131
132 pub fn decode(bytes: &[u8]) -> Result<ActionRequest, ServiceError> {
134 if bytes.len() < 3 {
135 return Err(ServiceError::Truncated);
136 }
137 if bytes[0] != tag::ACTION_REQUEST {
138 return Err(ServiceError::UnexpectedTag(bytes[0]));
139 }
140 let invoke_id_and_priority = bytes[2];
141 match bytes[1] {
142 request_type::NORMAL => {
143 let (method, n) = MethodDescriptor::decode(&bytes[3..])?;
144 let rest = &bytes[3 + n..];
145 let parameters = match rest.first() {
146 Some(0x00) => None,
147 Some(0x01) => Some(CosemDataType::deserialize_ber(&rest[1..])?.0),
148 Some(&other) => return Err(ServiceError::UnexpectedType(other)),
149 None => return Err(ServiceError::Truncated),
150 };
151 Ok(ActionRequest::Normal { invoke_id_and_priority, method, parameters })
152 }
153 request_type::NEXT_PBLOCK => {
154 let b = bytes.get(3..7).ok_or(ServiceError::Truncated)?;
155 Ok(ActionRequest::NextPblock {
156 invoke_id_and_priority,
157 block_number: u32::from_be_bytes([b[0], b[1], b[2], b[3]]),
158 })
159 }
160 request_type::WITH_FIRST_PBLOCK => {
161 let (method, n) = MethodDescriptor::decode(&bytes[3..])?;
162 let (datablock, _) = DataBlockSa::decode(&bytes[3 + n..])?;
163 Ok(ActionRequest::WithFirstPblock { invoke_id_and_priority, method, datablock })
164 }
165 request_type::WITH_PBLOCK => {
166 let (datablock, _) = DataBlockSa::decode(&bytes[3..])?;
167 Ok(ActionRequest::WithPblock { invoke_id_and_priority, datablock })
168 }
169 request_type::WITH_LIST => {
170 let (count, header) = read_length(&bytes[3..])?;
171 let mut pos = 3 + header;
172 let mut methods = Vec::with_capacity(count);
173 for _ in 0..count {
174 let (method, n) = MethodDescriptor::decode(&bytes[pos..])?;
175 pos += n;
176 methods.push(method);
177 }
178 let (pcount, pheader) = read_length(&bytes[pos..])?;
179 pos += pheader;
180 let mut parameters = Vec::with_capacity(pcount);
181 for _ in 0..pcount {
182 let (data, rest) = CosemDataType::deserialize_ber(&bytes[pos..])?;
183 pos = bytes.len() - rest.len();
184 parameters.push(data);
185 }
186 Ok(ActionRequest::WithList { invoke_id_and_priority, methods, parameters })
187 }
188 other => Err(ServiceError::UnexpectedType(other)),
189 }
190 }
191}
192
193#[derive(Debug, Clone, PartialEq)]
195pub enum ActionResponse {
196 Normal {
198 invoke_id_and_priority: u8,
200 result: u8,
202 return_parameters: Option<GetDataResult>,
204 },
205 WithPblock {
207 invoke_id_and_priority: u8,
209 datablock: DataBlockSa,
211 },
212 NextPblock {
214 invoke_id_and_priority: u8,
216 block_number: u32,
218 },
219 WithList {
222 invoke_id_and_priority: u8,
224 results: Vec<(u8, Option<GetDataResult>)>,
226 },
227}
228
229impl ActionResponse {
230 pub fn encode(&self) -> Result<Vec<u8>, ServiceError> {
232 let mut buf = vec![tag::ACTION_RESPONSE];
233 match self {
234 ActionResponse::Normal { invoke_id_and_priority, result, return_parameters } => {
235 buf.push(response_type::NORMAL);
236 buf.push(*invoke_id_and_priority);
237 buf.push(*result);
238 match return_parameters {
239 None => buf.push(0x00),
240 Some(GetDataResult::Data(data)) => {
241 buf.push(0x01);
242 buf.push(0x00);
243 data.serialize_ber(&mut buf)?;
244 }
245 Some(GetDataResult::AccessResult(code)) => {
246 buf.push(0x01);
247 buf.push(0x01);
248 buf.push(*code);
249 }
250 }
251 }
252 ActionResponse::WithPblock { invoke_id_and_priority, datablock } => {
253 buf.push(response_type::WITH_PBLOCK);
254 buf.push(*invoke_id_and_priority);
255 datablock.encode(&mut buf);
256 }
257 ActionResponse::NextPblock { invoke_id_and_priority, block_number } => {
258 buf.push(response_type::NEXT_PBLOCK);
259 buf.push(*invoke_id_and_priority);
260 buf.extend_from_slice(&block_number.to_be_bytes());
261 }
262 ActionResponse::WithList { invoke_id_and_priority, results } => {
263 buf.push(response_type::WITH_LIST);
264 buf.push(*invoke_id_and_priority);
265 push_length(results.len(), &mut buf);
266 for (result, return_parameters) in results {
267 buf.push(*result);
268 match return_parameters {
269 None => buf.push(0x00),
270 Some(GetDataResult::Data(data)) => {
271 buf.push(0x01);
272 buf.push(0x00);
273 data.serialize_ber(&mut buf)?;
274 }
275 Some(GetDataResult::AccessResult(code)) => {
276 buf.push(0x01);
277 buf.push(0x01);
278 buf.push(*code);
279 }
280 }
281 }
282 }
283 }
284 Ok(buf)
285 }
286
287 pub fn decode(bytes: &[u8]) -> Result<ActionResponse, ServiceError> {
289 if bytes.len() < 4 {
290 return Err(ServiceError::Truncated);
291 }
292 if bytes[0] != tag::ACTION_RESPONSE {
293 return Err(ServiceError::UnexpectedTag(bytes[0]));
294 }
295 let invoke_id_and_priority = bytes[2];
296 match bytes[1] {
297 response_type::NORMAL => {
298 let result = bytes[3];
299 let rest = &bytes[4..];
300 let return_parameters = match rest.first() {
301 Some(0x00) => None,
302 Some(0x01) => {
303 let choice = *rest.get(1).ok_or(ServiceError::Truncated)?;
304 match choice {
305 0x00 => Some(GetDataResult::Data(CosemDataType::deserialize_ber(&rest[2..])?.0)),
306 0x01 => Some(GetDataResult::AccessResult(*rest.get(2).ok_or(ServiceError::Truncated)?)),
307 other => return Err(ServiceError::UnexpectedType(other)),
308 }
309 }
310 Some(&other) => return Err(ServiceError::UnexpectedType(other)),
311 None => return Err(ServiceError::Truncated),
312 };
313 Ok(ActionResponse::Normal { invoke_id_and_priority, result, return_parameters })
314 }
315 response_type::WITH_PBLOCK => {
316 let (datablock, _) = DataBlockSa::decode(&bytes[3..])?;
317 Ok(ActionResponse::WithPblock { invoke_id_and_priority, datablock })
318 }
319 response_type::NEXT_PBLOCK => {
320 let b = bytes.get(3..7).ok_or(ServiceError::Truncated)?;
321 Ok(ActionResponse::NextPblock {
322 invoke_id_and_priority,
323 block_number: u32::from_be_bytes([b[0], b[1], b[2], b[3]]),
324 })
325 }
326 response_type::WITH_LIST => {
327 let (count, header) = read_length(&bytes[3..])?;
328 let mut pos = 3 + header;
329 let mut results = Vec::with_capacity(count);
330 for _ in 0..count {
331 let result = *bytes.get(pos).ok_or(ServiceError::Truncated)?;
332 pos += 1;
333 let flag = *bytes.get(pos).ok_or(ServiceError::Truncated)?;
334 pos += 1;
335 let return_parameters = match flag {
336 0x00 => None,
337 0x01 => {
338 let choice = *bytes.get(pos).ok_or(ServiceError::Truncated)?;
339 pos += 1;
340 match choice {
341 0x00 => {
342 let (data, rest) = CosemDataType::deserialize_ber(&bytes[pos..])?;
343 pos = bytes.len() - rest.len();
344 Some(GetDataResult::Data(data))
345 }
346 0x01 => {
347 let code = *bytes.get(pos).ok_or(ServiceError::Truncated)?;
348 pos += 1;
349 Some(GetDataResult::AccessResult(code))
350 }
351 other => return Err(ServiceError::UnexpectedType(other)),
352 }
353 }
354 other => return Err(ServiceError::UnexpectedType(other)),
355 };
356 results.push((result, return_parameters));
357 }
358 Ok(ActionResponse::WithList { invoke_id_and_priority, results })
359 }
360 other => Err(ServiceError::UnexpectedType(other)),
361 }
362 }
363}
364
365#[cfg(test)]
366mod tests {
367 use super::*;
368 use crate::obis::ObisCode;
369 use crate::service::data_access_result;
370
371 fn method() -> MethodDescriptor {
372 MethodDescriptor::new(70, ObisCode::new(0, 0, 96, 3, 10, 255), 1)
374 }
375
376 #[test]
377 fn action_request_without_parameters_round_trips() {
378 let req = ActionRequest::Normal { invoke_id_and_priority: 0xC1, method: method(), parameters: None };
379 let bytes = req.encode().unwrap();
380 assert_eq!(bytes, vec![0xC3, 0x01, 0xC1, 0x00, 0x46, 0x00, 0x00, 0x60, 0x03, 0x0A, 0xFF, 0x01, 0x00]);
382 assert_eq!(ActionRequest::decode(&bytes).unwrap(), req);
383 }
384
385 #[test]
386 fn action_request_with_parameters_round_trips() {
387 let req = ActionRequest::Normal {
388 invoke_id_and_priority: 0xC1,
389 method: method(),
390 parameters: Some(CosemDataType::Integer(0)),
391 };
392 let bytes = req.encode().unwrap();
393 assert_eq!(ActionRequest::decode(&bytes).unwrap(), req);
394 }
395
396 #[test]
397 fn action_response_success_no_return_round_trips() {
398 let resp = ActionResponse::Normal {
399 invoke_id_and_priority: 0xC1,
400 result: data_access_result::SUCCESS,
401 return_parameters: None,
402 };
403 let bytes = resp.encode().unwrap();
404 assert_eq!(bytes, vec![0xC7, 0x01, 0xC1, 0x00, 0x00]);
405 assert_eq!(ActionResponse::decode(&bytes).unwrap(), resp);
406 }
407
408 #[test]
409 fn action_response_with_return_data_round_trips() {
410 let resp = ActionResponse::Normal {
411 invoke_id_and_priority: 0xC1,
412 result: data_access_result::SUCCESS,
413 return_parameters: Some(GetDataResult::Data(CosemDataType::Unsigned(7))),
414 };
415 let bytes = resp.encode().unwrap();
416 assert_eq!(bytes, vec![0xC7, 0x01, 0xC1, 0x00, 0x01, 0x00, 0x11, 0x07]);
418 assert_eq!(ActionResponse::decode(&bytes).unwrap(), resp);
419 }
420
421 #[test]
422 fn action_request_with_list_round_trips() {
423 let req = ActionRequest::WithList {
424 invoke_id_and_priority: 0xC1,
425 methods: vec![method(), MethodDescriptor::new(70, ObisCode::new(0, 0, 96, 3, 10, 255), 2)],
426 parameters: vec![CosemDataType::Integer(0), CosemDataType::Null],
427 };
428 let bytes = req.encode().unwrap();
429 assert_eq!(bytes[..4], [0xC3, 0x03, 0xC1, 0x02]);
431 assert_eq!(ActionRequest::decode(&bytes).unwrap(), req);
432 }
433
434 #[test]
435 fn action_response_with_list_round_trips() {
436 let resp = ActionResponse::WithList {
437 invoke_id_and_priority: 0xC1,
438 results: vec![
439 (data_access_result::SUCCESS, None),
440 (data_access_result::SUCCESS, Some(GetDataResult::Data(CosemDataType::Unsigned(7)))),
441 ],
442 };
443 let bytes = resp.encode().unwrap();
444 assert_eq!(bytes, vec![0xC7, 0x03, 0xC1, 0x02, 0x00, 0x00, 0x00, 0x01, 0x00, 0x11, 0x07]);
446 assert_eq!(ActionResponse::decode(&bytes).unwrap(), resp);
447 }
448
449 #[test]
450 fn action_request_block_variants_round_trip() {
451 let next = ActionRequest::NextPblock { invoke_id_and_priority: 0xC1, block_number: 2 };
452 assert_eq!(next.encode().unwrap(), vec![0xC3, 0x02, 0xC1, 0x00, 0x00, 0x00, 0x02]);
453 assert_eq!(ActionRequest::decode(&next.encode().unwrap()).unwrap(), next);
454
455 let first = ActionRequest::WithFirstPblock {
456 invoke_id_and_priority: 0xC1,
457 method: method(),
458 datablock: DataBlockSa { last_block: false, block_number: 1, raw_data: vec![0xAA, 0xBB] },
459 };
460 assert_eq!(ActionRequest::decode(&first.encode().unwrap()).unwrap(), first);
461
462 let more = ActionRequest::WithPblock {
463 invoke_id_and_priority: 0xC1,
464 datablock: DataBlockSa { last_block: true, block_number: 2, raw_data: vec![0xCC] },
465 };
466 assert_eq!(ActionRequest::decode(&more.encode().unwrap()).unwrap(), more);
467 }
468
469 #[test]
470 fn action_response_block_variants_round_trip() {
471 let block = ActionResponse::WithPblock {
472 invoke_id_and_priority: 0xC1,
473 datablock: DataBlockSa { last_block: false, block_number: 1, raw_data: vec![0x01, 0x02, 0x03] },
474 };
475 assert_eq!(ActionResponse::decode(&block.encode().unwrap()).unwrap(), block);
476
477 let next = ActionResponse::NextPblock { invoke_id_and_priority: 0xC1, block_number: 1 };
478 assert_eq!(next.encode().unwrap(), vec![0xC7, 0x04, 0xC1, 0x00, 0x00, 0x00, 0x01]);
479 assert_eq!(ActionResponse::decode(&next.encode().unwrap()).unwrap(), next);
480 }
481}