use std::collections::HashMap;
use std::io;
use crate::classes::data::Data;
use crate::transport::DataLinkLayer;
use crate::types::CosemDataType;
use super::obis;
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct DirectChannel {
pub direct_id: u16,
pub meter_id: Vec<u8>,
pub channel_id: u8,
}
#[derive(Clone, Debug, Default)]
pub struct DirectChannelTable {
channels: Vec<DirectChannel>,
}
impl DirectChannelTable {
pub fn new() -> Self {
Self::default()
}
pub fn add(&mut self, channel: DirectChannel) {
self.channels.push(channel);
}
pub fn by_direct_id(&self, direct_id: u16) -> Option<&DirectChannel> {
self.channels.iter().find(|c| c.direct_id == direct_id)
}
pub fn build(&self) -> Data {
let array = self
.channels
.iter()
.map(|c| {
CosemDataType::Structure(vec![
CosemDataType::LongUnsigned(c.direct_id),
CosemDataType::OctetString(c.meter_id.clone()),
CosemDataType::Unsigned(c.channel_id),
])
})
.collect();
Data::new(obis::direct_channel_table(), CosemDataType::Array(array))
}
}
#[derive(Debug)]
pub enum ProxyError {
UnknownDirectId(u16),
NoLink(Vec<u8>),
Io(io::Error),
}
impl std::fmt::Display for ProxyError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ProxyError::UnknownDirectId(id) => write!(f, "no direct-channel entry for direct_id {id}"),
ProxyError::NoLink(meter) => write!(f, "no downstream link for meter {meter:02X?}"),
ProxyError::Io(e) => write!(f, "downstream transport error: {e}"),
}
}
}
impl std::error::Error for ProxyError {}
pub struct MeterProxy<L: DataLinkLayer> {
table: DirectChannelTable,
links: HashMap<Vec<u8>, L>,
}
impl<L: DataLinkLayer> MeterProxy<L> {
pub fn new(table: DirectChannelTable) -> Self {
MeterProxy { table, links: HashMap::new() }
}
pub fn attach(&mut self, meter_id: Vec<u8>, link: L) {
self.links.insert(meter_id, link);
}
pub fn table(&self) -> &DirectChannelTable {
&self.table
}
pub fn forward(&mut self, direct_id: u16, request: &[u8]) -> Result<Vec<u8>, ProxyError> {
let meter_id =
self.table.by_direct_id(direct_id).ok_or(ProxyError::UnknownDirectId(direct_id))?.meter_id.clone();
let link = self.links.get_mut(&meter_id).ok_or_else(|| ProxyError::NoLink(meter_id.clone()))?;
link.send_apdu(request).map_err(ProxyError::Io)?;
link.receive_apdu().map_err(ProxyError::Io)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::interface::InterfaceClass;
struct MockLink {
response: Vec<u8>,
sent: Vec<u8>,
}
impl DataLinkLayer for MockLink {
fn send_apdu(&mut self, apdu: &[u8]) -> io::Result<()> {
self.sent = apdu.to_vec();
Ok(())
}
fn receive_apdu(&mut self) -> io::Result<Vec<u8>> {
Ok(self.response.clone())
}
}
#[test]
fn direct_channel_table_builds_data_object() {
let mut table = DirectChannelTable::new();
table.add(DirectChannel { direct_id: 200, meter_id: b"SIT12260004".to_vec(), channel_id: 1 });
assert_eq!(table.by_direct_id(200).unwrap().meter_id, b"SIT12260004");
assert!(table.by_direct_id(999).is_none());
let object = table.build();
assert_eq!(object.class_id(), 1);
assert_eq!(object.logical_name(), &obis::direct_channel_table());
let CosemDataType::Array(rows) = &object.attributes()[1].1 else { panic!("array") };
assert_eq!(rows.len(), 1);
}
#[test]
fn proxy_forwards_to_the_addressed_meter() {
let mut table = DirectChannelTable::new();
table.add(DirectChannel { direct_id: 200, meter_id: b"SIT12260004".to_vec(), channel_id: 1 });
let mut proxy = MeterProxy::new(table);
proxy.attach(b"SIT12260004".to_vec(), MockLink { response: vec![0xC4, 0x01, 0xC1, 0x00], sent: Vec::new() });
let request = vec![0xC0, 0x01, 0xC1, 0x00, 0x01, 0x00, 0x00, 0x80, 0x00, 0x00, 0xFF, 0x02, 0x00];
let response = proxy.forward(200, &request).unwrap();
assert_eq!(response, vec![0xC4, 0x01, 0xC1, 0x00]);
assert!(matches!(proxy.forward(999, &request), Err(ProxyError::UnknownDirectId(999))));
}
}