From fef5efb8095e10b4d0a40dd5ade50ff510cd9916 Mon Sep 17 00:00:00 2001
From: David Woodhouse <dwmw@amazon.co.uk>
Date: Fri, 10 May 2024 20:39:47 +0100
Subject: [PATCH] Adjust on/off thresholds for valve

---
 pool.yaml | 22 ++++++++++++++++------
 1 file changed, 16 insertions(+), 6 deletions(-)

diff --git a/pool.yaml b/pool.yaml
index 1e820ca..389217b 100644
--- a/pool.yaml
+++ b/pool.yaml
@@ -95,15 +95,24 @@ script:
         // seems to be reading *lower* than the output by about 0.1°C, so we
         // end up pumping heat into the sky, especially in the evenings. So
         // we now make the correction in the opposite direction.
-        intemp += 0.1;
-
-        if (outtemp == intemp)
-          return;
+        //
+        // Those tests with a single on/off threshold informed the 'off at 0,
+        // on at +0.3°C' logic we now have below.
 
         time_t now = ::time(NULL);
-        boolean want_state = outtemp > intemp;
+        boolean cur_state = id(valve_output).state;
+        boolean want_state = cur_state;
+        if (cur_state) {
+            // Only turn off if the output has got all the way down below the input temp
+            want_state = outtemp >= intemp;
+        } else {
+            // If already off but the roof is warming up, no need to turn it on
+            // too early; the water that's sitting there can continue to gather
+            // heat.
+            want_state = outtemp > intemp + 0.3;
+        }
 
-        if (id(valve_output).state == want_state) {
+        if (cur_state == want_state) {
             ESP_LOGD("control_valve", "Leaving valve %s", want_state ? "ON" : "OFF");
             if (!want_state && id(pool_pump).state && now > id(control_valve_last_change) + 600) {
                     auto t = id(sntp_time).now();
@@ -121,6 +130,7 @@ script:
             return;
         }
 
+        ESP_LOGD("control_valve", "Turning valve %s", want_state ? "ON" : "OFF");
         id(control_valve_last_change) = now;
         id(valve_output).toggle();
 
-- 
2.49.0