1use crate::types::CosemDataType;
16
17use super::get::AccessSelection;
18use super::{push_length, read_length, tag, AttributeDescriptor, DataBlockSa, ServiceError};
19
20mod request_type {
21 pub const NORMAL: u8 = 1;
22 pub const WITH_FIRST_DATABLOCK: u8 = 2;
23 pub const WITH_DATABLOCK: u8 = 3;
24 pub const WITH_LIST: u8 = 4;
25}
26
27mod response_type {
28 pub const NORMAL: u8 = 1;
29 pub const DATABLOCK: u8 = 2;
30 pub const LAST_DATABLOCK: u8 = 3;
31 pub const WITH_LIST: u8 = 5;
32}
33
34#[derive(Debug, Clone, PartialEq)]
36pub enum SetRequest {
37 Normal {
39 invoke_id_and_priority: u8,
41 attribute: AttributeDescriptor,
43 access_selection: Option<AccessSelection>,
45 value: CosemDataType,
47 },
48 WithFirstDatablock {
51 invoke_id_and_priority: u8,
53 attribute: AttributeDescriptor,
55 access_selection: Option<AccessSelection>,
57 datablock: DataBlockSa,
59 },
60 WithDatablock {
62 invoke_id_and_priority: u8,
64 datablock: DataBlockSa,
66 },
67 WithList {
69 invoke_id_and_priority: u8,
71 attributes: Vec<(AttributeDescriptor, Option<AccessSelection>)>,
73 values: Vec<CosemDataType>,
75 },
76}
77
78impl SetRequest {
79 pub fn encode(&self) -> Result<Vec<u8>, ServiceError> {
81 let mut buf = vec![tag::SET_REQUEST];
82 match self {
83 SetRequest::Normal { invoke_id_and_priority, attribute, access_selection, value } => {
84 buf.push(request_type::NORMAL);
85 buf.push(*invoke_id_and_priority);
86 attribute.encode(&mut buf);
87 AccessSelection::encode_into(access_selection, &mut buf)?;
88 value.serialize_ber(&mut buf)?;
89 }
90 SetRequest::WithFirstDatablock { invoke_id_and_priority, attribute, access_selection, datablock } => {
91 buf.push(request_type::WITH_FIRST_DATABLOCK);
92 buf.push(*invoke_id_and_priority);
93 attribute.encode(&mut buf);
94 AccessSelection::encode_into(access_selection, &mut buf)?;
95 datablock.encode(&mut buf);
96 }
97 SetRequest::WithDatablock { invoke_id_and_priority, datablock } => {
98 buf.push(request_type::WITH_DATABLOCK);
99 buf.push(*invoke_id_and_priority);
100 datablock.encode(&mut buf);
101 }
102 SetRequest::WithList { invoke_id_and_priority, attributes, values } => {
103 buf.push(request_type::WITH_LIST);
104 buf.push(*invoke_id_and_priority);
105 push_length(attributes.len(), &mut buf);
106 for (attribute, access_selection) in attributes {
107 attribute.encode(&mut buf);
108 AccessSelection::encode_into(access_selection, &mut buf)?;
109 }
110 push_length(values.len(), &mut buf);
111 for value in values {
112 value.serialize_ber(&mut buf)?;
113 }
114 }
115 }
116 Ok(buf)
117 }
118
119 pub fn decode(bytes: &[u8]) -> Result<SetRequest, ServiceError> {
121 if bytes.len() < 3 {
122 return Err(ServiceError::Truncated);
123 }
124 if bytes[0] != tag::SET_REQUEST {
125 return Err(ServiceError::UnexpectedTag(bytes[0]));
126 }
127 let invoke_id_and_priority = bytes[2];
128 match bytes[1] {
129 request_type::NORMAL => {
130 let (attribute, n) = AttributeDescriptor::decode(&bytes[3..])?;
131 let (access_selection, m) = AccessSelection::decode_from(&bytes[3 + n..])?;
132 let (value, _) = CosemDataType::deserialize_ber(&bytes[3 + n + m..])?;
133 Ok(SetRequest::Normal { invoke_id_and_priority, attribute, access_selection, value })
134 }
135 request_type::WITH_FIRST_DATABLOCK => {
136 let (attribute, n) = AttributeDescriptor::decode(&bytes[3..])?;
137 let (access_selection, m) = AccessSelection::decode_from(&bytes[3 + n..])?;
138 let (datablock, _) = DataBlockSa::decode(&bytes[3 + n + m..])?;
139 Ok(SetRequest::WithFirstDatablock { invoke_id_and_priority, attribute, access_selection, datablock })
140 }
141 request_type::WITH_DATABLOCK => {
142 let (datablock, _) = DataBlockSa::decode(&bytes[3..])?;
143 Ok(SetRequest::WithDatablock { invoke_id_and_priority, datablock })
144 }
145 request_type::WITH_LIST => {
146 let (count, header) = read_length(&bytes[3..])?;
147 let mut pos = 3 + header;
148 let mut attributes = Vec::with_capacity(count);
149 for _ in 0..count {
150 let (attribute, n) = AttributeDescriptor::decode(&bytes[pos..])?;
151 pos += n;
152 let (access_selection, m) = AccessSelection::decode_from(&bytes[pos..])?;
153 pos += m;
154 attributes.push((attribute, access_selection));
155 }
156 let (vcount, vheader) = read_length(&bytes[pos..])?;
157 pos += vheader;
158 let mut values = Vec::with_capacity(vcount);
159 for _ in 0..vcount {
160 let (value, rest) = CosemDataType::deserialize_ber(&bytes[pos..])?;
161 pos = bytes.len() - rest.len();
162 values.push(value);
163 }
164 Ok(SetRequest::WithList { invoke_id_and_priority, attributes, values })
165 }
166 other => Err(ServiceError::UnexpectedType(other)),
167 }
168 }
169}
170
171#[derive(Debug, Clone, PartialEq)]
173pub enum SetResponse {
174 Normal {
176 invoke_id_and_priority: u8,
178 result: u8,
180 },
181 Datablock {
183 invoke_id_and_priority: u8,
185 block_number: u32,
187 },
188 LastDatablock {
191 invoke_id_and_priority: u8,
193 result: u8,
195 block_number: u32,
197 },
198 WithList {
200 invoke_id_and_priority: u8,
202 results: Vec<u8>,
204 },
205}
206
207impl SetResponse {
208 pub fn encode(&self) -> Vec<u8> {
210 match self {
211 SetResponse::Normal { invoke_id_and_priority, result } => {
212 vec![tag::SET_RESPONSE, response_type::NORMAL, *invoke_id_and_priority, *result]
213 }
214 SetResponse::Datablock { invoke_id_and_priority, block_number } => {
215 let mut buf = vec![tag::SET_RESPONSE, response_type::DATABLOCK, *invoke_id_and_priority];
216 buf.extend_from_slice(&block_number.to_be_bytes());
217 buf
218 }
219 SetResponse::LastDatablock { invoke_id_and_priority, result, block_number } => {
220 let mut buf = vec![tag::SET_RESPONSE, response_type::LAST_DATABLOCK, *invoke_id_and_priority, *result];
221 buf.extend_from_slice(&block_number.to_be_bytes());
222 buf
223 }
224 SetResponse::WithList { invoke_id_and_priority, results } => {
225 let mut buf = vec![tag::SET_RESPONSE, response_type::WITH_LIST, *invoke_id_and_priority];
226 push_length(results.len(), &mut buf);
227 buf.extend_from_slice(results);
228 buf
229 }
230 }
231 }
232
233 pub fn decode(bytes: &[u8]) -> Result<SetResponse, ServiceError> {
235 if bytes.len() < 4 {
236 return Err(ServiceError::Truncated);
237 }
238 if bytes[0] != tag::SET_RESPONSE {
239 return Err(ServiceError::UnexpectedTag(bytes[0]));
240 }
241 let invoke_id_and_priority = bytes[2];
242 match bytes[1] {
243 response_type::NORMAL => Ok(SetResponse::Normal { invoke_id_and_priority, result: bytes[3] }),
244 response_type::DATABLOCK => {
245 let b = bytes.get(3..7).ok_or(ServiceError::Truncated)?;
246 Ok(SetResponse::Datablock {
247 invoke_id_and_priority,
248 block_number: u32::from_be_bytes([b[0], b[1], b[2], b[3]]),
249 })
250 }
251 response_type::LAST_DATABLOCK => {
252 let result = bytes[3];
253 let b = bytes.get(4..8).ok_or(ServiceError::Truncated)?;
254 Ok(SetResponse::LastDatablock {
255 invoke_id_and_priority,
256 result,
257 block_number: u32::from_be_bytes([b[0], b[1], b[2], b[3]]),
258 })
259 }
260 response_type::WITH_LIST => {
261 let (count, header) = read_length(&bytes[3..])?;
262 let start = 3 + header;
263 let results = bytes.get(start..start + count).ok_or(ServiceError::Truncated)?.to_vec();
264 Ok(SetResponse::WithList { invoke_id_and_priority, results })
265 }
266 other => Err(ServiceError::UnexpectedType(other)),
267 }
268 }
269}
270
271#[cfg(test)]
272mod tests {
273 use super::*;
274 use crate::obis::ObisCode;
275 use crate::service::data_access_result;
276
277 #[test]
278 fn set_request_normal_matches_reference_bytes() {
279 let req = SetRequest::Normal {
281 invoke_id_and_priority: 0xC1,
282 attribute: AttributeDescriptor::new(1, ObisCode::new(0, 0, 0x80, 0, 0, 0xFF), 2),
283 access_selection: None,
284 value: CosemDataType::OctetString(vec![0xAA, 0xBB]),
285 };
286 assert_eq!(
287 req.encode().unwrap(),
288 vec![0xC1, 0x01, 0xC1, 0x00, 0x01, 0x00, 0x00, 0x80, 0x00, 0x00, 0xFF, 0x02, 0x00, 0x09, 0x02, 0xAA, 0xBB]
289 );
290 assert_eq!(SetRequest::decode(&req.encode().unwrap()).unwrap(), req);
291 }
292
293 #[test]
294 fn set_response_normal_matches_reference_bytes() {
295 let resp = SetResponse::Normal { invoke_id_and_priority: 0xC1, result: data_access_result::SUCCESS };
297 assert_eq!(resp.encode(), vec![0xC5, 0x01, 0xC1, 0x00]);
298 assert_eq!(SetResponse::decode(&resp.encode()).unwrap(), resp);
299 }
300
301 #[test]
302 fn set_request_with_datablock_matches_reference_bytes() {
303 let raw =
305 vec![0x39, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x50, 0x0A, 0x03, 0x30, 0x30, 0x30];
306 let req = SetRequest::WithDatablock {
307 invoke_id_and_priority: 0xC1,
308 datablock: DataBlockSa { last_block: true, block_number: 3, raw_data: raw },
309 };
310 let bytes = req.encode().unwrap();
311 assert_eq!(&bytes[..6], &[0xC1, 0x03, 0xC1, 0x01, 0x00, 0x00]);
312 assert_eq!(SetRequest::decode(&bytes).unwrap(), req);
313 }
314
315 #[test]
316 fn set_request_with_list_round_trips() {
317 let req = SetRequest::WithList {
318 invoke_id_and_priority: 0xC1,
319 attributes: vec![
320 (AttributeDescriptor::new(1, ObisCode::new(0, 0, 0x80, 0, 0, 0xFF), 2), None),
321 (AttributeDescriptor::new(3, ObisCode::new(1, 0, 1, 8, 0, 0xFF), 2), None),
322 ],
323 values: vec![CosemDataType::Unsigned(1), CosemDataType::LongUnsigned(0x1234)],
324 };
325 let bytes = req.encode().unwrap();
326 assert_eq!(bytes[..4], [0xC1, 0x04, 0xC1, 0x02]);
328 assert_eq!(SetRequest::decode(&bytes).unwrap(), req);
329 }
330
331 #[test]
332 fn set_response_with_list_round_trips() {
333 let resp = SetResponse::WithList {
334 invoke_id_and_priority: 0xC1,
335 results: vec![data_access_result::SUCCESS, data_access_result::READ_WRITE_DENIED],
336 };
337 let bytes = resp.encode();
338 assert_eq!(bytes, vec![0xC5, 0x05, 0xC1, 0x02, 0x00, 0x03]);
340 assert_eq!(SetResponse::decode(&bytes).unwrap(), resp);
341 }
342
343 #[test]
344 fn set_response_datablock_variants_round_trip() {
345 let ack = SetResponse::Datablock { invoke_id_and_priority: 0xC1, block_number: 1 };
346 assert_eq!(ack.encode(), vec![0xC5, 0x02, 0xC1, 0x00, 0x00, 0x00, 0x01]);
347 assert_eq!(SetResponse::decode(&ack.encode()).unwrap(), ack);
348
349 let last = SetResponse::LastDatablock { invoke_id_and_priority: 0xC1, result: 0, block_number: 3 };
350 assert_eq!(last.encode(), vec![0xC5, 0x03, 0xC1, 0x00, 0x00, 0x00, 0x00, 0x03]);
351 assert_eq!(SetResponse::decode(&last.encode()).unwrap(), last);
352 }
353}