equilibrium 0.1.0-alpha

A framework for creating distributed control systems
Documentation
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
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
/// Bidirectional Threshold

use crate::controllers::Controller;
use crate::types::{Action, Message};
use chrono::{DateTime, Duration, Utc};
use crate::input::Input;
use crate::output::Output;
use crate::scheduler::Scheduler;

/// Internal state of the controller
///
/// This is used to determine which output should be activated.
enum State {
    BelowThreshold,
    WithinTolerance,
    AboveThreshold,
}

/// Controller with two outputs that are activated when the input is above or below a threshold.
///
/// This is used to control a system that has two modes of control (increase and decrease). This controller is
/// not very precise, and is intended to keep a value within a general range.
///
/// ## Potential Use Cases
/// * For a reservoir or sump pump, turning on a pump or relief valve according to fill level
///
/// # Example
/// In this example, the controller will increase the value if it rises above 11.0, and decrease the value if it falls
/// below 9.0.
/// ```
/// use chrono::{Duration, Utc};
/// use equilibrium::controllers::{Controller, BidirectionalThreshold};
/// use equilibrium::Input;
/// use equilibrium::Output;
///
/// let threshold = 10.0;
/// let tolerance = 1.0;
///
/// let interval = Duration::seconds(1);
///
/// let mut controller = BidirectionalThreshold::new(
///     threshold,
///     tolerance,
///     Input::default(),
///     Output::default(),
///     Output::default(),
///     interval,
/// );
///
/// controller.poll(Utc::now());
/// ```
#[derive(Debug)]
pub struct BidirectionalThreshold<I, O, O2>
    where
        I: Fn() -> String,
        O: FnMut(bool),
        O2: FnMut(bool),
{
    name: Option<String>,
    threshold: f32,
    tolerance: f32,
    input: Input<I>,
    increase_output: Output<O>,
    decrease_output: Output<O2>,
    interval: Duration,
    schedule: Scheduler,
}

impl<I, O, O2> BidirectionalThreshold<I, O, O2>
    where
        I: Fn() -> String,
        O: FnMut(bool),
        O2: FnMut(bool),
{
    /// Create a new controller with a specific time as the first read time
    ///
    /// This is the recommended API for instantiation.
    pub fn new(
        threshold: f32,
        tolerance: f32,
        input: Input<I>,
        increase_output: Output<O>,
        decrease_output: Output<O2>,
        interval: Duration,
    ) -> Self {
        Self {
            name: None,
            threshold,
            tolerance,
            input,
            increase_output,
            decrease_output,
            interval,
            schedule: Scheduler::new(),
        }.schedule_next(None)
    }

    /// Create a new controller without scheduling the first read
    ///
    /// [`BidirectionalThreshold::schedule_next()`] must be called after this function.
    ///
    /// [`BidirectionalThreshold::new()`] is the preferred API for instantiation.
    ///
    /// This method is only useful for testing purposes.
    pub fn new_without_scheduled(
        threshold: f32,
        tolerance: f32,
        input: Input<I>,
        increase_output: Output<O>,
        decrease_output: Output<O2>,
        interval: Duration,
    ) -> Self {
        Self {
            name: None,
            threshold,
            tolerance,
            input,
            increase_output,
            decrease_output,
            interval,
            schedule: Scheduler::new(),
        }
    }

    /// Read the input and determine the state of the controller
    fn get_state(&mut self) -> State {
        let value = self.input.read().parse::<f32>().unwrap();
        if value > self.threshold + self.tolerance {
            State::AboveThreshold
        } else if value < self.threshold - self.tolerance {
            State::BelowThreshold
        } else {
            State::WithinTolerance
        }
    }

    /// Attempt to lower the input value
    fn handle_above_threshold(&mut self) {
        self.decrease_output.activate();
        self.increase_output.deactivate();
    }

    /// Attempt to raise the input value
    fn handle_below_threshold(&mut self) {
        self.increase_output.activate();
        self.decrease_output.deactivate();
    }

    /// Turn off both outputs to maintain the current value
    fn handle_within_tolerance(&mut self) {
        self.increase_output.deactivate();
        self.decrease_output.deactivate();
    }

    /// Schedule the next read for the specified time
    fn schedule_next_in_place(&mut self, time: DateTime<Utc>) {
        self.schedule.schedule_read(time + self.interval);
    }

    /// Builder method to schedule the next read for the specified time
    ///
    /// If no time is specified, the current time will be used.
    pub fn schedule_next<T>(mut self, time: T) -> Self
    where T: Into<Option<DateTime<Utc>>>{
        let time= time.into().unwrap_or_else(|| Utc::now());
        self.schedule_next_in_place(time);
        self
    }
}

impl<I, O, O2> Controller for BidirectionalThreshold<I, O, O2>
    where
        I: Fn() -> String,
        O: FnMut(bool),
        O2: FnMut(bool),
{
    fn set_name(&mut self, name: String) {
        self.name = Some(name);
    }

    fn get_name(&self) -> Option<String> {
        self.name.clone()
    }

    fn poll(&mut self, time: DateTime<Utc>) -> Option<Message> {
        if let Some(event) = self.schedule.attempt_execution(time) {
            match event.get_action() {
                Action::Read => {
                    let msg = match self.get_state() {
                        State::AboveThreshold => {
                            self.handle_above_threshold();
                            "Above Threshold".to_string()
                        },
                        State::BelowThreshold => {
                            self.handle_below_threshold();
                            "Below Threshold".to_string()
                        },
                        State::WithinTolerance => {
                            self.handle_within_tolerance();
                            "Within Tolerance".to_string()
                        },
                    };
                    self.schedule_next_in_place(time);

                    let read_state = self.input.get_state().clone();
                    return Some(Message::new(
                        self.get_name().unwrap_or_default(),
                        msg,
                        event.get_timestamp().clone(),
                        read_state,
                    ));
                }
                _ => {}
            }
        }
        None
    }
}

impl Default for BidirectionalThreshold<fn() -> String, fn(bool), fn(bool)> {
    fn default() -> Self {
        Self::new_without_scheduled(
            0.0,
            0.0,
            Input::default(),
            Output::default(),
            Output::default(),
            Duration::seconds(1),
        )
    }
}

#[cfg(test)]
mod tests {
    use std::collections::VecDeque;
    use std::sync::{Arc, Mutex};
    use super::*;

    #[test]
    fn test_new() {
        let threshold = 10.0;
        let tolerance = 1.0;
        let input = Input::default();

        let increase_output = Output::default();
        let decrease_output = Output::default();
        let interval = Duration::seconds(1);

        let controller = BidirectionalThreshold::new_without_scheduled(
            threshold,
            tolerance,
            input,
            increase_output,
            decrease_output,
            interval,
        );

        assert_eq!(controller.threshold, threshold);
        assert_eq!(controller.tolerance, tolerance);
        assert_eq!(controller.interval, interval);

        assert!(!controller.schedule.has_future_events());

        assert!(controller.increase_output.get_state().is_none());
        assert!(controller.decrease_output.get_state().is_none());
    }

    #[test]
    fn test_with_time() {
        let threshold = 10.0;
        let tolerance = 1.0;
        let input = Input::default();

        let increase_output = Output::default();
        let decrease_output = Output::default();
        let interval = Duration::seconds(1);

        let controller = BidirectionalThreshold::new(
            threshold,
            tolerance,
            input,
            increase_output,
            decrease_output,
            interval,
        );

        assert_eq!(controller.threshold, threshold);
        assert_eq!(controller.tolerance, tolerance);
        assert_eq!(controller.interval, interval);

        assert!(controller.schedule.has_future_events());
    }

    #[test]
    fn test_handle_above_threshold() {
        let threshold = 10.0;
        let tolerance = 1.0;
        let input = Input::default();

        let increase_output = Output::default();
        let decrease_output = Output::default();
        let interval = Duration::seconds(1);

        let mut controller = BidirectionalThreshold::new_without_scheduled(
            threshold,
            tolerance,
            input,
            increase_output,
            decrease_output,
            interval,
        );

        controller.handle_above_threshold();

        assert_eq!(controller.increase_output.get_state(), Some(false));
        assert_eq!(controller.decrease_output.get_state(), Some(true));
    }

    #[test]
    fn test_handle_below_threshold() {
        let threshold = 10.0;
        let tolerance = 1.0;
        let input = Input::default();

        let increase_output = Output::default();
        let decrease_output = Output::default();
        let interval = Duration::seconds(1);

        let mut controller = BidirectionalThreshold::new_without_scheduled(
            threshold,
            tolerance,
            input,
            increase_output,
            decrease_output,
            interval,
        );

        controller.handle_below_threshold();

        assert_eq!(controller.increase_output.get_state(), Some(true));
        assert_eq!(controller.decrease_output.get_state(), Some(false));
    }

    #[test]
    fn test_handle_within_tolerance() {
        let threshold = 10.0;
        let tolerance = 1.0;
        let input = Input::default();

        let increase_output = Output::default();
        let decrease_output = Output::default();
        let interval = Duration::seconds(1);

        let mut controller = BidirectionalThreshold::new_without_scheduled(
            threshold,
            tolerance,
            input,
            increase_output,
            decrease_output,
            interval,
        );

        controller.handle_within_tolerance();

        assert_eq!(controller.increase_output.get_state(), Some(false));
        assert_eq!(controller.decrease_output.get_state(), Some(false));
    }

    #[test]
    fn test_get_set_name() {
        let mut controller = BidirectionalThreshold::default();

        assert_eq!(controller.get_name(), None);

        controller.set_name(String::from("test"));

        assert_eq!(controller.get_name(), Some(String::from("test")));
    }

    #[test]
    fn test_poll() {
        let threshold = 10.0;
        let tolerance = 1.0;

        let input_values = Arc::new(Mutex::new(VecDeque::from([
            "8.0".to_string(),
            "10.5".to_string(),
            "12.0".to_string(),
        ])));

        let input = Input::new(||
            input_values.lock().unwrap().pop_front().unwrap()
        );

        let increase_output = Output::default();
        let decrease_output = Output::default();
        let interval = Duration::seconds(1);

        let time = Utc::now();
        let mut controller = BidirectionalThreshold::new_without_scheduled(
            threshold,
            tolerance,
            input,
            increase_output,
            decrease_output,
            interval,
        ).schedule_next(time);

        // check default state
        assert!(controller.increase_output.get_state().is_none());
        assert!(controller.decrease_output.get_state().is_none());

        controller.poll(time);

        assert!(controller.increase_output.get_state().is_none());
        assert!(controller.decrease_output.get_state().is_none());

        // check before first read
        let message = controller.poll(time + Duration::milliseconds(500));
        assert!(controller.increase_output.get_state().is_none());
        assert!(controller.decrease_output.get_state().is_none());

        assert!(message.is_none());

        // check first read which should be below threshold
        let message = controller.poll(time + Duration::seconds(1));
        assert_eq!(controller.increase_output.get_state(), Some(true));
        assert_eq!(controller.decrease_output.get_state(), Some(false));

        assert!(message.is_some());
        assert_eq!(message.as_ref().unwrap().get_read_state().unwrap(), "8.0".to_string());
        assert_eq!(message.as_ref().unwrap().get_content(), "Below Threshold".to_string());

        // check again before second read
        let message = controller.poll(time + Duration::seconds(1) + Duration::milliseconds(500));
        assert_eq!(controller.increase_output.get_state(), Some(true));
        assert_eq!(controller.decrease_output.get_state(), Some(false));

        assert!(message.is_none());

        // check second read which should be within tolerance
        let message = controller.poll(time + Duration::seconds(2));
        assert_eq!(controller.increase_output.get_state(), Some(false));
        assert_eq!(controller.decrease_output.get_state(), Some(false));

        assert!(message.is_some());
        assert_eq!(message.as_ref().unwrap().get_read_state().unwrap(), "10.5".to_string());
        assert_eq!(message.as_ref().unwrap().get_content(), "Within Tolerance".to_string());

        // check again before third read
        let message = controller.poll(time + Duration::seconds(2) + Duration::milliseconds(500));
        assert_eq!(controller.increase_output.get_state(), Some(false));
        assert_eq!(controller.decrease_output.get_state(), Some(false));

        assert!(message.is_none());

        // check third read which should be above threshold
        let message = controller.poll(time + Duration::seconds(3));
        assert_eq!(controller.increase_output.get_state(), Some(false));
        assert_eq!(controller.decrease_output.get_state(), Some(true));

        assert!(message.is_some());
        assert_eq!(message.as_ref().unwrap().get_read_state().unwrap(), "12.0".to_string());
        assert_eq!(message.as_ref().unwrap().get_content(), "Above Threshold".to_string());

        // check again after third read
        let message = controller.poll(time + Duration::seconds(3) + Duration::milliseconds(500));
        assert_eq!(controller.increase_output.get_state(), Some(false));
        assert_eq!(controller.decrease_output.get_state(), Some(true));

        assert!(message.is_none());
    }
}