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
use log::*;
use tokio::runtime::Runtime;

use crate::brain::python_like::config::PythonBrainConfig;
use crate::brain::python_like::control::heating_control::HeatPumpMode;
use crate::brain::BrainFailure;
use crate::expect_available;
use crate::io::IOBundle;
use crate::time_util::mytime::TimeProvider;

use super::intention::Intention;
use super::working_temp::{find_working_temp_action, CurrentHeatDirection, WorkingTempAction, MixedState};
use super::{InfoCache, Mode, allow_dhw_mixed, AllowDhwMixed};

/// Mode for running both heating and
#[derive(Debug, PartialEq)]
pub struct MixedMode {}

impl MixedMode {
    pub fn new() -> Self {
        Self { }
    }
}

impl Mode for MixedMode {
    fn enter(
        &mut self,
        _config: &PythonBrainConfig,
        _runtime: &Runtime,
        io_bundle: &mut IOBundle,
    ) -> Result<(), BrainFailure> {
        info!("Entering mixed mode");
        let heating = expect_available!(io_bundle.heating_control())?;
        heating.set_heat_pump(HeatPumpMode::MostlyHotWater, Some("Turning on HP when entering mode."))?;
        heating.set_heat_circulation_pump(true, Some("Turning on CP when entering mode."))
    }

    fn update(
        &mut self,
        rt: &Runtime,
        config: &PythonBrainConfig,
        info_cache: &mut InfoCache,
        io_bundle: &mut IOBundle,
        time: &impl TimeProvider,
    ) -> Result<Intention, BrainFailure> {
        if !info_cache.heating_on() {
            info!("Heating is no longer on");
            return Ok(Intention::finish());
        }

        let temps = match rt.block_on(info_cache.get_temps(io_bundle.temperature_manager())) {
            Err(err) => {
                error!("Temperatures not available, stopping overrun {err}");
                return Ok(Intention::off_now());
            },
            Ok(temps) => temps,
        };

        let now = time.get_utc_time();

        let slot = config.get_overrun_during().find_matching_slot(&now, &temps,
            |temps, temp| temp < temps.extra.unwrap_or(temps.max)
        );

        let Some(slot) = slot else {
            info!("No longer matches a DHW slot");
            return Ok(Intention::finish());
        };

        let allow_dhw_mixed = allow_dhw_mixed(&temps, slot, true);

        if matches!(allow_dhw_mixed, AllowDhwMixed::Force) {
            return Ok(Intention::KeepState)
        }

        match find_working_temp_action(
            &temps,
            &info_cache.get_working_temp_range(),
            &config.hp_circulation,
            CurrentHeatDirection::Climbing,
            Some(MixedState::MixedHeating),
            Some(slot),
        ) {
            Ok(WorkingTempAction::Heat { mixed_state }) => {
                match allow_dhw_mixed {
                    AllowDhwMixed::Error  => Ok(Intention::off_now()),
                    AllowDhwMixed::Can    => {
                        if mixed_state == MixedState::MixedHeating {
                            Ok(Intention::KeepState)
                        }
                        else {
                            Ok(Intention::finish())
                        }
                    }
                    AllowDhwMixed::Force  => { error!("Believed impossible"); Ok(Intention::finish()) },
                    AllowDhwMixed::Cannot => Ok(Intention::finish()),
                }
            }
            Ok(WorkingTempAction::Cool { .. }) => Ok(Intention::finish()),
            Err(missing_sensor) => {
                error!(
                    "Could not check whether to circulate due to missing sensor: {}. Turning off",
                    missing_sensor
                );
                Ok(Intention::off_now())
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use tokio::runtime::Runtime;

    use crate::brain::modes::intention::Intention;
    use crate::brain::modes::working_temp::{WorkingRange, WorkingTemperatureRange};
    use crate::brain::modes::{HeatingState, InfoCache, Mode};
    use crate::brain::python_like::config::PythonBrainConfig;
    use crate::brain::BrainFailure;
    use crate::brain::python_like::config::overrun_config::DhwBap;
    use crate::io::dummy_io_bundle::new_dummy_io;
    use crate::io::temperatures::Sensor;
    use crate::time_util::mytime::DummyTimeProvider;
    use crate::time_util::test_utils::{utc_datetime, utc_time_slot};

    use super::MixedMode;

    #[test]
    fn test_finish_when_wiser_off() -> Result<(), BrainFailure> {
        let mut config = PythonBrainConfig::default();
        let (mut io_bundle, mut handle) = new_dummy_io();
        let range = WorkingRange::from_temp_only(WorkingTemperatureRange::from_min_max(20.0, 60.0));
        let mut info_cache = InfoCache::create(HeatingState::OFF, range.clone());
        let rt = Runtime::new().unwrap();
        let time_provider = DummyTimeProvider::new(utc_datetime(2023, 11, 14, 12, 0, 0));

        config._add_dhw_slot(DhwBap::_new(
            utc_time_slot(11,0,0, 15,30,20),
            Sensor::TKBT, 0.0, 40.0,
        ));

        handle.send_temp(Sensor::HXIF, 59.0);
        handle.send_temp(Sensor::HXIR, 59.0);
        handle.send_temp(Sensor::HXOR, 59.0);
        handle.send_temp(Sensor::TKBT, 35.5);
        handle.send_temp(Sensor::HPRT, 50.0);

        let mut mode = MixedMode::new();

        mode.enter(&config, &rt, &mut io_bundle)?;

        let intention = mode.update(
            &rt,
            &config,
            &mut info_cache,
            &mut io_bundle,
            &time_provider,
        )?;

        assert_eq!(intention, Intention::Finish);

        Ok(())
    }

    #[test]
    fn test_finish_when_temp_reached() -> Result<(), BrainFailure> {
        let mut config = PythonBrainConfig::default();
        let (mut io_bundle, mut handle) = new_dummy_io();
        let range = WorkingRange::from_temp_only(WorkingTemperatureRange::from_min_max(20.0, 60.0));
        let mut info_cache = InfoCache::create(HeatingState::ON, range.clone());
        let rt = Runtime::new().unwrap();
        let time_provider = DummyTimeProvider::new(utc_datetime(2023, 11, 14, 12, 0, 0));

        config._add_dhw_slot(DhwBap::_new(
            utc_time_slot(11,0,0, 15,30,20),
            Sensor::TKBT, 0.0, 40.0,
        ));

        handle.send_temp(Sensor::HXIF, 59.0);
        handle.send_temp(Sensor::HXIR, 59.0);
        handle.send_temp(Sensor::HXOR, 59.0);
        handle.send_temp(Sensor::TKBT, 40.5);
        handle.send_temp(Sensor::HPRT, 50.0);

        let mut mode = MixedMode::new();

        mode.enter(&config, &rt, &mut io_bundle)?;

        let intention = mode.update(
            &rt,
            &config,
            &mut info_cache,
            &mut io_bundle,
            &time_provider,
        )?;

        assert_eq!(intention, Intention::Finish);

        Ok(())
    }

    #[test]
    fn test_continue_when_wiser_on_and_within_temp() -> Result<(), BrainFailure> {
        let mut config = PythonBrainConfig::default();
        let (mut io_bundle, mut handle) = new_dummy_io();
        let range = WorkingRange::from_temp_only(WorkingTemperatureRange::from_min_max(20.0, 60.0));
        let mut info_cache = InfoCache::create(HeatingState::ON, range.clone());
        let rt = Runtime::new().unwrap();
        let time_provider = DummyTimeProvider::new(utc_datetime(2023, 11, 14, 12, 0, 0));

        config._add_dhw_slot(DhwBap::_new(
            utc_time_slot(11,0,0, 15,30,20),
            Sensor::TKBT, 0.0, 40.0,
        ));

        handle.send_temp(Sensor::HXIF, 59.0);
        handle.send_temp(Sensor::HXIR, 59.0);
        handle.send_temp(Sensor::HXOR, 59.0);
        handle.send_temp(Sensor::TKBT, 35.5);

        handle.send_temp(Sensor::TKFL, 20.0);
        handle.send_temp(Sensor::HPFL, 30.0);
        handle.send_temp(Sensor::HPRT, 50.0);

        let mut mode = MixedMode::new();

        mode.enter(&config, &rt, &mut io_bundle)?;

        let intention = mode.update(
            &rt,
            &config,
            &mut info_cache,
            &mut io_bundle,
            &time_provider,
        )?;

        assert_eq!(intention, Intention::KeepState);

        Ok(())
    }

    #[test]
    fn test_finish_when_wiser_on_and_below_temp() -> Result<(), BrainFailure> {
        let mut config = PythonBrainConfig::default();
        let (mut io_bundle, mut handle) = new_dummy_io();
        let range = WorkingRange::from_temp_only(WorkingTemperatureRange::from_min_max(20.0, 60.0));
        let mut info_cache = InfoCache::create(HeatingState::ON, range.clone());
        let rt = Runtime::new().unwrap();
        let time_provider = DummyTimeProvider::new(utc_datetime(2023, 11, 14, 12, 0, 0));

        config._add_dhw_slot(DhwBap::_new(
            utc_time_slot(11,0,0, 15,30,20),
            Sensor::TKBT, 36.0, 40.0,
        ));

        handle.send_temp(Sensor::HXIF, 59.0);
        handle.send_temp(Sensor::HXIR, 59.0);
        handle.send_temp(Sensor::HXOR, 59.0);
        handle.send_temp(Sensor::TKBT, 35.5);

        handle.send_temp(Sensor::TKFL, 20.0);
        handle.send_temp(Sensor::HPFL, 30.0);
        handle.send_temp(Sensor::HPRT, 50.0);

        let mut mode = MixedMode::new();

        mode.enter(&config, &rt, &mut io_bundle)?;

        let intention = mode.update(
            &rt,
            &config,
            &mut info_cache,
            &mut io_bundle,
            &time_provider,
        )?;

        assert_eq!(intention, Intention::Finish);

        Ok(())
    }
}