Skip to main content

spodes_rs/classes/
gsm_diagnostic.rs

1use crate::interface::InterfaceClass;
2use crate::obis::ObisCode;
3use crate::types::attrs::{CellInfo, DateTime, GsmAdjacentCell};
4use crate::types::{BerError, CosemDataType};
5use serde::{Deserialize, Serialize};
6use std::any::Any;
7
8/// Configuration structure used to build a [`GsmDiagnostic`] object.
9#[derive(Clone, Serialize, Deserialize, Debug)]
10pub struct GsmDiagnosticConfig {
11    /// Attribute 1: the object's logical name (OBIS code).
12    pub logical_name: ObisCode,
13    /// Class version: 0, 1 or 2 (same attribute set; later versions extend the
14    /// internal `cell_info` structure).
15    pub version: u8,
16    /// Attribute 2: name of the current network operator (visible-string).
17    pub operator: Vec<u8>,
18    /// Attribute 3: modem registration status (enum).
19    pub status: u8,
20    /// Attribute 4: circuit-switched attachment status (enum).
21    pub cs_attachment: u8,
22    /// Attribute 5: packet-switched status (enum).
23    pub ps_status: u8,
24    /// Attribute 6: serving `cell_info` structure.
25    pub cell_info: CellInfo,
26    /// Attribute 7: array of adjacent cell structures.
27    pub adjacent_cells: Vec<GsmAdjacentCell>,
28    /// Attribute 8: capture time of the diagnostic values (date-time).
29    pub capture_time: DateTime,
30}
31
32/// `GSM diagnostic` interface class (class_id = 47) per IEC 62056-6-2 §4.7.8.
33/// Reports the diagnostic values of the GSM/GPRS/LTE modem.
34///
35/// Versions 0, 1 and 2 share the same eight attributes. This class defines no
36/// specific methods.
37#[derive(Clone, Serialize, Deserialize, Debug)]
38pub struct GsmDiagnostic {
39    version: u8,
40    logical_name: ObisCode,
41    operator: Vec<u8>,
42    status: u8,
43    cs_attachment: u8,
44    ps_status: u8,
45    cell_info: CellInfo,
46    adjacent_cells: Vec<GsmAdjacentCell>,
47    capture_time: DateTime,
48}
49
50impl GsmDiagnostic {
51    /// Builds a new [`GsmDiagnostic`] from its configuration.
52    pub fn new(config: GsmDiagnosticConfig) -> Self {
53        GsmDiagnostic {
54            version: config.version,
55            logical_name: config.logical_name,
56            operator: config.operator,
57            status: config.status,
58            cs_attachment: config.cs_attachment,
59            ps_status: config.ps_status,
60            cell_info: config.cell_info,
61            adjacent_cells: config.adjacent_cells,
62            capture_time: config.capture_time,
63        }
64    }
65}
66
67impl InterfaceClass for GsmDiagnostic {
68    fn class_id(&self) -> u16 {
69        47
70    }
71
72    fn version(&self) -> u8 {
73        self.version
74    }
75
76    fn logical_name(&self) -> &ObisCode {
77        &self.logical_name
78    }
79
80    fn attributes(&self) -> Vec<(u8, CosemDataType)> {
81        vec![
82            (1, CosemDataType::OctetString(self.logical_name.to_bytes())),
83            (2, CosemDataType::OctetString(self.operator.clone())),
84            (3, CosemDataType::Enum(self.status)),
85            (4, CosemDataType::Enum(self.cs_attachment)),
86            (5, CosemDataType::Enum(self.ps_status)),
87            (6, CosemDataType::from(self.cell_info.clone())),
88            (7, CosemDataType::Array(self.adjacent_cells.iter().cloned().map(CosemDataType::from).collect())),
89            (8, self.capture_time.clone().into()),
90        ]
91    }
92
93    fn methods(&self) -> Vec<(u8, String)> {
94        // The GSM diagnostic class defines no specific methods.
95        vec![]
96    }
97
98    fn serialize_ber(&self, buf: &mut Vec<u8>) -> Result<(), BerError> {
99        let mut seq_buf = Vec::new();
100        CosemDataType::LongUnsigned(self.class_id()).serialize_ber(&mut seq_buf)?;
101        for (_, attr) in self.attributes() {
102            attr.serialize_ber(&mut seq_buf)?;
103        }
104        buf.push(0x02); // structure [2]
105        write_length(1 + self.attributes().len(), buf); // length = element count
106        buf.extend_from_slice(&seq_buf);
107        Ok(())
108    }
109
110    fn deserialize_ber(&mut self, data: &[u8]) -> Result<(), BerError> {
111        let (tlv, rest) = CosemDataType::deserialize_ber(data)?;
112        if !rest.is_empty() {
113            return Err(BerError::InvalidTag);
114        }
115        let CosemDataType::Structure(seq) = tlv else {
116            return Err(BerError::InvalidTag);
117        };
118        // class_id + 8 attributes.
119        if seq.len() != 9 {
120            return Err(BerError::InvalidLength);
121        }
122        if let CosemDataType::LongUnsigned(class_id) = seq[0] {
123            if class_id != self.class_id() {
124                return Err(BerError::InvalidValue);
125            }
126        } else {
127            return Err(BerError::InvalidTag);
128        }
129        if let CosemDataType::OctetString(obis) = &seq[1] {
130            if obis.len() == 6 {
131                self.logical_name = ObisCode::new(obis[0], obis[1], obis[2], obis[3], obis[4], obis[5]);
132            } else {
133                return Err(BerError::InvalidLength);
134            }
135        } else {
136            return Err(BerError::InvalidTag);
137        }
138        self.operator = match &seq[2] {
139            CosemDataType::OctetString(v) => v.clone(),
140            _ => return Err(BerError::InvalidTag),
141        };
142        self.status = take_enum(&seq[3])?;
143        self.cs_attachment = take_enum(&seq[4])?;
144        self.ps_status = take_enum(&seq[5])?;
145        self.cell_info = CellInfo::try_from(&seq[6]).map_err(|_| BerError::InvalidValue)?;
146        self.adjacent_cells = match &seq[7] {
147            CosemDataType::Array(list) => list
148                .iter()
149                .map(GsmAdjacentCell::try_from)
150                .collect::<Result<Vec<_>, _>>()
151                .map_err(|_| BerError::InvalidValue)?,
152            _ => return Err(BerError::InvalidTag),
153        };
154        self.capture_time = DateTime::try_from(&seq[8]).map_err(|_| BerError::InvalidValue)?;
155        Ok(())
156    }
157
158    fn invoke_method(&mut self, method_id: u8, _params: Option<CosemDataType>) -> Result<CosemDataType, String> {
159        Err(format!("Method {method_id} not supported for GSM diagnostic (no specific methods)"))
160    }
161
162    fn as_any(&self) -> &dyn Any {
163        self
164    }
165}
166
167fn take_enum(value: &CosemDataType) -> Result<u8, BerError> {
168    match value {
169        CosemDataType::Enum(v) => Ok(*v),
170        _ => Err(BerError::InvalidTag),
171    }
172}
173
174/// Writes a BER length octet (short or long form).
175#[allow(clippy::cast_possible_truncation)] // length < 128 and num_octets in 1..=8 always fit u8
176fn write_length(length: usize, buf: &mut Vec<u8>) {
177    if length < 128 {
178        buf.push(length as u8);
179    } else {
180        let bytes = (length as u64).to_be_bytes();
181        let first_non_zero = bytes.iter().position(|&b| b != 0).unwrap_or(7);
182        let num_octets = 8 - first_non_zero;
183        buf.push(0x80 | num_octets as u8);
184        buf.extend_from_slice(&bytes[first_non_zero..]);
185    }
186}
187
188#[cfg(test)]
189mod tests {
190    use super::*;
191
192    fn sample_versioned(version: u8) -> GsmDiagnostic {
193        GsmDiagnostic::new(GsmDiagnosticConfig {
194            logical_name: ObisCode::new(0, 0, 25, 6, 0, 255),
195            version,
196            operator: b"Operator".to_vec(),
197            status: 4,
198            cs_attachment: 2,
199            ps_status: 5,
200            cell_info: CellInfo {
201                cell_id: vec![],
202                location_id: vec![],
203                imsi: vec![],
204                imei: vec![],
205                rn: vec![],
206                cn: vec![],
207                signal_quality: vec![],
208                signal_strength: vec![],
209                channel_number: vec![],
210                cell_parameter_id: vec![],
211                bsic: vec![],
212                iccid: vec![],
213                lac: vec![],
214                mcc: vec![],
215                mnc: vec![],
216                tmsi: vec![],
217                tmgi: vec![],
218                gprs_status: vec![],
219                routing_area_code: vec![],
220                geographic_address: vec![],
221                access_point_name: vec![],
222                data_transport_state: vec![],
223                nma_message: vec![],
224            },
225            adjacent_cells: vec![],
226            capture_time: DateTime::new([0; 12]),
227        })
228    }
229
230    #[test]
231    fn attribute_and_method_counts() {
232        for version in 0..=2u8 {
233            let obj = sample_versioned(version);
234            assert_eq!(obj.class_id(), 47);
235            assert_eq!(obj.version(), version);
236            assert_eq!(obj.attributes().len(), 8);
237            assert!(obj.methods().is_empty());
238        }
239    }
240
241    #[test]
242    fn round_trip_all_versions() {
243        for version in 0..=2u8 {
244            let obj = sample_versioned(version);
245            let mut buf = Vec::new();
246            obj.serialize_ber(&mut buf).unwrap();
247            let mut decoded = sample_versioned(version);
248            decoded.status = 0;
249            decoded.deserialize_ber(&buf).unwrap();
250            assert_eq!(decoded.attributes(), obj.attributes());
251        }
252    }
253}