From eb12cb9f3a73cdc8affcee3492cb0d0a46f5b1a1 Mon Sep 17 00:00:00 2001 From: koliver2k2 Date: Tue, 17 Nov 2026 12:18:08 +0100 Subject: [PATCH] First version of webserver, working on localhost. Arduino needs to be tested. --- UCPSMain/UCPSMain.ino | 182 +++++++++++--- UCPSMain/go.mod | 3 + UCPSMain/index.html | 538 ++++++++++++++++++++++++++++++++++++++++++ UCPSMain/main.go | 271 +++++++++++++++++++++ 4 files changed, 956 insertions(+), 38 deletions(-) create mode 100644 UCPSMain/go.mod create mode 100644 UCPSMain/index.html create mode 100644 UCPSMain/main.go diff --git a/UCPSMain/UCPSMain.ino b/UCPSMain/UCPSMain.ino index 76a8f8a..6db1bb4 100644 --- a/UCPSMain/UCPSMain.ino +++ b/UCPSMain/UCPSMain.ino @@ -3,15 +3,30 @@ #include #include -// Wifi (Hotspot) +// ============ Settings you may need to change ============ + +// Wifi (phone hotspot) const char wifiSSID[] = "FreeWifi"; const char wifiPASS[] = "temppassword"; +// Computer that runs the Go server (IP of the PC in the hotspot network). +// The server prints it when it starts. If the PC gets a new IP, change it here. +const char SERVER_IP[] = "172.20.46.81"; +const int SERVER_PORT = 8080; + +const unsigned long POLL_INTERVAL = 5000UL; // ask the server every 5 s +const unsigned long FAILSAFE_MS = 30000UL; // no server answer for 30 s -> heating off +const unsigned long SENSOR_STALE_MS = 30000UL; // no valid sensor value for 30 s -> heating off +const float HYSTERESIS = 0.5; // on below (target - 0.5), off at target + // (keep in sync with HYST in index.html) + +// ============ Hardware ============ + // ESP8266 (Wifi module, AT firmware) -SoftwareSerial wifiSerial(0, 1); // RX = 15, TX = 14 +SoftwareSerial wifiSerial(0, 1); // RX, TX WiFiEspClient client; -// LCD Display +// DHT11 + LCD #define DHT_SENSOR_TYPE DHT_TYPE_11 static const int DHT_SENSOR_PIN = A1; DHT_nonblocking dht_sensor(DHT_SENSOR_PIN, DHT_SENSOR_TYPE); @@ -25,30 +40,49 @@ int latchPin = 5; // ST_CP int clockPin = 6; // SH_CP int leds = 0; -// API +// ============ State ============ + const float NO_TEMP = -999.0; + +// Outdoor temperature (Open-Meteo) const unsigned long API_INTERVAL = 60000UL; // 60s -const unsigned long RETRY_INTERVAL = 30000UL; // 30s +const unsigned long RETRY_INTERVAL = 30000UL; // 30s unsigned long lastApiFetch = 0; unsigned long fetchInterval = API_INTERVAL; float outdoorTemp = NO_TEMP; +// Indoor temperature (DHT11) +float lastIndoorTemp = NO_TEMP; +unsigned long lastIndoorMillis = 0; + +// Orders from the server +char modeLetter = '?'; // 'A' automatic, 'M' manual, '?' = no connection yet / lost +float targetTemp = NO_TEMP; +unsigned long lastServerOk = 0; +bool serverEverOk = false; +unsigned long lastPoll = 0; + // MOSFET module (heating elements) +// The heater is only allowed to run while heatRequest is true AND the +// 60 s ON / 5 s OFF cycle below is in its ON phase. const int mosfetPin = 13; unsigned long previousMosfetMillis = 0; -bool mosfetState = true; -const unsigned long mosfetOnTime = 60000UL/*60000UL*/; // 60 seconds ON -const unsigned long mosfetOffTime = 5000UL; // 60 seconds OFF +bool mosfetState = true; // phase of the cycle (not the pin!) +const unsigned long mosfetOnTime = 60000UL; // 60 seconds ON +const unsigned long mosfetOffTime = 5000UL; // 5 seconds OFF +bool heatRequest = false; // thermostat wants heat -// Store the indoor temp -float lastIndoorTemp = NO_TEMP; +// ============ Wifi ============ -// Connect to hotspot if not connected, then fetch the current temperature +bool ensureWifi() { + if (WiFi.status() == WL_CONNECTED) return true; + WiFi.begin(wifiSSID, wifiPASS); + return WiFi.status() == WL_CONNECTED; +} + +// Fetch the current outdoor temperature float fetchOutdoorTemp() { - if (WiFi.status() != WL_CONNECTED) { - WiFi.begin(wifiSSID, wifiPASS); - if (WiFi.status() != WL_CONNECTED) return NO_TEMP; - } + if (!ensureWifi()) return NO_TEMP; client.setTimeout(5000); if (!client.connect("api.open-meteo.com", 80)) return NO_TEMP; @@ -57,7 +91,7 @@ float fetchOutdoorTemp() { "Host: api.open-meteo.com\r\n" "Connection: close\r\n" "\r\n")); - + float t = NO_TEMP; if (client.find("\"current\":") && client.find("\"temperature_2m\":")) { t = client.parseFloat(); @@ -66,6 +100,42 @@ float fetchOutdoorTemp() { return t; } +// Send indoor temp + heating state to the local server, read mode + target back. +// Answer looks like: mode=A;target=21.00 +bool pollServer() { + if (!ensureWifi()) return false; + + client.setTimeout(3000); + if (!client.connect(SERVER_IP, SERVER_PORT)) return false; + + client.print(F("GET /api/arduino?heat=")); + client.print(heatRequest ? 1 : 0); + if (indoorValid()) { + client.print(F("&temp=")); + client.print(lastIndoorTemp, 1); + } + client.print(F(" HTTP/1.1\r\nHost: ")); + client.print(SERVER_IP); + client.print(F("\r\nConnection: close\r\n\r\n")); + + bool ok = false; + if (client.find("mode=")) { + char m = 0; + if (client.readBytes(&m, 1) == 1 && client.find("target=")) { + float t = client.parseFloat(); + if ((m == 'A' || m == 'M') && t >= 5.0 && t <= 30.0) { + modeLetter = m; + targetTemp = t; + ok = true; + } + } + } + client.stop(); + return ok; +} + +// ============ Helpers ============ + // Write to LCD display void lcdLine(uint8_t row, const char *text) { lcd.setCursor(0, row); @@ -84,7 +154,6 @@ void updateShiftRegister() { // Measure temperature static bool measure_environment(float *temp, float *hum) { static unsigned long timestamp = millis(); - // FIXED syntax error below if (millis() - timestamp > 3000ul) { if (dht_sensor.measure(temp, hum) == true) { timestamp = millis(); @@ -94,13 +163,32 @@ static bool measure_environment(float *temp, float *hum) { return false; } +bool indoorValid() { + return lastIndoorTemp != NO_TEMP && (millis() - lastIndoorMillis) < SENSOR_STALE_MS; +} + +bool serverFresh() { + return serverEverOk && (millis() - lastServerOk) < FAILSAFE_MS; +} + +// Thermostat: decides whether heating is wanted +void updateThermostat() { + if (!serverFresh() || !indoorValid() || targetTemp == NO_TEMP) { + heatRequest = false; // fail-safe: no data -> no heat + return; + } + if (lastIndoorTemp < targetTemp - HYSTERESIS) heatRequest = true; + else if (lastIndoorTemp >= targetTemp) heatRequest = false; + // in between: keep the previous decision (hysteresis) +} + void setup() { + pinMode(mosfetPin, OUTPUT); + digitalWrite(mosfetPin, LOW); // heater off from the very start pinMode(latchPin, OUTPUT); pinMode(dataPin, OUTPUT); pinMode(clockPin, OUTPUT); - pinMode(mosfetPin, OUTPUT); - Serial.begin(115200); lcd.begin(16, 2); lcdLine(0, "Connecting WiFi"); lcdLine(1, ""); @@ -118,26 +206,24 @@ void setup() { fetchInterval = (outdoorTemp == NO_TEMP) ? RETRY_INTERVAL : API_INTERVAL; lcd.clear(); - digitalWrite(mosfetPin, HIGH); mosfetState = true; previousMosfetMillis = millis(); + lastPoll = millis() - POLL_INTERVAL; // poll the server right away } void loop() { unsigned long currentMillis = millis(); - // MOSFET timer + // 60 s ON / 5 s OFF cycle (upper limit for the heater) if (mosfetState) { if (currentMillis - previousMosfetMillis >= mosfetOnTime) { mosfetState = false; previousMosfetMillis = currentMillis; - digitalWrite(mosfetPin, LOW); } } else { if (currentMillis - previousMosfetMillis >= mosfetOffTime) { mosfetState = true; previousMosfetMillis = currentMillis; - digitalWrite(mosfetPin, HIGH); } } @@ -152,24 +238,42 @@ void loop() { float indoorTemp, indoorHum; if (measure_environment(&indoorTemp, &indoorHum) == true) { lastIndoorTemp = indoorTemp; + lastIndoorMillis = currentMillis; } - // LCD row 0 (Temp + Countdown) + // Ask the local server every POLL_INTERVAL (blocks for a moment) + if (currentMillis - lastPoll >= POLL_INTERVAL) { + if (pollServer()) { + lastServerOk = millis(); + serverEverOk = true; + } + lastPoll = millis(); + currentMillis = millis(); + } + if (!serverFresh()) modeLetter = '?'; + + // Thermostat + heater output + updateThermostat(); + bool heaterOn = heatRequest && mosfetState; + digitalWrite(mosfetPin, heaterOn ? HIGH : LOW); + + // LCD row 0 (Temp + heater state + countdown of the ON/OFF cycle) char line0[20]; - if (lastIndoorTemp != NO_TEMP) { - char tempStr[6]; - dtostrf(lastIndoorTemp, 4, 1, tempStr); - // Formats into exactly 16 chars: "In:22.5C ON 10" - snprintf(line0, sizeof(line0), "In:%sC %s %2lu", tempStr, mosfetState ? "ON " : "OFF", remainingSeconds); + char tempStr[6]; + if (lastIndoorTemp != NO_TEMP) dtostrf(lastIndoorTemp, 4, 1, tempStr); + else strcpy(tempStr, "--- "); + if (heatRequest) { + snprintf(line0, sizeof(line0), "In:%sC %s %2lu", tempStr, heaterOn ? "ON " : "OFF", remainingSeconds); } else { - snprintf(line0, sizeof(line0), "In:--- C %s %2lu", mosfetState ? "ON " : "OFF", remainingSeconds); + snprintf(line0, sizeof(line0), "In:%sC OFF --", tempStr); } lcdLine(0, line0); // API outdoor temp if (currentMillis - lastApiFetch >= fetchInterval) { float t = fetchOutdoorTemp(); - lastApiFetch = currentMillis; + lastApiFetch = millis(); + currentMillis = millis(); if (t != NO_TEMP) { outdoorTemp = t; fetchInterval = API_INTERVAL; @@ -178,16 +282,18 @@ void loop() { } } - // LCD row 1 + // LCD row 1: outdoor temp, mode letter (A / M / ?) in the bottom right corner + char left[16]; if (outdoorTemp != NO_TEMP) { char outStr[10]; dtostrf(outdoorTemp, 4, 1, outStr); - char line1[20]; - snprintf(line1, sizeof(line1), "Out: %s C", outStr); - lcdLine(1, line1); + snprintf(left, sizeof(left), "Out: %s C", outStr); } else { - lcdLine(1, "Out: API Error"); + snprintf(left, sizeof(left), "Out: API Error"); } + char line1[20]; + snprintf(line1, sizeof(line1), "%-15s%c", left, modeLetter); + lcdLine(1, line1); // Light sensor LEDs int reading = analogRead(lightPin); @@ -200,5 +306,5 @@ void loop() { } updateShiftRegister(); - delay(100); -} \ No newline at end of file + delay(100); +} diff --git a/UCPSMain/go.mod b/UCPSMain/go.mod new file mode 100644 index 0000000..6fdb467 --- /dev/null +++ b/UCPSMain/go.mod @@ -0,0 +1,3 @@ +module UCPSMain.ino + +go 1.27.4 diff --git a/UCPSMain/index.html b/UCPSMain/index.html new file mode 100644 index 0000000..fd5eb4f --- /dev/null +++ b/UCPSMain/index.html @@ -0,0 +1,538 @@ + + + + + +Heizungssteuerung + + + +
+ +
+
🔥 Heizungssteuerung
+
Verbinde mit Server …
+
+ + +
+
+
+ + Lade … +
+
+ + +
+
+
+
+
+
Ist-Temperatur (Sensor)
+
–
+
+
+
Zielwert der Heizung
+
–
+
+
+
+
Abstand zum Zielwert
+
–
+
+
+
+
Warum?
+
+ +
+ + +
+ + +
+ + + +
+ + +
+
Dein Temperaturbereich
+
Du legst nur deinen eigenen Wunschbereich fest. Die Bereiche der anderen Mitglieder bleiben anonym und sind für dich nicht änderbar.
+ +
+
+
+ + + + + + +
+
+ + + +
+ +
+ +
+
Vorlagen
+
Schnellauswahl für typische Bereiche. Eine Vorlage füllt nur deine Regler vor und gilt erst, wenn du auf „Übernehmen“ klickst.
+
+ + + +
+
+
+ + + + + + + +
+ + + + diff --git a/UCPSMain/main.go b/UCPSMain/main.go new file mode 100644 index 0000000..951a1ee --- /dev/null +++ b/UCPSMain/main.go @@ -0,0 +1,271 @@ +// Local heating server. +// +// - Serves index.html to browsers on the same network. +// - Keeps all values in memory (lost when the server stops). +// - GET /api/state -> everything the website needs (JSON) +// - POST /api/update -> website changes settings (JSON, partial updates) +// - GET /api/arduino -> Arduino sends its data as query parameters and +// gets its orders back as plain text +// +// Run: go run . +package main + +import ( + "encoding/json" + "fmt" + "log" + "net" + "net/http" + "strconv" + "sync" + "time" +) + +const ( + listenAddr = ":8080" // all network interfaces, port 8080 + onlineTimeout = 15 * time.Second // Arduino counts as offline after this + minTemp = 5.0 + maxTemp = 30.0 +) + +// Confirmed group value (what "Automatic" mode uses). +type Confirmed struct { + A float64 `json:"a"` + B float64 `json:"b"` + Soll float64 `json:"soll"` +} + +// Settings that the website changes. +type Settings struct { + Mode string `json:"mode"` // "auto" or "manual" + Mine [2]float64 `json:"mine"` // my own wish range + Others [][2]float64 `json:"others"` + Confirmed Confirmed `json:"confirmed"` + SelfTemp float64 `json:"selfTemp"` // manual target +} + +// What the website receives. +type View struct { + Settings + Target float64 `json:"target"` // value the Arduino is told to hold + Indoor *float64 `json:"indoor"` // null while the Arduino is offline + Heating bool `json:"heating"` + Online bool `json:"online"` +} + +type Server struct { + mu sync.Mutex + s Settings + + // live data from the Arduino + indoor float64 + haveIndoor bool + heating bool + lastSeen time.Time +} + +func newServer() *Server { + return &Server{ + s: Settings{ + Mode: "auto", + Mine: [2]float64{18, 22}, + Others: [][2]float64{{20, 24}, {21, 21}, {20, 22}}, + // Result of the group aggregation for the default ranges above. + Confirmed: Confirmed{A: 21, B: 21, Soll: 21}, + SelfTemp: 21, + }, + } +} + +// target returns the temperature the heating should hold. Caller holds the lock. +func (sv *Server) target() float64 { + if sv.s.Mode == "manual" { + return sv.s.SelfTemp + } + return sv.s.Confirmed.Soll +} + +// view builds the JSON for the website. Caller holds the lock. +func (sv *Server) view() View { + online := !sv.lastSeen.IsZero() && time.Since(sv.lastSeen) < onlineTimeout + v := View{ + Settings: sv.s, + Target: sv.target(), + Heating: online && sv.heating, + Online: online, + } + if online && sv.haveIndoor { + t := sv.indoor + v.Indoor = &t + } + return v +} + +func writeJSON(w http.ResponseWriter, status int, v any) { + w.Header().Set("Content-Type", "application/json") + w.Header().Set("Cache-Control", "no-store") + w.WriteHeader(status) + _ = json.NewEncoder(w).Encode(v) +} + +func validTemp(t float64) bool { return t >= minTemp && t <= maxTemp } + +// ---------- Website ---------- + +func (sv *Server) handleIndex(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/" { + http.NotFound(w, r) + return + } + w.Header().Set("Cache-Control", "no-store") + http.ServeFile(w, r, "index.html") // read from disk: edit + refresh, no restart +} + +func (sv *Server) handleState(w http.ResponseWriter, r *http.Request) { + sv.mu.Lock() + v := sv.view() + sv.mu.Unlock() + writeJSON(w, http.StatusOK, v) +} + +// Every field is optional: only the fields that are sent are changed. +type update struct { + Mode *string `json:"mode"` + Mine *[2]float64 `json:"mine"` + SelfTemp *float64 `json:"selfTemp"` + Confirmed *Confirmed `json:"confirmed"` +} + +func (sv *Server) handleUpdate(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost { + http.Error(w, "POST only", http.StatusMethodNotAllowed) + return + } + r.Body = http.MaxBytesReader(w, r.Body, 4096) + var u update + if err := json.NewDecoder(r.Body).Decode(&u); err != nil { + http.Error(w, "invalid JSON", http.StatusBadRequest) + return + } + + // Validate everything first, then apply. + if u.Mode != nil && *u.Mode != "auto" && *u.Mode != "manual" { + http.Error(w, "mode must be auto or manual", http.StatusBadRequest) + return + } + if u.Mine != nil && (!validTemp(u.Mine[0]) || !validTemp(u.Mine[1]) || u.Mine[0] > u.Mine[1]) { + http.Error(w, "invalid range", http.StatusBadRequest) + return + } + if u.SelfTemp != nil && !validTemp(*u.SelfTemp) { + http.Error(w, "invalid temperature", http.StatusBadRequest) + return + } + if u.Confirmed != nil && (!validTemp(u.Confirmed.A) || !validTemp(u.Confirmed.B) || + !validTemp(u.Confirmed.Soll) || u.Confirmed.A > u.Confirmed.B) { + http.Error(w, "invalid confirmed value", http.StatusBadRequest) + return + } + + sv.mu.Lock() + if u.Mode != nil { + sv.s.Mode = *u.Mode + } + if u.Mine != nil { + sv.s.Mine = *u.Mine + } + if u.SelfTemp != nil { + sv.s.SelfTemp = *u.SelfTemp + } + if u.Confirmed != nil { + sv.s.Confirmed = *u.Confirmed + } + v := sv.view() + log.Printf("web: update -> mode=%s target=%.1f", v.Mode, v.Target) + sv.mu.Unlock() + + writeJSON(w, http.StatusOK, v) +} + +// ---------- Arduino ---------- + +// GET /api/arduino?temp=21.5&heat=1 +// +// temp: indoor temperature (omitted if the sensor has no valid value) +// heat: 1 if the Arduino currently wants to heat, else 0 +// +// Response (plain text): mode=A;target=21.00 +func (sv *Server) handleArduino(w http.ResponseWriter, r *http.Request) { + q := r.URL.Query() + + sv.mu.Lock() + // ParseFloat also accepts "nan"; the range check rejects it. + if t, err := strconv.ParseFloat(q.Get("temp"), 64); err == nil && t > -40 && t < 80 { + sv.indoor, sv.haveIndoor = t, true + } else { + sv.haveIndoor = false + } + sv.heating = q.Get("heat") == "1" + sv.lastSeen = time.Now() + + letter := "A" + if sv.s.Mode == "manual" { + letter = "M" + } + target := sv.target() + log.Printf("arduino: indoor=%.1f (valid=%v) heat=%v -> mode=%s target=%.2f", + sv.indoor, sv.haveIndoor, sv.heating, letter, target) + sv.mu.Unlock() + + w.Header().Set("Content-Type", "text/plain") + w.Header().Set("Cache-Control", "no-store") + fmt.Fprintf(w, "mode=%s;target=%.2f\n", letter, target) +} + +// ---------- Start ---------- + +func printAddresses() { + ifaces, err := net.Interfaces() + if err != nil { + return + } + fmt.Println("Heating server is running. Addresses of this PC (adapter name in brackets):") + for _, ifc := range ifaces { + if ifc.Flags&net.FlagUp == 0 || ifc.Flags&net.FlagLoopback != 0 { + continue + } + addrs, err := ifc.Addrs() + if err != nil { + continue + } + for _, a := range addrs { + ipnet, ok := a.(*net.IPNet) + if !ok || ipnet.IP.To4() == nil || ipnet.IP.IsLinkLocalUnicast() { + continue // skip IPv6 and 169.254.x.x (adapter without a real connection) + } + fmt.Printf(" http://%s%s [%s]\n", ipnet.IP, listenAddr, ifc.Name) + } + } + fmt.Println("Use the address of your Wi-Fi adapter (connected to the phone hotspot) as SERVER_IP in the Arduino sketch.") +} + +func main() { + sv := newServer() + + mux := http.NewServeMux() + mux.HandleFunc("/", sv.handleIndex) + mux.HandleFunc("/api/state", sv.handleState) + mux.HandleFunc("/api/update", sv.handleUpdate) + mux.HandleFunc("/api/arduino", sv.handleArduino) + + srv := &http.Server{ + Addr: listenAddr, + Handler: mux, + ReadHeaderTimeout: 5 * time.Second, + ReadTimeout: 10 * time.Second, + WriteTimeout: 10 * time.Second, + } + + printAddresses() + log.Fatal(srv.ListenAndServe()) +}