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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
use std::thread::sleep;
use std::time::Duration;

use crate::brain::python_like::control::heating_control::HeatPumpMode;
use crate::brain::BrainFailure;
use crate::config::ControlConfig;
use crate::io::controls::{translate_get_gpio, translate_set_gpio};
use crate::io::gpio::GPIOError;
use crate::python_like::control::heating_control::{HeatCirculationPumpControl, HeatPumpControl};
use crate::{brain_fail, GPIOManager, GPIOMode, HeatingControl};
use chrono::{Utc, DateTime};
use log::*;
use strum::IntoEnumIterator;

#[derive(Clone)]
pub struct GPIOPins {
    /// Turns on/off the heat pump and its valve
    pub heat_pump_pin: usize,
    /// Turns on/off the pump that pumps water through radiators
    pub heat_circulation_pump_pin: usize,
    /// Opens / closes the valve located just outside of TKRT.
    pub tank_valve_pin: usize,
    /// Opens / closes the valve between the TKFL and heat exchanger
    pub heating_valve_pin: usize,
    /// Turns on/off the pump between the TKFL and heat exchanger (next to the valve)
    pub heating_extra_pump: usize,
}

#[derive(Debug)]
enum Valve {
    /// Closing this valve will stop water going through the tank.
    Tank,
    /// Closing this valve will stop water going through the heating.
    Heating,
}

#[derive(Debug)]
enum Pump {
    /// The heat pump that actually heats the hot water.
    #[allow(clippy::enum_variant_names)]
    HeatPump,
    /// The pump in series (sometimes) with the heat pump that helps to increase the flow and is
    /// also used for circulating
    ExtraHeating,
    /// The pump that pushes water through the radiators
    HeatingCirculation,
}

pub struct GPIOHeatingControl<G: GPIOManager> {
    gpio_manager: G,
    pins: GPIOPins,
    should_sleep: bool,
    valve_start_open_time: Duration,
    valve_change_time: Duration,
    pump_water_slow_time: Duration,
    extra_heat_pump_water_slow_time: Duration,

    heat_pump_last_changed: DateTime<Utc>,
}

impl<G: GPIOManager> GPIOHeatingControl<G> {
    pub fn create(
        pins: GPIOPins,
        mut gpio_manager: G,
        control_config: &ControlConfig,
    ) -> Result<Self, GPIOError> {
        gpio_manager.setup(pins.heat_pump_pin, &GPIOMode::Output)?;
        gpio_manager.setup(pins.heat_circulation_pump_pin, &GPIOMode::Output)?;
        gpio_manager.setup(pins.tank_valve_pin, &GPIOMode::Output)?;
        gpio_manager.setup(pins.heating_valve_pin, &GPIOMode::Output)?;
        gpio_manager.setup(pins.heating_extra_pump, &GPIOMode::Output)?;
        Ok(Self {
            gpio_manager,
            pins,
            should_sleep: true,
            valve_start_open_time:           *control_config.get_valve_start_open_time(),
            valve_change_time:               *control_config.get_valve_change_time(),
            pump_water_slow_time:            *control_config.get_pump_water_slow_time(),
            extra_heat_pump_water_slow_time: *control_config.get_heat_pump_water_slow_time(),
            heat_pump_last_changed:          Utc::now(),
        })
    }

    #[cfg(test)]
    pub fn create_no_sleep(pins: GPIOPins, gpio_manager: G) -> Result<Self, GPIOError> {
        let mut control = Self::create(pins, gpio_manager, &ControlConfig::default())?;
        control.should_sleep = false;
        Ok(control)
    }

    fn get_valve_pin(&self, valve: &Valve) -> usize {
        match valve {
            Valve::Tank => self.pins.tank_valve_pin,
            Valve::Heating => self.pins.heating_valve_pin,
        }
    }

    fn get_pump_pin(&self, pump: &Pump) -> usize {
        match pump {
            Pump::HeatPump => self.pins.heat_pump_pin,
            Pump::ExtraHeating => self.pins.heating_extra_pump,
            Pump::HeatingCirculation => self.pins.heat_circulation_pump_pin,
        }
    }

    fn set_valve(&mut self, valve: &Valve, open: bool) -> Result<(), BrainFailure> {
        let pin = self.get_valve_pin(valve);
        debug!(
            "Changing {:?} Valve (GPIO: {}) to {}",
            valve,
            pin,
            to_valve_state(open)
        );
        translate_set_gpio(
            pin,
            &mut self.gpio_manager,
            open,
            &format!("Failed to set {:?} Valve pin", valve),
        )
    }

    fn get_valve(&self, valve: &Valve) -> Result<bool, BrainFailure> {
        let pin = self.get_valve_pin(valve);
        translate_get_gpio(
            pin,
            &self.gpio_manager,
            &format!("Failed to get {:?} Valve pin", valve),
        )
    }

    fn set_pump(&mut self, pump: &Pump, on: bool) -> Result<(), BrainFailure> {
        let pin = self.get_pump_pin(pump);
        debug!(
            "Changing {:?} Pump (GPIO: {}) to {}",
            pump,
            pin,
            to_valve_state(on)
        );
        translate_set_gpio(
            pin,
            &mut self.gpio_manager,
            on,
            &format!("Failed to set {:?} Pump pin", pump),
        )
    }

    fn get_pump(&self, pump: &Pump) -> Result<bool, BrainFailure> {
        let pin = self.get_pump_pin(pump);
        translate_get_gpio(
            pin,
            &self.gpio_manager,
            &format!("Failed to get {:?} Pump pin", pump),
        )
    }

    fn wait_for(&self, amount: Duration, why: &str) {
        let reason = format!("Waiting {}s for {}", amount.as_secs(), why);
        #[cfg(test)]
        if !self.should_sleep {
            warn!("TESTING - SKIPPING {}", reason);
            return;
        }
        debug!("{}", reason);
        sleep(amount);
    }

    fn switch_to_configuration(
        &mut self,
        config: &ValveAndPumpConfiguration,
    ) -> Result<(), BrainFailure> {
        // We need to be careful how any in what order / when we change the state of valves / pumps
        // to avoid causing unecessary pressure / stress on the pipework.
        //
        // 0. Stop the heat pump if it needs to be stoppd as it takes longer to stop.
        // 1. Stop any pumps that need to be stopped
        // 2. Wait for water to slow / pressure to reduce.
        // 3. Open any valves that need opening
        // 4. Wait for them to start opening as they take longer to open than close.
        // 5. Close any valves that need closing
        // 6. Wait for all valves to change.
        // 7. Start any pumps
        let mut hp_stopped = false;
        let mut xh_stopped = false;

        if !config.heat_pump_on {
            hp_stopped = self.change_pump_if_needed(&Pump::HeatPump, false)?;
        }

        if !config.extra_heating_pump_on {
            xh_stopped = self.change_pump_if_needed(&Pump::ExtraHeating, false)?;
        }

        if hp_stopped {
            self.wait_for(self.extra_heat_pump_water_slow_time, "HP pump to switch off");
        } else {
            debug!("Heat pump not stopped - not waiting.")
        }

        if xh_stopped || hp_stopped {
            self.wait_for(self.pump_water_slow_time, "Pumps / Water to slow");
        } else {
            debug!("No pumps stopped - not waiting.");
        }

        let any_valves_opened = self.update_valves_if_needed(config, true)?;
        if any_valves_opened {
            self.wait_for(self.valve_start_open_time, "Valves to start opening");
        } else {
            debug!("No valves to open - not waiting.");
        }

        let any_valves_closed = self.update_valves_if_needed(config, false)?;
        if any_valves_opened || any_valves_closed {
            self.wait_for(self.valve_change_time, "Valves to change");
        } else {
            debug!("No valves to open or close - not waiting.");
        }

        self.update_pumps_if_needed(config, true)?;

        Ok(())
    }

    /// Change pumps' state to the given state if they are not already in that state.
    /// To turn on pumps that need turning on, call with to: true
    /// To turn off pumps that need turning off, call with to: false
    fn update_pumps_if_needed(
        &mut self,
        config: &ValveAndPumpConfiguration,
        to: bool,
    ) -> Result<bool, BrainFailure> {
        let mut any_pumps_changed = false;
        if config.heat_pump_on == to && self.change_pump_if_needed(&Pump::HeatPump, to)? {
            any_pumps_changed = true;
        }

        if config.extra_heating_pump_on == to
            && self.change_pump_if_needed(&Pump::ExtraHeating, to)?
        {
            any_pumps_changed = true;
        }
        Ok(any_pumps_changed)
    }

    /// Change valves' state to the given state if they are not already in that state.
    /// To open valves that need opening, call with to: true
    /// To turn off pumps that need closing, call with to: false
    fn update_valves_if_needed(
        &mut self,
        config: &ValveAndPumpConfiguration,
        to: bool,
    ) -> Result<bool, BrainFailure> {
        let mut any_valves_changed = false;
        if config.heating_valve_open == to && self.change_valve_if_needed(&Valve::Heating, to)? {
            any_valves_changed = true;
        }

        if config.tank_valve_open == to && self.change_valve_if_needed(&Valve::Tank, to)? {
            any_valves_changed = true;
        }
        Ok(any_valves_changed)
    }

    /// Change the valve to the given state if needed.
    /// Returns whether the valve was changed.
    fn change_valve_if_needed(&mut self, valve: &Valve, open: bool) -> Result<bool, BrainFailure> {
        if self.get_valve(valve)? == open {
            trace!("{:?} was already {}", valve, to_valve_state(open));
            return Ok(false);
        }
        self.set_valve(valve, open)?;
        Ok(true)
    }

    /// Change the pump to the given state if needed.
    /// Returns whether the pump was changed.
    fn change_pump_if_needed(&mut self, pump: &Pump, open: bool) -> Result<bool, BrainFailure> {
        if self.get_pump(pump)? == open {
            trace!("{:?} was already {}", pump, to_pump_state(open));
            return Ok(false);
        }
        self.set_pump(pump, open)?;

        if matches!(pump, Pump::HeatPump) {
            self.heat_pump_last_changed = Utc::now();
        }
        
        Ok(true)
    }
}

impl<G: GPIOManager + 'static> HeatingControl for GPIOHeatingControl<G> {
    fn as_hp(&mut self) -> &mut dyn HeatPumpControl {
        self
    }

    fn as_cp(&mut self) -> &mut dyn HeatCirculationPumpControl {
        self
    }
}

impl HeatPumpMode {
    fn value_and_pump_configutation(&self) -> ValveAndPumpConfiguration {
        match self {
            HeatPumpMode::HotWaterOnly => ValveAndPumpConfiguration {
                heat_pump_on:          true,
                extra_heating_pump_on: false,
                tank_valve_open:       true,
                heating_valve_open:    false,
            },
            HeatPumpMode::HeatingOnly => ValveAndPumpConfiguration {
                heat_pump_on:          true,
                extra_heating_pump_on: true,
                tank_valve_open:       false,
                heating_valve_open:    true,
            },
            HeatPumpMode::MostlyHotWater => ValveAndPumpConfiguration {
                heat_pump_on:          true,
                extra_heating_pump_on: false,
                tank_valve_open:       true,
                heating_valve_open:    true,
            },
            HeatPumpMode::BoostedHeating => ValveAndPumpConfiguration {
                heat_pump_on:          true,
                extra_heating_pump_on: true,
                tank_valve_open:       true,
                heating_valve_open:    true,
            },
            HeatPumpMode::DrainTank => ValveAndPumpConfiguration {
                heat_pump_on:          false,
                extra_heating_pump_on: true,
                tank_valve_open:       true,
                heating_valve_open:    true,
            },
            HeatPumpMode::Off => ValveAndPumpConfiguration {
                heat_pump_on:          false,
                extra_heating_pump_on: false,
                tank_valve_open:       false,
                heating_valve_open:    false,
            },
        }
    }

}

impl<G: GPIOManager> HeatPumpControl for GPIOHeatingControl<G> {
    fn try_set_heat_pump(&mut self, mode: HeatPumpMode) -> Result<(), BrainFailure> {
        debug!("Changing to HeatPumpMode {:?}", mode);
        self.switch_to_configuration(&mode.value_and_pump_configutation())
    }

    fn try_get_heat_pump(&self) -> Result<HeatPumpMode, BrainFailure> {
        let cfg = ValveAndPumpConfiguration {
            heat_pump_on:          self.get_pump(&Pump::HeatPump)?,
            extra_heating_pump_on: self.get_pump(&Pump::ExtraHeating)?,
            tank_valve_open:       self.get_valve(&Valve::Tank)?,
            heating_valve_open:    self.get_valve(&Valve::Heating)?,
        };

        for mode in HeatPumpMode::iter() {
            if cfg == mode.value_and_pump_configutation() {
                return Ok(mode);
            }
        }

        error!("Unknown value_and_pump_configutation() = {cfg:?}");
        
        let msg = format!(
            "Value configuration was invalid: HP is on. Tank Valve: {}, Heating Valve: {}",
            to_valve_state(cfg.heating_valve_open),
            to_valve_state(cfg.heating_valve_open)
        );
        return Err(brain_fail!(&msg));
    }

    fn get_heat_pump_on_with_time(&self) -> Result<(bool, Duration), BrainFailure> {
        Ok((self.get_pump(&Pump::HeatPump)?, (Utc::now() - self.heat_pump_last_changed).to_std().expect("Time travelling")))
    }
}

impl<G: GPIOManager> HeatCirculationPumpControl for GPIOHeatingControl<G> {
    fn try_set_heat_circulation_pump(&mut self, on: bool) -> Result<(), BrainFailure> {
        self.set_pump(&Pump::HeatingCirculation, on)
    }

    fn try_get_heat_circulation_pump(&self) -> Result<bool, BrainFailure> {
        self.get_pump(&Pump::HeatingCirculation)
    }
}

fn to_valve_state(open: bool) -> String {
    match open {
        true => "Open",
        false => "Closed",
    }
    .to_owned()
}

fn to_pump_state(on: bool) -> String {
    match on {
        true => "On",
        false => "Off",
    }
    .to_owned()
}

#[derive(PartialEq, Debug)]
struct ValveAndPumpConfiguration {
    heat_pump_on:          bool,
    extra_heating_pump_on: bool,
    tank_valve_open:       bool,
    heating_valve_open:    bool,
}

#[cfg(test)]
mod test {
    use crate::brain::python_like::control::heating_control::{HeatPumpControl, HeatPumpMode};
    use crate::brain::BrainFailure;
    use crate::io::gpio::dummy::Dummy;
    use crate::io::gpio::{GPIOError, GPIOManager, GPIOState};

    use super::{GPIOHeatingControl, GPIOPins};

    const GPIO_PINS: GPIOPins = GPIOPins {
        heat_pump_pin: 1000,
        heat_circulation_pump_pin: 1001,
        tank_valve_pin: 1002,
        heating_valve_pin: 1003,
        heating_extra_pump: 1004,
    };

    #[test]
    fn test_get_and_set() -> Result<(), BrainFailure> {
        let gpio_manager = Dummy::default();
        let mut controls =
            GPIOHeatingControl::create_no_sleep(GPIO_PINS.clone(), gpio_manager).unwrap();

        fn check_pin(
            controls: &mut GPIOHeatingControl<impl GPIOManager>,
            pin: usize,
            expected: GPIOState,
        ) {
            assert_eq!(controls.gpio_manager.get_pin(pin).unwrap(), expected);
        }

        controls.try_set_heat_pump(HeatPumpMode::HotWaterOnly)?;
        assert_eq!(controls.try_get_heat_pump()?, HeatPumpMode::HotWaterOnly);
        check_pin(&mut controls, GPIO_PINS.heat_pump_pin, GPIOState::Low);
        check_pin(&mut controls, GPIO_PINS.heating_extra_pump, GPIOState::High);
        check_pin(&mut controls, GPIO_PINS.heating_valve_pin, GPIOState::High);
        check_pin(&mut controls, GPIO_PINS.tank_valve_pin, GPIOState::Low);

        controls.try_set_heat_pump(HeatPumpMode::MostlyHotWater)?;
        assert_eq!(controls.try_get_heat_pump()?, HeatPumpMode::MostlyHotWater);
        check_pin(&mut controls, GPIO_PINS.heat_pump_pin, GPIOState::Low);
        check_pin(&mut controls, GPIO_PINS.heating_extra_pump, GPIOState::High);
        check_pin(&mut controls, GPIO_PINS.heating_valve_pin, GPIOState::Low);
        check_pin(&mut controls, GPIO_PINS.tank_valve_pin, GPIOState::Low);

        controls.try_set_heat_pump(HeatPumpMode::HeatingOnly)?;
        assert_eq!(controls.try_get_heat_pump()?, HeatPumpMode::HeatingOnly);
        check_pin(&mut controls, GPIO_PINS.heat_pump_pin, GPIOState::Low);
        check_pin(&mut controls, GPIO_PINS.heating_extra_pump, GPIOState::Low);
        check_pin(&mut controls, GPIO_PINS.heating_valve_pin, GPIOState::Low);
        check_pin(&mut controls, GPIO_PINS.tank_valve_pin, GPIOState::High);

        controls.try_set_heat_pump(HeatPumpMode::DrainTank)?;
        assert_eq!(controls.try_get_heat_pump()?, HeatPumpMode::DrainTank);
        check_pin(&mut controls, GPIO_PINS.heat_pump_pin, GPIOState::High);
        check_pin(&mut controls, GPIO_PINS.heating_extra_pump, GPIOState::Low);
        check_pin(&mut controls, GPIO_PINS.heating_valve_pin, GPIOState::Low);
        check_pin(&mut controls, GPIO_PINS.tank_valve_pin, GPIOState::Low);

        controls.try_set_heat_pump(HeatPumpMode::Off)?;
        assert_eq!(controls.try_get_heat_pump()?, HeatPumpMode::Off);
        check_pin(&mut controls, GPIO_PINS.heat_pump_pin, GPIOState::High);
        check_pin(&mut controls, GPIO_PINS.heating_extra_pump, GPIOState::High);
        check_pin(&mut controls, GPIO_PINS.heating_valve_pin, GPIOState::High);
        check_pin(&mut controls, GPIO_PINS.tank_valve_pin, GPIOState::High);

        Ok(())
    }

    #[test]
    fn test_error_on_get_bad_valves() -> Result<(), GPIOError> {
        let gpio_manager = Dummy::default();
        let mut controls =
            GPIOHeatingControl::create_no_sleep(GPIO_PINS.clone(), gpio_manager).unwrap();

        controls
            .gpio_manager
            .set_pin(GPIO_PINS.heating_extra_pump, &GPIOState::Low)?;

        controls
            .gpio_manager
            .set_pin(GPIO_PINS.heating_valve_pin, &GPIOState::High)?;

        controls
            .gpio_manager
            .set_pin(GPIO_PINS.heat_pump_pin, &GPIOState::Low)?;

        match controls.try_get_heat_pump() {
            Ok(state) => panic!("Expected error, got: {:?}", state),
            Err(_) => Ok(()),
        }
    }

    #[test]
    fn test_off_works() -> Result<(), GPIOError> {
        let gpio_manager = Dummy::default();
        let mut controls =
            GPIOHeatingControl::create_no_sleep(GPIO_PINS.clone(), gpio_manager).unwrap();

        controls
            .try_set_heat_pump(HeatPumpMode::HeatingOnly)
            .expect("Should be able to go into HeatingOnly HeatPumpMode");

        controls
            .try_set_heat_pump(HeatPumpMode::Off)
            .expect("Should be able to turn off Heat pump");

        let gpio = controls.gpio_manager;
        assert_eq!(gpio.get_pin(GPIO_PINS.heat_pump_pin)?, GPIOState::High);
        assert_eq!(gpio.get_pin(GPIO_PINS.heating_extra_pump)?, GPIOState::High);
        assert_eq!(gpio.get_pin(GPIO_PINS.heating_valve_pin)?, GPIOState::High);
        assert_eq!(gpio.get_pin(GPIO_PINS.tank_valve_pin)?, GPIOState::High);

        Ok(())
    }

    #[test]
    fn test_heating_only_works() -> Result<(), GPIOError> {
        let gpio_manager = Dummy::default();
        let mut controls =
            GPIOHeatingControl::create_no_sleep(GPIO_PINS.clone(), gpio_manager).unwrap();

        controls
            .try_set_heat_pump(HeatPumpMode::Off)
            .expect("Should be able to turn off Heat pump");

        controls
            .try_set_heat_pump(HeatPumpMode::HeatingOnly)
            .expect("Should be able to go into HeatingOnly HeatPumpMode");

        let gpio = controls.gpio_manager;
        assert_eq!(gpio.get_pin(GPIO_PINS.heat_pump_pin)?, GPIOState::Low);
        assert_eq!(gpio.get_pin(GPIO_PINS.heating_extra_pump)?, GPIOState::Low);
        assert_eq!(gpio.get_pin(GPIO_PINS.heating_valve_pin)?, GPIOState::Low);
        assert_eq!(gpio.get_pin(GPIO_PINS.tank_valve_pin)?, GPIOState::High);

        Ok(())
    }

    #[test]
    fn test_hot_water_only_works() -> Result<(), GPIOError> {
        let gpio_manager = Dummy::default();
        let mut controls =
            GPIOHeatingControl::create_no_sleep(GPIO_PINS.clone(), gpio_manager).unwrap();

        controls
            .try_set_heat_pump(HeatPumpMode::Off)
            .expect("Should be able to turn off Heat pump");

        controls
            .try_set_heat_pump(HeatPumpMode::HotWaterOnly)
            .expect("Should be able to go into HotWaterOnly HeatPumpMode");

        let gpio = controls.gpio_manager;
        assert_eq!(gpio.get_pin(GPIO_PINS.heat_pump_pin)?, GPIOState::Low);
        assert_eq!(gpio.get_pin(GPIO_PINS.heating_extra_pump)?, GPIOState::High);
        assert_eq!(gpio.get_pin(GPIO_PINS.heating_valve_pin)?, GPIOState::High);
        assert_eq!(gpio.get_pin(GPIO_PINS.tank_valve_pin)?, GPIOState::Low);

        Ok(())
    }

    #[test]
    fn test_drain_tank_works() -> Result<(), GPIOError> {
        let gpio_manager = Dummy::default();
        let mut controls =
            GPIOHeatingControl::create_no_sleep(GPIO_PINS.clone(), gpio_manager).unwrap();

        controls
            .try_set_heat_pump(HeatPumpMode::Off)
            .expect("Should be able to turn off Heat pump");

        controls
            .try_set_heat_pump(HeatPumpMode::DrainTank)
            .expect("Should be able to go into DrainTank HeatPumpMode");

        let gpio = controls.gpio_manager;
        assert_eq!(gpio.get_pin(GPIO_PINS.heat_pump_pin)?, GPIOState::High);
        assert_eq!(gpio.get_pin(GPIO_PINS.heating_extra_pump)?, GPIOState::Low);
        assert_eq!(gpio.get_pin(GPIO_PINS.heating_valve_pin)?, GPIOState::Low);
        assert_eq!(gpio.get_pin(GPIO_PINS.tank_valve_pin)?, GPIOState::Low);

        Ok(())
    }

    #[test]
    fn test_mostly_hot_water_works() -> Result<(), GPIOError> {
        let gpio_manager = Dummy::default();
        let mut controls =
            GPIOHeatingControl::create_no_sleep(GPIO_PINS.clone(), gpio_manager).unwrap();

        controls
            .try_set_heat_pump(HeatPumpMode::Off)
            .expect("Should be able to turn off Heat pump");

        controls
            .try_set_heat_pump(HeatPumpMode::MostlyHotWater)
            .expect("Should be able to go into MostlyHotWater HeatPumpMode");

        let gpio = controls.gpio_manager;
        assert_eq!(gpio.get_pin(GPIO_PINS.heat_pump_pin)?, GPIOState::Low);
        assert_eq!(gpio.get_pin(GPIO_PINS.heating_extra_pump)?, GPIOState::High);
        assert_eq!(gpio.get_pin(GPIO_PINS.heating_valve_pin)?, GPIOState::Low);
        assert_eq!(gpio.get_pin(GPIO_PINS.tank_valve_pin)?, GPIOState::Low);

        Ok(())
    }
}