1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
//! Convenience structs to get and keep the current state of the meter in memory.
//!
//! Usage of these types is entirely optional.
//! When only needing a few or single record, it is more efficient to directly filter on the
//! telegram objects iterator.

use crate::obis::*;
use crate::types::*;

/// A reading from a power meter, per Tariff.
#[derive(Default, Debug)]
pub struct MeterReading {
    pub to: Option<f64>,
    pub by: Option<f64>,
}

/// One of three possible lines in the meter.
#[derive(Default, Debug)]
pub struct Line {
    pub voltage_sags: Option<u64>,
    pub voltage_swells: Option<u64>,
    pub voltage: Option<f64>,
    pub current: Option<u64>,
    pub active_power_plus: Option<f64>,
    pub active_power_neg: Option<f64>,
}

/// One of 4 possible slaves to the meter.
///
/// Such as a gas meter, water meter or heat supply.
#[derive(Default, Debug)]
pub struct Slave {
    pub device_type: Option<u64>,
    pub meter_reading: Option<(TST, f64)>,
}

/// The metering state surmised for a single Telegram.
#[derive(Default, Debug)]
pub struct State {
    pub datetime: Option<TST>,
    pub meterreadings: [MeterReading; 2],
    pub tariff_indicator: Option<[u8; 2]>,
    pub power_delivered: Option<f64>,
    pub power_received: Option<f64>,
    pub power_failures: Option<u64>,
    pub long_power_failures: Option<u64>,
    pub lines: [Line; 3],
    pub slaves: [Slave; 4],
}

impl<'a> core::convert::From<&crate::Telegram<'a>> for crate::Result<State> {
    fn from(t: &crate::Telegram<'a>) -> Self {
        t.objects().try_fold(State::default(), |mut state, o| {
            match o? {
                OBIS::DateTime(tst) => {
                    state.datetime = Some(tst);
                }
                OBIS::MeterReadingTo(t, mr) => {
                    state.meterreadings[t as usize].to = Some(f64::from(&mr));
                }
                OBIS::MeterReadingBy(t, mr) => {
                    state.meterreadings[t as usize].by = Some(f64::from(&mr));
                }
                OBIS::TariffIndicator(ti) => {
                    let mut buf = [0u8; 2];
                    let mut octets = ti.as_octets();
                    buf[0] = octets.next().unwrap_or(Err(crate::Error::InvalidFormat))?;
                    buf[1] = octets.next().unwrap_or(Err(crate::Error::InvalidFormat))?;

                    state.tariff_indicator = Some(buf);
                }
                OBIS::PowerDelivered(p) => {
                    state.power_delivered = Some(f64::from(&p));
                }
                OBIS::PowerReceived(p) => {
                    state.power_received = Some(f64::from(&p));
                }
                OBIS::PowerFailures(UFixedInteger(pf)) => {
                    state.power_failures = Some(pf);
                }
                OBIS::LongPowerFailures(UFixedInteger(lpf)) => {
                    state.long_power_failures = Some(lpf);
                }
                OBIS::VoltageSags(l, UFixedInteger(n)) => {
                    state.lines[l as usize].voltage_sags = Some(n);
                }
                OBIS::VoltageSwells(l, UFixedInteger(n)) => {
                    state.lines[l as usize].voltage_swells = Some(n);
                }
                OBIS::InstantaneousVoltage(l, v) => {
                    state.lines[l as usize].voltage = Some(f64::from(&v));
                }
                OBIS::InstantaneousCurrent(l, UFixedInteger(a)) => {
                    state.lines[l as usize].current = Some(a);
                }
                OBIS::InstantaneousActivePowerPlus(l, p) => {
                    state.lines[l as usize].active_power_plus = Some(f64::from(&p));
                }
                OBIS::InstantaneousActivePowerNeg(l, p) => {
                    state.lines[l as usize].active_power_neg = Some(f64::from(&p));
                }
                OBIS::SlaveDeviceType(s, UFixedInteger(dt)) => {
                    state.slaves[s as usize].device_type = Some(dt);
                }
                OBIS::SlaveMeterReading(s, tst, mr) => {
                    state.slaves[s as usize].meter_reading = Some((tst, f64::from(&mr)));
                }
                _ => {} // Ignore rest.
            }
            Ok(state)
        })
    }
}

#[cfg(test)]
mod tests {
    #[test]
    fn example() {
        let mut buffer = [0u8; 2048];
        let file = std::fs::read("test/telegram.txt").unwrap();

        let (left, _right) = buffer.split_at_mut(file.len());
        left.copy_from_slice(file.as_slice());

        let readout = crate::Readout { buffer };
        let telegram = readout.to_telegram().unwrap();
        let state = crate::Result::<crate::state::State>::from(&telegram).unwrap();

        assert_eq!(
            state.datetime.as_ref().unwrap(),
            &crate::types::TST {
                year: 19,
                month: 3,
                day: 20,
                hour: 18,
                minute: 14,
                second: 3,
                dst: false
            }
        );

        use crate::obis::Tariff::*;

        assert_eq!(state.meterreadings[Tariff1 as usize].to.unwrap(), 576.239);
        assert_eq!(state.meterreadings[Tariff2 as usize].to.unwrap(), 465.162);
        assert_eq!(state.tariff_indicator.unwrap(), [0, 2]);

        eprintln!("{:?}", state);
    }
}