spodes_rs/spodus/
proxy.rs1use 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#[derive(Clone, Debug, Default, PartialEq, Eq)]
20pub struct DirectChannel {
21 pub direct_id: u16,
23 pub meter_id: Vec<u8>,
25 pub channel_id: u8,
27}
28
29#[derive(Clone, Debug, Default)]
31pub struct DirectChannelTable {
32 channels: Vec<DirectChannel>,
33}
34
35impl DirectChannelTable {
36 pub fn new() -> Self {
38 Self::default()
39 }
40
41 pub fn add(&mut self, channel: DirectChannel) {
43 self.channels.push(channel);
44 }
45
46 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 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#[derive(Debug)]
70pub enum ProxyError {
71 UnknownDirectId(u16),
73 NoLink(Vec<u8>),
75 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
91pub struct MeterProxy<L: DataLinkLayer> {
94 table: DirectChannelTable,
95 links: HashMap<Vec<u8>, L>,
96}
97
98impl<L: DataLinkLayer> MeterProxy<L> {
99 pub fn new(table: DirectChannelTable) -> Self {
101 MeterProxy { table, links: HashMap::new() }
102 }
103
104 pub fn attach(&mut self, meter_id: Vec<u8>, link: L) {
106 self.links.insert(meter_id, link);
107 }
108
109 pub fn table(&self) -> &DirectChannelTable {
111 &self.table
112 }
113
114 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 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 assert!(matches!(proxy.forward(999, &request), Err(ProxyError::UnknownDirectId(999))));
173 }
174}