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
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
use crate::brain::{modes::heating_mode::PossibleTemperatureContainer, python_like::config::overrun_config::DhwBap};
use crate::brain::python_like::config::heat_pump_circulation::HeatPumpCirculationConfig;
use crate::brain::python_like::config::working_temp_model::WorkingTempModelConfig;
use crate::io::temperatures::Sensor;
use crate::io::wiser::hub::WiserRoomData;
use crate::python_like::FallbackWorkingRange;
use crate::wiser::hub::RetrieveDataError;
use log::{debug, error, info};
use serde::Deserialize;
use std::fmt::{Debug, Display, Formatter};

const UNKNOWN_ROOM: &str = "Unknown";

#[derive(Clone)]
pub struct WorkingRange {
    temp_range: WorkingTemperatureRange,
    room: Option<Room>,
}

impl WorkingRange {
    pub fn from_wiser(temp_range: WorkingTemperatureRange, room: Room) -> Self {
        Self {
            temp_range: temp_range.clone(),
            room: Some(room),
        }
    }

    pub fn from_temp_only(temp_range: WorkingTemperatureRange) -> Self {
        Self {
            temp_range: temp_range.clone(),
            room: None,
        }
    }

    pub fn get_min(&self) -> f32 {
        self.temp_range.min
    }

    pub fn get_max(&self) -> f32 {
        self.temp_range.max
    }

    pub fn get_temperature_range(&self) -> &WorkingTemperatureRange {
        &self.temp_range
    }

    pub fn get_room(&self) -> Option<&Room> {
        self.room.as_ref()
    }
}

impl Display for WorkingRange {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "Room ")?;
        match &self.room {
            None => write!(f, "N/A: ",)?,
            Some(room) => {
                write!(f, "{} (diff: {:.1}", room.name, room.difference)?;
                if room.capped_difference != room.difference {
                    write!(f, ", cap: {:.1}", room.capped_difference)?;
                }
                write!(f, "); ")?;
            }
        }
        write!(
            f,
            "Working Range {:.2}-{:.2}",
            self.get_min(),
            self.get_max()
        )?;
        Ok(())
    }
}

#[derive(Clone)]
pub struct Room {
    name: String,
    difference: f32,
    capped_difference: f32,
}

impl Room {
    pub fn of(name: String, difference: f32, capped_difference: f32) -> Self {
        Self {
            name,
            difference,
            capped_difference,
        }
    }

    pub fn get_difference(&self) -> f32 {
        self.capped_difference
    }
}

#[derive(Clone, Deserialize, PartialEq)]
pub struct WorkingTemperatureRange {
    max: f32,
    min: f32,
}

impl WorkingTemperatureRange {
    pub fn from_delta(max: f32, delta: f32) -> Self {
        assert!(delta > 0.0);
        WorkingTemperatureRange {
            max,
            min: max - delta,
        }
    }

    pub fn from_min_max(min: f32, max: f32) -> Self {
        assert!(max > min, "Max should be greater than min.");
        WorkingTemperatureRange { max, min }
    }
}

impl Debug for WorkingTemperatureRange {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "WorkingTemperatureRange {{ min: {:.2} max: {:.2} }}",
            self.min, self.max
        )
    }
}

impl Display for WorkingTemperatureRange {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{:.2}-{:.2}", self.min, self.max)
    }
}

// Cap the maximum room temperature in order to make boosts at high temperatures
// increase just the time rather than the temperature
const MAX_ROOM_TEMP: f32 = 21.0;

fn get_working_temperature(
    data: &[WiserRoomData],
    working_temp_config: &WorkingTempModelConfig,
) -> WorkingRange {
    let difference = data
        .iter()
        .filter(|room| room.get_temperature() > -10.0) // Low battery or something.
        .map(|room| {
            (
                room.get_name().unwrap_or(UNKNOWN_ROOM),
                room.get_set_point().min(MAX_ROOM_TEMP) - room.get_temperature(),
            )
        })
        .max_by(|a, b| a.1.total_cmp(&b.1))
        .unwrap_or((UNKNOWN_ROOM, 0.0));

    let (range, capped_difference) =
        get_working_temperature_from_max_difference(difference.1, working_temp_config);

    let room = Room::of(difference.0.to_owned(), difference.1, capped_difference);

    WorkingRange::from_wiser(range, room)
}

fn get_working_temperature_from_max_difference(
    difference: f32,
    config: &WorkingTempModelConfig,
) -> (WorkingTemperatureRange, f32) {
    (
        WorkingTemperatureRange::from_min_max(
            config.min.get_temp_from_room_diff(difference),
            config.max.get_temp_from_room_diff(difference)
        ),
        difference,
    )
}

pub fn get_working_temperature_range_from_wiser_data(
    fallback: &mut FallbackWorkingRange,
    result: Result<Vec<WiserRoomData>, RetrieveDataError>,
    working_temp_config: &WorkingTempModelConfig,
) -> WorkingRange {
    result
        .ok()
        .filter(|data| {
            let good_data = data.iter().any(|r| r.get_temperature() > -10.0);
            if !good_data {
                error!(target: "wiser", "Bad data detected: no rooms with sensible temperatures");
                error!(target: "wiser", "{:?}", data);
            }
            good_data
        })
        .map(|data| {
            let working_range = get_working_temperature(&data, working_temp_config);
            fallback.update(working_range.get_temperature_range().clone());
            working_range
        })
        .unwrap_or_else(|| WorkingRange::from_temp_only(fallback.get_fallback().clone()))
}

/// Which way we are currently travelling within the working range.
pub enum CurrentHeatDirection {
    /// Just started up. Fine to go either up or down.
    None,
    /// Already climbing / temperature rising, only start circulating once we hit the top.
    Climbing,
    /// Already falling (circulating already), only stop circulating once we hit the bottom.
    Falling,
}

/// What to do about the working temp in order to stay within the required range.
#[derive(PartialEq, Debug)]
pub enum WorkingTempAction {
    /// Heat up - we are below the top.
    Heat { mixed_state: MixedState },
    /// Circulate (i.e. cool down)
    Cool { circulate: bool },
}

/// Whether in mixed mode i.e. whether heating and hot water both being heated
#[derive(PartialEq, Debug)]
pub enum MixedState {
    /// Both heating and hot water being heated
    MixedHeating,
    /// Heating boosted from hot water
    BoostedHeating,
    /// Not mixed
    NotMixed,
}

/// Forecasts what the Heat Exchanger temperature is likely to be soon based on the temperature of HXOR since
/// it will drop quickly if HXOR is low (and hence maybe we should go straight to On).
/// Returns the forecasted temperature, or the sensor that was missing.
pub fn find_working_temp_action(
    temps:          &impl PossibleTemperatureContainer,
    range:          &WorkingRange,
    config:         &HeatPumpCirculationConfig,
    heat_direction: CurrentHeatDirection,
    mixed_state:    Option<MixedState>,
    dhw_slot:       Option<&DhwBap>,
) -> Result<WorkingTempAction, Sensor> {
    let hx_pct = forecast_hx_pct(temps, config, &heat_direction, range)?;

    // Only cause 1 log if needed.
    let mut tk_pct_cached = None;
    let mut get_tk_pct = || -> Result<f32, Sensor> {
        if tk_pct_cached.is_none() {
            tk_pct_cached = Some(forecast_tk_pct(temps, config, &heat_direction, range)?);
        }
        Ok(tk_pct_cached.unwrap())
    };

    let should_cool = match heat_direction {
        CurrentHeatDirection::Falling => hx_pct >= 0.0,
        CurrentHeatDirection::Climbing => hx_pct >= 1.0,
        CurrentHeatDirection::None => {
            let tk_pct = get_tk_pct()?;

            // Happy to circulate first
            let hx_above_req = hx_pct >= config.forecast_start_above_percent;
            // Happy to drain from tank first
            let tk_above_req = tk_pct >= config.forecast_start_above_percent;

            hx_above_req || tk_above_req
        }
    };

    let (required_pct, used_tk) = match heat_direction {
        CurrentHeatDirection::None => (Some(config.forecast_start_above_percent), true),
        _ => (None, false),
    };
    if should_cool || used_tk {
        info!(
            "HX Forecast ({}), TK Forecast ({})",
            format_pct(hx_pct, required_pct),
            format_pct(get_tk_pct()?, required_pct)
        )
    } else {
        info!("HX Forecast ({})", format_pct(hx_pct, required_pct))
    }

    if !should_cool {
        return Ok(WorkingTempAction::Heat { mixed_state: get_mixed_state(temps, config, mixed_state, hx_pct, dhw_slot)? });
    }

    Ok(WorkingTempAction::Cool {
        circulate: temps.get_sensor_temp(&Sensor::TKBT).ok_or(Sensor::TKBT)? > temps.get_sensor_temp(&Sensor::HXOF).ok_or(Sensor::HXOF)?,
    })
}

fn get_mixed_state(
    temps:          &impl PossibleTemperatureContainer,
    config:         &HeatPumpCirculationConfig,
    mixed_state:    Option<MixedState>,
    hx_pct:         f32,
    dhw_slot:       Option<&DhwBap>,
) -> Result<MixedState, Sensor> {
    if let Some(mixed_state) = mixed_state {
        // Possible candidate for boosting. This is where the heat pump is on, but the values and pump speeds
        // are such that some the the water from HXRT enters the tank heat exchanger at TKRT, gets heated and
        // comes out at TKFL (flowing in the reverse of the normal direction) to join the flow from HPFL.
        // On an energy flow analysis this will provide a boost if TKFL > HXRT, but perhaps only by throttling
        // the flow through the heat pump which reduces its efficiency. A more conservative view is to only
        // boost if TKFL > HPFL which will directly enrich HXFL.
        // There remains the problem that TKFL and HPFL are only fully accurate for this purpose when water is
        // flowing through them and the sensors have had time to respond. Other cases are considered below:
        // * Tank has just been heated: TKFL will be a significant over-estimate of what would flow from
        // the tank, but it will be similar to HPFL so unlikely to be an issue. If nothing has happened since
        // the it is reasonable to expect TKFL to fall quicker than HPFL so also not an issue.
        // * Tank heated then switched to heating: TKFL will be an overestimate and HPFL will likely be
        // materially lower. This is a risk this will incorrectly trigger boosting for a short while.
        // * Tank not heated recently: Experience suggests that TKFL will be influenced by bleed across from
        // HPFL as much as the actual tank temperature. This will often pull it down causeing the boost to
        // fail to trigger when it should.
        // * Was recently circulating from tank: TKFL will be accurate, but HPFL could be too high if heat
        // has been retained in the system. This will soon be resolved when the heat pump switches on.
        // In summary, the threshold differency between TKFL and HPFL needs to be tunable. Hysteresis is
        // suspected not to be required, but might as well be provided.
        let tkfl = temps.get_sensor_temp(&Sensor::TKFL).ok_or(Sensor::TKFL)?;
        let hpfl = temps.get_sensor_temp(&Sensor::HPFL).ok_or(Sensor::HPFL)?;

        let slot_margin = if let Some(dhw_slot) = dhw_slot {
            let temp = temps.get_sensor_temp(&dhw_slot.temps.sensor).ok_or(dhw_slot.temps.sensor.clone())?;
            *temp - dhw_slot.temps.min
        }
        else {
            0.0
        };


        match mixed_state {
            MixedState::BoostedHeating => {
                if hx_pct      <  config.boost_mode.stop_heat_pct &&
                   tkfl - hpfl >= config.boost_mode.stop_tkfl_hpfl_diff &&
                   slot_margin >  config.boost_mode.stop_slot_min_diff {
                        return Ok(MixedState::BoostedHeating)
                }
            }
            MixedState::NotMixed | MixedState::MixedHeating => {
                if hx_pct      <  config.boost_mode.start_heat_pct &&
                   tkfl - hpfl >= config.boost_mode.start_tkfl_hpfl_diff &&
                   slot_margin >  config.boost_mode.start_slot_min_diff {
                        return Ok(MixedState::BoostedHeating)
                }
            }
        }

        match mixed_state {
            MixedState::MixedHeating => 
                if hx_pct > config.mixed_mode.stop_heat_pct {
                    return Ok(MixedState::MixedHeating)
                }
            MixedState::NotMixed | MixedState::BoostedHeating =>
                if hx_pct > config.mixed_mode.start_heat_pct {
                    return Ok(MixedState::MixedHeating)
                }
        }
    }

    return Ok(MixedState::NotMixed);
}

fn format_pct(pct: f32, required_pct: Option<f32>) -> String {
    if pct > 1.0 {
        "HI".to_owned()
    } else if pct < -0.995 {
        "LO".to_owned()
    } else {
        match required_pct {
            Some(required) => format!("{:.0}%, req. {:.0}%", pct * 100.0, required * 100.0),
            _ => format!("{:.0}%", pct * 100.0),
        }
    }
}



fn forecast_hx_pct(
    temps: &impl PossibleTemperatureContainer,
    config: &HeatPumpCirculationConfig,
    heat_direction: &CurrentHeatDirection,
    range: &WorkingRange,
) -> Result<f32, Sensor> {
    let hxif = temps.get_sensor_temp(&Sensor::HXIF).ok_or(Sensor::HXIF)?;
    let hxir = temps.get_sensor_temp(&Sensor::HXIR).ok_or(Sensor::HXIR)?;
    let hxor = temps.get_sensor_temp(&Sensor::HXOR).ok_or(Sensor::HXOR)?;
    let hprt = temps.get_sensor_temp(&Sensor::HPRT).ok_or(Sensor::HPRT)?;

    let hxia = (hxif + hxir) / 2.0;
    
    let adjusted_difference = (hxia - hxor) - config.forecast_diff_offset;
    let expected_drop = adjusted_difference * config.forecast_diff_proportion;
    let expected_drop = expected_drop.clamp(0.0, 25.0);
    let hxia_forecast_raw = hxia - expected_drop;

    let hxia_forecast = merge_hprt_into_fhxia(hxia_forecast_raw, *hprt);
    
    let range_width = range.get_max() - range.get_min();

    let hx_pct = (hxia_forecast - range.get_min()) / range_width;

    let required_pct = match heat_direction {
        CurrentHeatDirection::None => Some(config.forecast_start_above_percent),
        _ => None,
    };

    debug!(
        "HXIA: {hxia:.2}, HXOR: {hxor:.2} => HXIA forecast: {hxia_forecast_raw:.2}/{hxia_forecast:.2} ({})",
        format_pct(hx_pct, required_pct),
    );

    Ok(hx_pct)
}

fn forecast_tk_pct(
    temps: &impl PossibleTemperatureContainer,
    config: &HeatPumpCirculationConfig,
    heat_direction: &CurrentHeatDirection,
    range: &WorkingRange,
) -> Result<f32, Sensor> {
    let tkbt = temps.get_sensor_temp(&Sensor::TKBT).ok_or(Sensor::TKBT)?;
    let hxor = temps.get_sensor_temp(&Sensor::HXOR).ok_or(Sensor::HXOR)?;
    let hxia = tkbt - config.forecast_tkbt_hxia_drop;

    let adjusted_difference = (hxia - hxor) - config.forecast_diff_offset;
    let expected_drop = adjusted_difference * config.forecast_diff_proportion;
    let expected_drop = expected_drop.clamp(0.0, 25.0);
    let hxia_forecast = (hxia - expected_drop).clamp(0.0, 100.0);

    let range_width = range.get_max() - range.get_min();

    let tk_pct = (hxia_forecast - range.get_min()) / range_width;

    let required_pct = match heat_direction {
        CurrentHeatDirection::None => Some(config.forecast_start_above_percent),
        _ => None,
    };

    debug!(
        "TKBT: {tkbt:.2}, HXOR: {hxor:.2} => HXIA forecast: {hxia_forecast:.2} ({})",
        format_pct(tk_pct, required_pct),
    );

    Ok(tk_pct)
}

/// Gradually switch from using forecast HXI to using HPRT as temperatures get higher
/// This may result in higher or lower circulation temps, but either way it aligns the
/// top end of the range with the hard heatpump limit of 55deg HPRT.
fn merge_hprt_into_fhxia(fhxia: f32, hprt: f32) -> f32 {
    const HPRT_LO_LIMIT: f32 = 50.0;
    const HPRT_HI_LIMIT: f32 = 55.0;

    // Either variables could be lower, but as either approach a maximum of 55 more emphasis needs
    // to be given to HPRT as ultimately this is what will cut off the heat pump. Also may be switching
    // from fhxia to hxoa at some point as a measure of output rather than effort.
    //let lower = fhxia.min(hprt);

    if hprt > HPRT_HI_LIMIT {
        hprt
    }
    else {
        let pct_hprt = ((hprt.max(hprt) - HPRT_LO_LIMIT) / (HPRT_HI_LIMIT - HPRT_LO_LIMIT)).clamp(0.0, 1.0);
        fhxia*(1.0-pct_hprt) + hprt*pct_hprt
    }
}

#[allow(clippy::zero_prefixed_literal)]
#[cfg(test)]
mod test {
    use crate::brain::python_like::config::PythonBrainConfig;
    
    use super::*;
    use std::{collections::HashMap, ops::Range};

    #[test]
    fn test_merge_hprt_into_fhxia_basic() {
        assert_eq!(merge_hprt_into_fhxia(50.0, 50.0), 50.0);
        assert_eq!(merge_hprt_into_fhxia(50.0, 55.0), 55.0);
        assert_eq!(merge_hprt_into_fhxia(40.0, 55.0), 55.0);
        assert_eq!(merge_hprt_into_fhxia(00.0, 55.0), 55.0);
    }

    #[test]
    fn test_merge_hprt_into_fhxia1() {
        // Must not bring fHXIA down at the top
        assert_range_float(merge_hprt_into_fhxia(15.0, 54.9), 53.9..55.3)
    }

    #[test]
    fn test_merge_hprt_into_fhxia2() {
        // Can only go a little over fHXIA near the top even in extreme circumstances
        assert_range_float(merge_hprt_into_fhxia(70.0, 54.9), 54.9..55.3);
    }

    #[test]
    fn test_merge_hprt_into_fhxia3() {
        assert_range_float(merge_hprt_into_fhxia(15.0, 56.0), 56.0..57.0);
    }

    #[test]
    fn test_merge_hprt_into_fhxia4() {
        assert_range_float(merge_hprt_into_fhxia(54.66, 52.1), 52.1..54.0);
    }

    fn assert_range_float<T>(value: T, range: Range<T>)
    where T: num_traits::Float + Display {
        if !value.is_zero() && !value.is_normal() {
            panic!("Abnormal number {}", value);
        }
        if !(range.start <= value && value < range.end) {
            panic!("Violation of {} <= {} < {}", range.start, value, range.end);
        }
    }

    #[test]
    fn test_none_heat_not_mixed1() -> Result<(), Sensor> {
        test_none_heat_not_mixed(Some(MixedState::MixedHeating))
    }
    #[test]
    fn test_none_heat_not_mixed2() -> Result<(), Sensor> {
        test_none_heat_not_mixed(Some(MixedState::NotMixed))
    }
    #[test]
    fn test_none_heat_not_mixed3() -> Result<(), Sensor> {
        test_none_heat_not_mixed(None)
    }
    
    fn test_none_heat_not_mixed(mixed_state: Option<MixedState>) -> Result<(), Sensor> {
        let range = WorkingRange::from_temp_only(WorkingTemperatureRange::from_min_max(30.0, 40.0));
        let mut temps = HashMap::new();

        temps.insert(Sensor::HXIF, 30.5);
        temps.insert(Sensor::HXIR, 30.5);
        temps.insert(Sensor::HXOR, 30.5);
        temps.insert(Sensor::TKBT, 20.0);

        temps.insert(Sensor::TKFL, 20.0);
        temps.insert(Sensor::HPFL, 30.0);
        temps.insert(Sensor::HPRT, 50.0);

        let action = find_working_temp_action(
            &temps,
            &range,
            &PythonBrainConfig::default().hp_circulation,
            CurrentHeatDirection::None,
            mixed_state,
            None,
        )?;

        assert_eq!(WorkingTempAction::Heat { mixed_state: MixedState::NotMixed }, action);

        Ok(())
    }

    #[test]
    fn test_none_heat_from_tank() -> Result<(), Sensor> {
        let range = WorkingRange::from_temp_only(WorkingTemperatureRange::from_min_max(30.0, 40.0));
        let mut temps = HashMap::new();

        temps.insert(Sensor::HXIF, 25.0);
        temps.insert(Sensor::HXIR, 25.0);
        temps.insert(Sensor::HXOF, 25.0);
        temps.insert(Sensor::HXOR, 25.0);
        temps.insert(Sensor::TKBT, 60.0);
        temps.insert(Sensor::HPRT, 50.0);

        let action = find_working_temp_action(
            &temps,
            &range,
            &PythonBrainConfig::default().hp_circulation,
            CurrentHeatDirection::None,
            None, None,
        )?;

        assert_eq!(WorkingTempAction::Cool { circulate: true }, action);

        Ok(())
    }

    #[test]
    fn test_none_refuse_circulate() -> Result<(), Sensor> {
        let range = WorkingRange::from_temp_only(WorkingTemperatureRange::from_min_max(30.0, 40.0));
        let mut temps = HashMap::new();

        temps.insert(Sensor::HXIF, 40.5);
        temps.insert(Sensor::HXIR, 40.5);
        temps.insert(Sensor::HXOF, 40.5);
        temps.insert(Sensor::HXOR, 40.5);
        temps.insert(Sensor::TKBT, 20.0);
        temps.insert(Sensor::HPRT, 50.0);

        let action = find_working_temp_action(
            &temps,
            &range,
            &PythonBrainConfig::default().hp_circulation,
            CurrentHeatDirection::None,
            None, None,
        )?;

        assert_eq!(WorkingTempAction::Cool { circulate: false }, action);

        Ok(())
    }

    #[test]
    fn test_none_idle_when_tank_cold_but_hx_warm() -> Result<(), Sensor> {
        let range = WorkingRange::from_temp_only(WorkingTemperatureRange::from_min_max(30.0, 40.0));
        let mut temps = HashMap::new();

        temps.insert(Sensor::HXIF, 39.5);
        temps.insert(Sensor::HXIR, 39.5);
        temps.insert(Sensor::HXOF, 39.5);
        temps.insert(Sensor::HXOR, 39.5);
        temps.insert(Sensor::TKBT, 20.0);
        temps.insert(Sensor::HPRT, 50.0);

        let action = find_working_temp_action(
            &temps,
            &range,
            &PythonBrainConfig::default().hp_circulation,
            CurrentHeatDirection::None,
            None, None,
        )?;

        assert_eq!(WorkingTempAction::Cool { circulate: false }, action);

        Ok(())
    }

    #[test]
    fn test_cool_using_idle_when_reach_top() -> Result<(), Sensor> {
        let range = WorkingRange::from_temp_only(WorkingTemperatureRange::from_min_max(30.0, 40.0));
        let mut temps = HashMap::new();

        temps.insert(Sensor::HXIF, 40.5);
        temps.insert(Sensor::HXIR, 40.5);
        temps.insert(Sensor::HXOF, 40.5);
        temps.insert(Sensor::HXOR, 40.5);
        temps.insert(Sensor::TKBT, 20.0);
        temps.insert(Sensor::HPRT, 50.0);

        let action = find_working_temp_action(
            &temps,
            &range,
            &PythonBrainConfig::default().hp_circulation,
            CurrentHeatDirection::Climbing,
            None, None,
        )?;

        assert_eq!(WorkingTempAction::Cool { circulate: false }, action);

        Ok(())
    }

    #[test]
    fn test_mixed_when_reach_high_in_range() -> Result<(), Sensor> {
        let range = WorkingRange::from_temp_only(WorkingTemperatureRange::from_min_max(30.0, 40.0));
        let mut temps = HashMap::new();

        temps.insert(Sensor::HXIF, 39.5);
        temps.insert(Sensor::HXIR, 39.5);
        temps.insert(Sensor::HXOR, 39.5);
        temps.insert(Sensor::TKBT, 30.0);

        temps.insert(Sensor::TKFL, 20.0);
        temps.insert(Sensor::HPFL, 30.0);
        temps.insert(Sensor::HPRT, 50.0);

        let action = find_working_temp_action(
            &temps,
            &range,
            &PythonBrainConfig::default().hp_circulation,
            CurrentHeatDirection::Climbing,
            Some(MixedState::NotMixed),
            None,
        )?;

        assert_eq!(WorkingTempAction::Heat { mixed_state: MixedState::MixedHeating }, action);

        Ok(())
    }

    #[test]
    fn test_stay_in_mixed_at_high() -> Result<(), Sensor> {
        let range = WorkingRange::from_temp_only(WorkingTemperatureRange::from_min_max(30.0, 40.0));
        let mut temps = HashMap::new();

        temps.insert(Sensor::HXIF, 39.5);
        temps.insert(Sensor::HXIR, 39.5);
        temps.insert(Sensor::HXOR, 39.5);
        temps.insert(Sensor::TKBT, 30.0);

        temps.insert(Sensor::TKFL, 20.0);
        temps.insert(Sensor::HPFL, 30.0);
        temps.insert(Sensor::HPRT, 50.0);

        let action = find_working_temp_action(
            &temps,
            &range,
            &PythonBrainConfig::default().hp_circulation,
            CurrentHeatDirection::Climbing,
            Some(MixedState::MixedHeating),
            None,
        )?;

        assert_eq!(WorkingTempAction::Heat { mixed_state: MixedState::MixedHeating }, action);

        Ok(())
    }

    #[test]
    fn test_not_mixed_when_lower() -> Result<(), Sensor> {
        let range = WorkingRange::from_temp_only(WorkingTemperatureRange::from_min_max(30.0, 40.0));
        let mut temps = HashMap::new();

        temps.insert(Sensor::HXIF, 35.0);
        temps.insert(Sensor::HXIR, 35.0);
        temps.insert(Sensor::HXOR, 35.0);
        temps.insert(Sensor::TKBT, 30.0);

        temps.insert(Sensor::TKFL, 20.0);
        temps.insert(Sensor::HPFL, 30.0);
        temps.insert(Sensor::HPRT, 50.0);

        let action = find_working_temp_action(
            &temps,
            &range,
            &PythonBrainConfig::default().hp_circulation,
            CurrentHeatDirection::Climbing,
            Some(MixedState::NotMixed),
            None,
        )?;

        assert_eq!(WorkingTempAction::Heat { mixed_state: MixedState::NotMixed }, action);

        Ok(())
    }

    #[test]
    fn test_stay_in_mixed_when_lower() -> Result<(), Sensor> {
        let range = WorkingRange::from_temp_only(WorkingTemperatureRange::from_min_max(30.0, 40.0));
        let mut temps = HashMap::new();

        temps.insert(Sensor::HXIF, 35.0);
        temps.insert(Sensor::HXIR, 35.0);
        temps.insert(Sensor::HXOR, 35.0);
        temps.insert(Sensor::TKBT, 30.0);

        temps.insert(Sensor::TKFL, 20.0);
        temps.insert(Sensor::HPFL, 30.0);
        temps.insert(Sensor::HPRT, 50.0);

        let action = find_working_temp_action(
            &temps,
            &range,
            &PythonBrainConfig::default().hp_circulation,
            CurrentHeatDirection::Climbing,
            Some(MixedState::MixedHeating),
            None,
        )?;

        assert_eq!(WorkingTempAction::Heat { mixed_state: MixedState::MixedHeating }, action);

        Ok(())
    }

    #[test]
    fn test_exit_mixed_when_lower_still() -> Result<(), Sensor> {
        let range = WorkingRange::from_temp_only(WorkingTemperatureRange::from_min_max(30.0, 40.0));
        let mut temps = HashMap::new();

        temps.insert(Sensor::HXIF, 31.0);
        temps.insert(Sensor::HXIR, 31.0);
        temps.insert(Sensor::HXOR, 31.0);
        temps.insert(Sensor::TKBT, 30.0);

        temps.insert(Sensor::TKFL, 20.0);
        temps.insert(Sensor::HPFL, 30.0);
        temps.insert(Sensor::HPRT, 50.0);

        let action = find_working_temp_action(
            &temps,
            &range,
            &PythonBrainConfig::default().hp_circulation,
            CurrentHeatDirection::Climbing,
            Some(MixedState::MixedHeating),
            None,
        )?;

        assert_eq!(WorkingTempAction::Heat { mixed_state: MixedState::NotMixed }, action);

        Ok(())
    }

    #[test]
    fn test_cool_using_tank_when_reach_top() -> Result<(), Sensor> {
        let range = WorkingRange::from_temp_only(WorkingTemperatureRange::from_min_max(30.0, 40.0));
        let mut temps = HashMap::new();

        temps.insert(Sensor::HXIF, 40.5);
        temps.insert(Sensor::HXIR, 40.5);
        temps.insert(Sensor::HXOF, 40.5);
        temps.insert(Sensor::HXOR, 40.5);
        temps.insert(Sensor::TKBT, 45.0);
        temps.insert(Sensor::HPRT, 50.0);

        let action = find_working_temp_action(
            &temps,
            &range,
            &PythonBrainConfig::default().hp_circulation,
            CurrentHeatDirection::Climbing,
            None, None,
        )?;

        assert_eq!(WorkingTempAction::Cool { circulate: true }, action);

        Ok(())
    }

    #[test]
    fn test_heat_when_hit_bottom1() -> Result<(), Sensor> {
        let range = WorkingRange::from_temp_only(WorkingTemperatureRange::from_min_max(30.0, 40.0));
        let mut temps = HashMap::new();

        temps.insert(Sensor::HXIF, 29.5);
        temps.insert(Sensor::HXIR, 29.5);
        temps.insert(Sensor::HXOF, 29.5);
        temps.insert(Sensor::HXOR, 29.5);
        temps.insert(Sensor::TKBT, 20.0);

        temps.insert(Sensor::TKFL, 20.0);
        temps.insert(Sensor::HPFL, 30.0);
        temps.insert(Sensor::HPRT, 50.0);

        let action = find_working_temp_action(
            &temps,
            &range,
            &PythonBrainConfig::default().hp_circulation,
            CurrentHeatDirection::Falling,
            Some(MixedState::MixedHeating),
            None,
        )?;

        assert_eq!(WorkingTempAction::Heat { mixed_state: MixedState::NotMixed }, action);

        Ok(())
    }

    #[test]
    fn test_heat_when_hit_bottom2() -> Result<(), Sensor> {
        let range = WorkingRange::from_temp_only(WorkingTemperatureRange::from_min_max(30.0, 40.0));
        let mut temps = HashMap::new();

        temps.insert(Sensor::HXIF, 29.5);
        temps.insert(Sensor::HXIR, 29.5);
        temps.insert(Sensor::HXOF, 29.5);
        temps.insert(Sensor::HXOR, 29.5);
        temps.insert(Sensor::TKBT, 20.0);

        temps.insert(Sensor::TKFL, 20.0);
        temps.insert(Sensor::HPFL, 30.0);
        temps.insert(Sensor::HPRT, 50.0);

        let action = find_working_temp_action(
            &temps,
            &range,
            &PythonBrainConfig::default().hp_circulation,
            CurrentHeatDirection::Falling,
            Some(MixedState::NotMixed),
            None,
        )?;

        assert_eq!(WorkingTempAction::Heat { mixed_state: MixedState::NotMixed }, action);

        Ok(())
    }
}