1pub mod measurement;
11pub mod relay;
12
13use core::{fmt, num::NonZeroU32, time::Duration};
14pub use eebus::usecases::limitation::Direction;
15use eebus::{
16 model::AddressDevice,
17 usecases::limitation::{EnergyGuardActor, LimitWrite},
18};
19use iec61850_kit::{
20 Fc, ObjectReference,
21 common::ControlModel,
22 proto::data::Value,
23 server::{ControlEvent, Stage},
24};
25
26pub struct PowerLimitBridge {
28 direction: Direction,
29 percent_control: String,
30 release_control: String,
31 device: AddressDevice,
32 rated_watts: NonZeroU32,
33}
34
35#[derive(Clone, Copy, Debug, PartialEq, Eq)]
37pub enum BridgeError {
38 InvalidMapping,
39 Expired,
40 UnmappedControl,
41 UnsupportedOperation,
42 InvalidValue,
43 PeerUnavailable,
44}
45
46impl fmt::Display for BridgeError {
47 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
48 f.write_str(match self {
49 Self::InvalidMapping => "invalid commissioned bridge mapping",
50 Self::Expired => "the command admission deadline has passed",
51 Self::UnmappedControl => "no configured mapping for this control",
52 Self::UnsupportedOperation => "expected an immediate, non-test operate",
53 Self::InvalidValue => "invalid control value for this mapping",
54 Self::PeerUnavailable => {
55 "the guard direction or ready peer does not match this mapping"
56 }
57 })
58 }
59}
60
61impl std::error::Error for BridgeError {}
62
63#[derive(Clone, Copy, Debug, PartialEq)]
66pub struct ScheduledLimit {
67 pub control_number: u8,
69 pub watts: Option<f64>,
71}
72
73fn validate_reference(name: &str, fc: Fc, min_depth: usize) -> Result<(), BridgeError> {
75 let reference = ObjectReference::parse(name).map_err(|_| BridgeError::InvalidMapping)?;
76 if reference.fc != Some(fc)
77 || reference.path().count() < min_depth
78 || name.contains(['.', '(', ')'])
79 {
80 return Err(BridgeError::InvalidMapping);
81 }
82 Ok(())
83}
84
85fn validate_controls(first: &str, second: &str) -> Result<(), BridgeError> {
86 if first == second {
87 return Err(BridgeError::InvalidMapping);
88 }
89 validate_reference(first, Fc::CO, 1)?;
90 validate_reference(second, Fc::CO, 1)
91}
92
93fn admit_operate(
94 event: &ControlEvent,
95 expires_at: Duration,
96 now: Duration,
97) -> Result<(), BridgeError> {
98 if now >= expires_at {
99 return Err(BridgeError::Expired);
100 }
101 if event.stage != Stage::Operate
102 || event.model == ControlModel::StatusOnly
103 || event.request.test
104 || event.request.oper_tm.is_some()
105 {
106 return Err(BridgeError::UnsupportedOperation);
107 }
108 Ok(())
109}
110
111fn percentage(input: &Value) -> Result<f64, BridgeError> {
112 let value = match input {
114 Value::Structure(fields) => match fields.as_slice() {
115 [value] => value,
116 _ => return Err(BridgeError::InvalidValue),
117 },
118 scalar => scalar,
119 };
120 let percent = match value {
121 Value::Float32(n) => f64::from(*n),
122 Value::Float64(n) => *n,
123 _ => return Err(BridgeError::InvalidValue),
124 };
125 if !(0.0..=100.0).contains(&percent) {
126 return Err(BridgeError::InvalidValue);
127 }
128 Ok(percent)
129}
130
131impl PowerLimitBridge {
132 pub fn new(
134 direction: Direction,
135 percent_control: &str,
136 release_control: &str,
137 device: AddressDevice,
138 rated_watts: NonZeroU32,
139 ) -> Result<Self, BridgeError> {
140 validate_controls(percent_control, release_control)?;
141 if device.as_str().trim().is_empty() {
142 return Err(BridgeError::InvalidMapping);
143 }
144 Ok(Self {
145 direction,
146 percent_control: percent_control.into(),
147 release_control: release_control.into(),
148 device,
149 rated_watts,
150 })
151 }
152
153 fn command(
154 &self,
155 event: &ControlEvent,
156 expires_at: Duration,
157 now: Duration,
158 ) -> Result<Option<f64>, BridgeError> {
159 admit_operate(event, expires_at, now)?;
160 if event.object == self.percent_control {
161 let percent = percentage(&event.request.ctl_val)?;
162 Ok(Some(f64::from(self.rated_watts.get()) * percent / 100.0))
163 } else if event.object == self.release_control {
164 if event.request.ctl_val != Value::Boolean(true) {
165 return Err(BridgeError::InvalidValue);
166 }
167 Ok(None)
168 } else {
169 Err(BridgeError::UnmappedControl)
170 }
171 }
172
173 pub fn schedule(
176 &self,
177 guard: &mut EnergyGuardActor,
178 event: &ControlEvent,
179 expires_at: Duration,
180 now: Duration,
181 ) -> Result<ScheduledLimit, BridgeError> {
182 let limit = self
183 .command(event, expires_at, now)?
184 .map(LimitWrite::active);
185 if guard.direction() != self.direction || !guard.is_ready(&self.device) {
186 return Err(BridgeError::PeerUnavailable);
187 }
188 guard
189 .require(&self.device, limit, now)
190 .map_err(|_| BridgeError::InvalidValue)?;
191 Ok(ScheduledLimit {
192 control_number: event.request.ctl_num,
193 watts: limit.map(|limit| limit.watts()),
194 })
195 }
196}