Skip to main content

spodes_rs/spodus/
proxy.rs

1//! Transparent pass-through to a meter (СТО 34.01-5.1-013-2023, §8.3 and §10.3).
2//!
3//! The head-end reaches an individual meter through the ИВКЭ by its `direct_id`
4//! — a logical address unique within the ИВКЭ (the HDLC lower / Wrapper address,
5//! range 200..16381, §8.3.5). The direct-channel table (§10.3, `0.0.94.7.129.255`)
6//! maps `direct_id → {meter_id, channel_id}`; the ИВКЭ then forwards the request
7//! frame to that meter and relays the response back.
8
9use std::collections::HashMap;
10use std::io;
11
12use crate::classes::data::Data;
13use crate::transport::DataLinkLayer;
14use crate::types::CosemDataType;
15
16use super::obis;
17
18/// One direct-channel entry (§10.3, `direct_channel`).
19#[derive(Clone, Debug, Default, PartialEq, Eq)]
20pub struct DirectChannel {
21    /// `direct_id` — the meter's logical address within the ИВКЭ (200..16381).
22    pub direct_id: u16,
23    /// Meter identifier.
24    pub meter_id: Vec<u8>,
25    /// Communication channel to reach the meter.
26    pub channel_id: u8,
27}
28
29/// The direct-channel table (§10.3, `0.0.94.7.129.255`).
30#[derive(Clone, Debug, Default)]
31pub struct DirectChannelTable {
32    channels: Vec<DirectChannel>,
33}
34
35impl DirectChannelTable {
36    /// Creates an empty table.
37    pub fn new() -> Self {
38        Self::default()
39    }
40
41    /// Adds a direct-channel mapping.
42    pub fn add(&mut self, channel: DirectChannel) {
43        self.channels.push(channel);
44    }
45
46    /// Resolves the meter addressed by `direct_id`.
47    pub fn by_direct_id(&self, direct_id: u16) -> Option<&DirectChannel> {
48        self.channels.iter().find(|c| c.direct_id == direct_id)
49    }
50
51    /// Builds the COSEM `Data` (IC 1) object holding the table (§10.3).
52    pub fn build(&self) -> Data {
53        let array = self
54            .channels
55            .iter()
56            .map(|c| {
57                CosemDataType::Structure(vec![
58                    CosemDataType::LongUnsigned(c.direct_id),
59                    CosemDataType::OctetString(c.meter_id.clone()),
60                    CosemDataType::Unsigned(c.channel_id),
61                ])
62            })
63            .collect();
64        Data::new(obis::direct_channel_table(), CosemDataType::Array(array))
65    }
66}
67
68/// Errors raised while forwarding a request to a meter.
69#[derive(Debug)]
70pub enum ProxyError {
71    /// No direct-channel entry for the requested `direct_id`.
72    UnknownDirectId(u16),
73    /// No downstream link is attached for the addressed meter.
74    NoLink(Vec<u8>),
75    /// A transport error on the downstream link.
76    Io(io::Error),
77}
78
79impl std::fmt::Display for ProxyError {
80    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
81        match self {
82            ProxyError::UnknownDirectId(id) => write!(f, "no direct-channel entry for direct_id {id}"),
83            ProxyError::NoLink(meter) => write!(f, "no downstream link for meter {meter:02X?}"),
84            ProxyError::Io(e) => write!(f, "downstream transport error: {e}"),
85        }
86    }
87}
88
89impl std::error::Error for ProxyError {}
90
91/// A transparent proxy: resolves `direct_id` to a meter via the direct-channel
92/// table and forwards raw request APDUs to that meter's downstream link.
93pub struct MeterProxy<L: DataLinkLayer> {
94    table: DirectChannelTable,
95    links: HashMap<Vec<u8>, L>,
96}
97
98impl<L: DataLinkLayer> MeterProxy<L> {
99    /// Creates a proxy over the given direct-channel table.
100    pub fn new(table: DirectChannelTable) -> Self {
101        MeterProxy { table, links: HashMap::new() }
102    }
103
104    /// Attaches the downstream link used to reach `meter_id`.
105    pub fn attach(&mut self, meter_id: Vec<u8>, link: L) {
106        self.links.insert(meter_id, link);
107    }
108
109    /// The direct-channel table.
110    pub fn table(&self) -> &DirectChannelTable {
111        &self.table
112    }
113
114    /// Forwards a raw request APDU to the meter addressed by `direct_id` and
115    /// returns its response APDU (transparent pass-through, §8.3).
116    pub fn forward(&mut self, direct_id: u16, request: &[u8]) -> Result<Vec<u8>, ProxyError> {
117        let meter_id =
118            self.table.by_direct_id(direct_id).ok_or(ProxyError::UnknownDirectId(direct_id))?.meter_id.clone();
119        let link = self.links.get_mut(&meter_id).ok_or_else(|| ProxyError::NoLink(meter_id.clone()))?;
120        link.send_apdu(request).map_err(ProxyError::Io)?;
121        link.receive_apdu().map_err(ProxyError::Io)
122    }
123}
124
125#[cfg(test)]
126mod tests {
127    use super::*;
128    use crate::interface::InterfaceClass;
129
130    /// A loopback link that returns a fixed canned response and records the sent APDU.
131    struct MockLink {
132        response: Vec<u8>,
133        sent: Vec<u8>,
134    }
135
136    impl DataLinkLayer for MockLink {
137        fn send_apdu(&mut self, apdu: &[u8]) -> io::Result<()> {
138            self.sent = apdu.to_vec();
139            Ok(())
140        }
141        fn receive_apdu(&mut self) -> io::Result<Vec<u8>> {
142            Ok(self.response.clone())
143        }
144    }
145
146    #[test]
147    fn direct_channel_table_builds_data_object() {
148        let mut table = DirectChannelTable::new();
149        table.add(DirectChannel { direct_id: 200, meter_id: b"SIT12260004".to_vec(), channel_id: 1 });
150        assert_eq!(table.by_direct_id(200).unwrap().meter_id, b"SIT12260004");
151        assert!(table.by_direct_id(999).is_none());
152
153        let object = table.build();
154        assert_eq!(object.class_id(), 1);
155        assert_eq!(object.logical_name(), &obis::direct_channel_table());
156        let CosemDataType::Array(rows) = &object.attributes()[1].1 else { panic!("array") };
157        assert_eq!(rows.len(), 1);
158    }
159
160    #[test]
161    fn proxy_forwards_to_the_addressed_meter() {
162        let mut table = DirectChannelTable::new();
163        table.add(DirectChannel { direct_id: 200, meter_id: b"SIT12260004".to_vec(), channel_id: 1 });
164        let mut proxy = MeterProxy::new(table);
165        proxy.attach(b"SIT12260004".to_vec(), MockLink { response: vec![0xC4, 0x01, 0xC1, 0x00], sent: Vec::new() });
166
167        let request = vec![0xC0, 0x01, 0xC1, 0x00, 0x01, 0x00, 0x00, 0x80, 0x00, 0x00, 0xFF, 0x02, 0x00];
168        let response = proxy.forward(200, &request).unwrap();
169        assert_eq!(response, vec![0xC4, 0x01, 0xC1, 0x00]);
170
171        // An unknown direct_id is rejected.
172        assert!(matches!(proxy.forward(999, &request), Err(ProxyError::UnknownDirectId(999))));
173    }
174}