First version of webserver, working on localhost. Arduino needs to be tested.

main
koliver2k2 2026-11-17 12:18:08 +01:00
parent 2de263f3a8
commit eb12cb9f3a
4 changed files with 956 additions and 38 deletions

View File

@ -3,15 +3,30 @@
#include <SoftwareSerial.h>
#include <WiFiEsp.h>
// 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);
}
delay(100);
}

3
UCPSMain/go.mod 100644
View File

@ -0,0 +1,3 @@
module UCPSMain.ino
go 1.27.4

538
UCPSMain/index.html 100644
View File

@ -0,0 +1,538 @@
<!doctype html>
<html lang="de">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Heizungssteuerung</title>
<style>
:root{
--surface-0:#f9f9f7; --surface-1:#f3f3f0; --surface-2:#ffffff;
--border:rgba(11,11,11,.10); --border-strong:rgba(11,11,11,.20); --border-stronger:rgba(11,11,11,.40);
--text-primary:#0b0b0b; --text-secondary:#52514e; --text-muted:#7b7974;
--text-accent:#184f95; --bg-accent:#cde2fb; --border-accent:#86b6ef;
--text-success:#006300; --bg-success:#caeac7; --border-success:#73cb6d; --fill-success:#0ca30c;
--text-warning:#734500; --bg-warning:#f9dca4;
--text-danger:#8e2626; --bg-danger:#fad6d6;
--fill-primary:#0b0b0b; --on-primary:#ffffff;
--radius:8px;
}
@media (prefers-color-scheme: dark){
:root{
--surface-0:#0b0b0b; --surface-1:#151515; --surface-2:#1a1a19;
--border:rgba(255,255,255,.10); --border-strong:rgba(255,255,255,.20); --border-stronger:rgba(255,255,255,.40);
--text-primary:#f0efec; --text-secondary:#c3c2b7; --text-muted:#898781;
--text-accent:#6da7ec; --bg-accent:#032042; --border-accent:#184f95;
--text-success:#55bf50; --bg-success:#11260f; --border-success:#007300; --fill-success:#0ca30c;
--text-warning:#db9300; --bg-warning:#311a00;
--text-danger:#ec7e7e; --bg-danger:#3c0e0e;
--fill-primary:#f0efec; --on-primary:#0b0b0b;
}
}
*{box-sizing:border-box;margin:0;padding:0}
body{font-family:system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;background:var(--surface-0);color:var(--text-primary);padding:16px;font-size:14px}
.wrap{max-width:760px;margin:0 auto;background:var(--surface-2);border:0.5px solid var(--border);border-radius:12px;padding:1rem 1.25rem}
button{font:inherit;padding:8px 16px;background:transparent;color:var(--text-primary);border:0.5px solid var(--border-strong);border-radius:var(--radius);cursor:pointer}
button:hover:not(:disabled){background:var(--surface-1)}
button:disabled{opacity:.4;cursor:default}
button.primary{background:var(--fill-primary);color:var(--on-primary);border-color:transparent}
button.primary:hover:not(:disabled){background:var(--fill-primary);opacity:.85}
input[type=range]{-webkit-appearance:none;appearance:none;width:100%;height:4px;background:var(--border-strong);border-radius:2px;outline:none}
input[type=range]::-webkit-slider-thumb{-webkit-appearance:none;width:22px;height:22px;border-radius:50%;background:var(--surface-2);border:1px solid var(--border-stronger);cursor:pointer}
input[type=range]::-moz-range-thumb{width:22px;height:22px;border-radius:50%;background:var(--surface-2);border:1px solid var(--border-stronger);cursor:pointer}
.seg{display:inline-flex;border:0.5px solid var(--border-strong);border-radius:var(--radius);overflow:hidden}
.seg button{border:none;border-radius:0;padding:6px 14px}
.seg button[aria-pressed=true]{background:var(--fill-primary);color:var(--on-primary)}
.seg button[aria-pressed=true]:hover{background:var(--fill-primary)}
</style>
</head>
<body>
<div class="wrap">
<div style="display:flex; align-items:center; justify-content:space-between; gap:8px; flex-wrap:wrap; margin-bottom:14px;">
<div style="font-weight:500;font-size:16px;">🔥 Heizungssteuerung</div>
<div id="conn" style="font-size:13px; color:var(--text-secondary);">Verbinde mit Server …</div>
</div>
<!-- Was macht die Heizung und warum? (immer sichtbar) -->
<div id="status" style="background:var(--surface-1); border-radius:var(--radius); padding:14px; margin-bottom:16px;" aria-live="polite">
<div style="display:flex; justify-content:space-between; align-items:center; gap:12px; flex-wrap:wrap;">
<div style="display:flex; align-items:center; gap:10px; flex-wrap:wrap;">
<span id="badge" style="font-size:13px; font-weight:500; padding:3px 10px; border-radius:999px;"></span>
<span id="lvl-t" style="font-size:20px; font-weight:500;">Lade …</span>
</div>
<div class="seg" role="group" aria-label="Betriebsart">
<button id="m-auto" aria-pressed="false">Automatik</button>
<button id="m-man" aria-pressed="false">Manuell</button>
</div>
</div>
<div id="mode-hint" style="font-size:12px; color:var(--text-secondary); margin-top:8px;"></div>
<div style="display:grid; grid-template-columns:repeat(auto-fit,minmax(130px,1fr)); gap:10px; margin-top:12px;">
<div style="background:var(--surface-2); border-radius:var(--radius); padding:10px 12px;">
<div style="font-size:12px; color:var(--text-secondary);">Ist-Temperatur (Sensor)</div>
<div style="font-size:20px; font-weight:500;" id="t-ist">–</div>
</div>
<div style="background:var(--surface-2); border-radius:var(--radius); padding:10px 12px;">
<div style="font-size:12px; color:var(--text-secondary);">Zielwert der Heizung</div>
<div style="font-size:20px; font-weight:500;" id="t-tgt">–</div>
<div style="font-size:12px; color:var(--text-secondary);" id="t-src"></div>
</div>
<div style="background:var(--surface-2); border-radius:var(--radius); padding:10px 12px;">
<div style="font-size:12px; color:var(--text-secondary);">Abstand zum Zielwert</div>
<div style="font-size:20px; font-weight:500;" id="t-diff">–</div>
</div>
</div>
<div style="margin-top:12px; font-size:14px; line-height:1.55;">
<div><span style="font-weight:500;">Warum?</span> <span id="why"></span></div>
<div id="srcline" style="color:var(--text-secondary);"></div>
<div id="next" style="color:var(--text-secondary);"></div>
</div>
<div id="pend" style="display:none; margin-top:10px; background:var(--bg-warning); color:var(--text-warning); border-radius:var(--radius); padding:8px 12px; font-size:13px; align-items:center; justify-content:space-between; gap:10px; flex-wrap:wrap;">
<span id="pend-t"></span>
<button id="pend-go" style="font-size:13px;">Jetzt bestätigen</button>
</div>
<div id="toast" style="display:none; margin-top:10px; font-size:13px; color:var(--text-success);"></div>
</div>
<!-- Tabs -->
<div role="tablist" aria-label="Bereiche" style="display:flex; gap:4px; margin-bottom:16px; flex-wrap:wrap; border-bottom:0.5px solid var(--border);">
<button role="tab" id="t-pref" aria-controls="p-pref" style="border:none; border-bottom:2px solid transparent; border-radius:0; background:none; padding:8px 12px;">1 · Meine Präferenz<span id="dot-pref" style="display:none; margin-left:6px; color:var(--text-warning);" title="Nicht übernommen">●</span></button>
<button role="tab" id="t-group" aria-controls="p-group" style="border:none; border-bottom:2px solid transparent; border-radius:0; background:none; padding:8px 12px;">2 · Gruppe<span id="dot-group" style="display:none; margin-left:6px; color:var(--text-warning);" title="Wartet auf Bestätigung">●</span></button>
<button role="tab" id="t-self" aria-controls="p-self" style="border:none; border-bottom:2px solid transparent; border-radius:0; background:none; padding:8px 12px;">3 · Temperatur selbst wählen</button>
</div>
<!-- Tab 1: Meine Präferenz -->
<div id="p-pref" role="tabpanel" aria-labelledby="t-pref">
<div style="font-size:14px; font-weight:500;">Dein Temperaturbereich</div>
<div style="font-size:13px; color:var(--text-secondary); margin:2px 0 8px;">Du legst nur deinen eigenen Wunschbereich fest. Die Bereiche der anderen Mitglieder bleiben anonym und sind für dich nicht änderbar.</div>
<div style="background:var(--surface-1); border-radius:var(--radius); padding:12px 14px;">
<div id="pchart" style="position:relative; height:76px; margin:4px 10px 0;"></div>
<div style="display:grid; grid-template-columns:auto 1fr auto; gap:8px 12px; align-items:center; font-size:14px; margin-top:6px;">
<label for="plo" style="color:var(--text-secondary);">Minimum</label>
<input type="range" id="plo" min="5" max="30" step="0.5" value="18">
<span id="plo-o" style="min-width:56px; text-align:right; font-weight:500;"></span>
<label for="phi" style="color:var(--text-secondary);">Maximum</label>
<input type="range" id="phi" min="5" max="30" step="0.5" value="22">
<span id="phi-o" style="min-width:56px; text-align:right; font-weight:500;"></span>
</div>
<div style="display:flex; align-items:center; gap:10px; flex-wrap:wrap; margin-top:12px;">
<button id="apply" class="primary">✓ Übernehmen</button>
<button id="reset" style="font-size:13px;">Änderungen verwerfen</button>
<span id="pstate" style="font-size:13px;"></span>
</div>
<div id="applied" style="display:none; margin-top:12px; background:var(--bg-success); color:var(--text-success); border-radius:var(--radius); padding:10px 12px; font-size:13px;">
<div id="applied-t"></div>
<button id="to-group" style="margin-top:8px; font-size:13px;">Weiter zur Gruppe →</button>
</div>
</div>
<div style="margin-top:14px; border:0.5px dashed var(--border-stronger); border-radius:var(--radius); padding:12px 14px;">
<div style="font-size:14px; font-weight:500;">Vorlagen</div>
<div style="font-size:13px; color:var(--text-secondary); margin:2px 0 10px;">Schnellauswahl für typische Bereiche. Eine Vorlage füllt nur deine Regler vor und gilt erst, wenn du auf „Übernehmen“ klickst.</div>
<div style="display:flex; gap:8px; flex-wrap:wrap;">
<button data-p="20,22" style="font-size:13px;">Komfort 20–22 °C</button>
<button data-p="17,19" style="font-size:13px;">Sparen 17–19 °C</button>
<button data-p="16,18" style="font-size:13px;">Nacht 16–18 °C</button>
</div>
</div>
</div>
<!-- Tab 2: Gruppe -->
<div id="p-group" role="tabpanel" aria-labelledby="t-group" style="display:none;">
<div style="font-size:14px; font-weight:500;">Wunschbereiche der Gruppe (4 Mitglieder, anonym)</div>
<div style="font-size:13px; color:var(--text-secondary); margin:2px 0 8px;">Aus allen Wunschbereichen wird ein gemeinsamer Wert gebildet. Dein Bereich stammt aus Tab 1, die anderen sind nur zur Ansicht.</div>
<div style="background:var(--surface-1); border-radius:var(--radius); padding:12px 14px;">
<div id="chart" style="position:relative;" role="img" aria-label="Wunschbereiche der vier Mitglieder auf einer Temperaturachse von 5 bis 30 Grad mit Gruppenbereich, Gruppenwunschwert und Ist-Temperatur"></div>
<div style="display:grid; gap:6px; margin-top:12px; font-size:13px; color:var(--text-secondary);">
<div><span style="display:inline-block; width:14px; height:10px; vertical-align:-1px; margin-right:8px; background:color-mix(in srgb, var(--fill-success) 22%, transparent); border:1px solid var(--border-success);"></span><span id="lg-zone"></span></div>
<div><span style="display:inline-block; width:3px; height:13px; vertical-align:-2px; margin:0 10px 0 5px; background:var(--text-success); border-radius:2px;"></span><span id="lg-soll"></span></div>
<div><span style="display:inline-block; width:2px; height:13px; vertical-align:-2px; margin:0 10px 0 6px; background:var(--text-primary);"></span><span id="lg-ist"></span></div>
</div>
<button id="fn-open" aria-expanded="false" aria-controls="fn" style="margin-top:12px; font-size:13px;"><span id="fn-open-t">Aggregationsfunktion ansehen</span></button>
</div>
<div id="fn" style="display:none; margin-top:12px; border:0.5px solid var(--border-stronger); border-radius:var(--radius); padding:12px 14px;">
<div style="display:flex; justify-content:space-between; align-items:center; gap:8px; margin-bottom:8px;">
<div style="font-size:14px; font-weight:500;">So berechnet die Gruppe ihren Wert</div>
<button id="fn-close" aria-label="Schließen" style="padding:0 8px; font-size:16px; line-height:22px;">×</button>
</div>
<div style="display:flex; gap:6px; flex-wrap:wrap; margin-bottom:10px;">
<button id="fn-live" style="font-size:13px;">Aktuelle Gruppe</button>
<button id="fn-ex" style="font-size:13px;">Beispiel: keine Überschneidung</button>
</div>
<div id="fn-body"></div>
</div>
<div id="confirm" style="margin-top:14px; border-radius:var(--radius); padding:12px 14px;">
<div id="confirm-t" style="font-size:14px; font-weight:500;"></div>
<div id="confirm-d" style="font-size:13px; margin-top:2px;"></div>
<div style="display:flex; gap:8px; flex-wrap:wrap; margin-top:10px;">
<button id="agree" class="primary">✓ <span id="agree-t">Einverstanden</span></button>
<button id="adjust" style="font-size:13px;">Meinen Bereich anpassen</button>
</div>
</div>
</div>
<!-- Tab 3: Temperatur selbst wählen -->
<div id="p-self" role="tabpanel" aria-labelledby="t-self" style="display:none;">
<div style="font-size:14px; font-weight:500;">Temperatur selbst wählen</div>
<div style="font-size:13px; color:var(--text-secondary); margin:2px 0 8px;">Du legst eine feste Wunschtemperatur fest. Solange der manuelle Modus aktiv ist, ignoriert die Heizung den Gruppenwunschwert.</div>
<div style="background:var(--surface-1); border-radius:var(--radius); padding:12px 14px;">
<div style="display:grid; grid-template-columns:auto 1fr auto; gap:12px; align-items:center; font-size:14px;">
<label for="sst" style="color:var(--text-secondary);">Temperatur</label>
<input type="range" id="sst" min="5" max="30" step="0.5" value="21">
<span id="sst-o" style="min-width:64px; text-align:right; font-weight:500; font-size:18px;"></span>
</div>
<div id="self-cmp" style="font-size:13px; color:var(--text-secondary); margin-top:10px;"></div>
<div style="display:flex; gap:8px; flex-wrap:wrap; margin-top:12px;">
<button id="self-use" class="primary">✓ <span id="self-use-t">Diese Temperatur nutzen</span></button>
<button id="self-back" style="font-size:13px;">Zurück zum Gruppenwunschwert</button>
</div>
</div>
</div>
</div>
<script>
/* ============ Einstellungen ============ */
var POLL_MS = 5000; // wie oft die Seite den Server fragt
var HYST = 0.5; // muss zu HYSTERESIS im Arduino-Sketch passen
/* ============ Zustand ============ */
/* kommt vom Server: */
var IST=null, heating=false, online=false, OTHERS=[[20,24],[21,21],[20,22]];
var mine=[18,22], confirmed={a:21,b:21,soll:21}, source='group', selfTemp=21;
/* nur in diesem Browser: */
var draft=[18,22], selfDraft=21, tab='pref', applied=false, fnOpen=false, fnMode='live', toast='', srvErr=false, toastTimer=null;
var $=function(i){return document.getElementById(i)};
function fm(v){return (Math.round(v*100)/100).toString().replace('.',',')}
function fr(a,b){return a===b?fm(a)+' °C':fm(a)+'–'+fm(b)+' °C'}
function pct(v){return (v-5)/25*100}
/* Aggregationsfunktion
1. Wunschbereiche (min-max) aller Mitglieder erfassen
2. Gruppenbereich = Bereich mit der größtmöglichen Abdeckung (bei Gleichstand der niedrigere)
3. Gruppenwunschwert = niedrigster Wert des Gruppenbereichs (Energiesparen)
Ohne Überschneidung: Bereich zwischen den nächsten zwei Temperaturen (kleinste Lücke), Wert = Mittelwert */
function agg(P){
var best=null;
P.forEach(function(p){
var x=p[0],n=0,b=Infinity;
P.forEach(function(q){if(q[0]<=x&&x<=q[1]){n++;if(q[1]<b)b=q[1]}});
if(!best||n>best.n||(n===best.n&&x<best.a))best={n:n,a:x,b:b};
});
if(best.n>=2||P.length===1)return {kind:'overlap',a:best.a,b:best.b,soll:best.a,n:best.n};
var o=P.map(function(p,i){return {lo:p[0],hi:p[1],i:i}}).sort(function(x,y){return x.lo-y.lo}),g=null;
for(var k=0;k<o.length-1;k++){var a=o[k].hi,b=o[k+1].lo;if(!g||b-a<g.b-g.a)g={a:a,b:b,l:o[k].i,u:o[k+1].i}}
return {kind:'gap',a:g.a,b:g.b,soll:(g.a+g.b)/2,n:1,l:g.l,u:g.u};
}
function allRanges(){return [mine].concat(OTHERS)}
var NAMES=['Dein Bereich','Mitglied 1','Mitglied 2','Mitglied 3'];
/* ============ Server ============ */
function api(method,body){
return fetch(method==='GET'?'/api/state':'/api/update',{
method:method,
headers:{'Content-Type':'application/json'},
body:body?JSON.stringify(body):undefined
}).then(function(r){if(!r.ok)throw new Error('HTTP '+r.status);return r.json()});
}
/* Antwort des Servers übernehmen. Ungespeicherte Entwürfe bleiben erhalten. */
function takeState(st,first){
var mineClean=draft[0]===mine[0]&&draft[1]===mine[1];
var selfClean=selfDraft===selfTemp;
mine=st.mine; OTHERS=st.others; confirmed=st.confirmed; selfTemp=st.selfTemp;
source=st.mode==='manual'?'self':'group';
IST=st.indoor; heating=st.heating; online=st.online;
if(first||mineClean)draft=mine.slice();
if(first||selfClean)selfDraft=selfTemp;
srvErr=false;
render();
}
function refresh(first){
api('GET').then(function(st){takeState(st,first)}).catch(function(){srvErr=true;render()});
}
function send(body,msg){
return api('POST',body).then(function(st){
takeState(st,false);
setToast(msg||'');
}).catch(function(){srvErr=true;setToast('');render()});
}
function setToast(t){
toast=t;render();
clearTimeout(toastTimer);
if(t)toastTimer=setTimeout(function(){toast='';render()},6000);
}
var SAVED='Gespeichert. Der Arduino übernimmt den Wert beim nächsten Abruf (spätestens nach 5 s).';
/* ============ Diagramm Gruppe ============ */
var TOP=56,ROWH=30,N=4,TRACK='color-mix(in srgb, var(--text-muted) 25%, transparent)';
function buildChart(){
var c=$('chart'),h='',p='';
c.style.height=(TOP+N*ROWH+28)+'px';
for(var i=0;i<N;i++){
var st=i===0?'font-weight:500;color:var(--text-primary);':'color:var(--text-secondary);';
h+='<div id="cl'+i+'" style="position:absolute;left:0;top:'+(TOP+i*ROWH)+'px;width:96px;height:'+ROWH+'px;line-height:'+ROWH+'px;font-size:13px;'+st+'">'+NAMES[i]+'</div>';
h+='<div id="cv'+i+'" style="position:absolute;right:0;top:'+(TOP+i*ROWH)+'px;width:76px;height:'+ROWH+'px;line-height:'+ROWH+'px;text-align:right;font-size:12px;'+st+'"></div>';
}
h+='<div id="cunit" style="position:absolute;right:0;top:'+(TOP+N*ROWH+4)+'px;width:76px;text-align:right;font-size:11px;color:var(--text-muted);">°C</div>';
p='<div id="cplot" style="position:absolute;left:100px;right:80px;top:0;bottom:0;">';
for(var v=5;v<=30;v+=5){
p+='<div style="position:absolute;left:'+pct(v)+'%;top:'+(TOP-6)+'px;height:'+(N*ROWH+6)+'px;width:1px;background:var(--border);"></div>';
p+='<div style="position:absolute;left:'+pct(v)+'%;top:'+(TOP+N*ROWH+4)+'px;transform:translateX(-50%);font-size:11px;color:var(--text-muted);">'+v+'</div>';
}
p+='<div id="czone" style="position:absolute;top:'+(TOP-6)+'px;height:'+(N*ROWH+6)+'px;background:color-mix(in srgb, var(--fill-success) 22%, transparent);border-left:1px solid var(--border-success);border-right:1px solid var(--border-success);"></div>';
for(i=0;i<N;i++){
var y=TOP+i*ROWH+10;
p+='<div style="position:absolute;left:0;right:0;top:'+y+'px;height:10px;background:'+TRACK+';border-radius:5px;"></div>';
p+='<div id="cb'+i+'" style="position:absolute;top:'+y+'px;height:10px;border-radius:5px;'+(i===0?'background:var(--text-accent);':'background:color-mix(in srgb, var(--text-accent) 40%, transparent);border:0.5px solid var(--border-accent);')+'"></div>';
}
p+='<div id="ci-line" style="position:absolute;top:22px;height:'+(TOP+N*ROWH-22+4)+'px;width:2px;background:var(--text-primary);"></div>';
p+='<div id="cs-line" style="position:absolute;top:46px;height:'+(TOP+N*ROWH-46+4)+'px;width:3px;background:var(--text-success);border-radius:2px;"></div>';
p+='<div id="ci-flag" style="position:absolute;top:0;transform:translateX(-50%);white-space:nowrap;font-size:12px;font-weight:500;padding:3px 9px;border-radius:6px;background:var(--fill-primary);color:var(--on-primary);"></div>';
p+='<div id="cs-flag" style="position:absolute;top:24px;transform:translateX(-50%);white-space:nowrap;font-size:12px;font-weight:500;padding:3px 9px;border-radius:6px;background:var(--bg-success);color:var(--text-success);border:1px solid var(--border-success);"></div>';
p+='</div>';
c.innerHTML=h+p;
}
function placeFlag(f,plot,desired,left,right){
var w=f.offsetWidth,pw=plot.offsetWidth,min=-left+w/2+2,max=pw+right-w/2-2;
f.style.left=Math.min(max,Math.max(min,desired))+'px';
}
function updateChart(A){
var R=allRanges(),plot=$('cplot');
var nar=$('chart').offsetWidth<480,GL=nar?74:100,GR=nar?6:80;
plot.style.left=GL+'px';plot.style.right=GR+'px';$('cunit').style.display=nar?'none':'';
for(var k=0;k<N;k++){
var l=$('cl'+k),v=$('cv'+k),y=TOP+k*ROWH;
l.textContent=nar&&k===0?'Du':NAMES[k];l.style.whiteSpace='nowrap';l.style.width=nar?'70px':'96px';l.style.lineHeight=nar?'15px':ROWH+'px';
v.style.top=(nar?y+15:y)+'px';v.style.lineHeight=nar?'14px':ROWH+'px';v.style.height=nar?'14px':ROWH+'px';
v.style.fontSize=nar?'11px':'12px';v.style.textAlign=nar?'left':'right';v.style.width=nar?'70px':'76px';
v.style.left=nar?'0':'';v.style.right=nar?'':'0';
}
R.forEach(function(r,i){
$('cb'+i).style.left=pct(r[0])+'%';$('cb'+i).style.width=Math.max(pct(r[1])-pct(r[0]),1.6)+'%';
$('cv'+i).textContent=fr(r[0],r[1]);
});
$('czone').style.left=pct(A.a)+'%';$('czone').style.width=Math.max(pct(A.b)-pct(A.a),1.2)+'%';
$('cs-line').style.left='calc('+pct(A.soll)+'% - 1.5px)';
var sf=$('cs-flag'),isf=$('ci-flag'),hasIst=IST!==null;
sf.textContent='Gruppenwunschwert '+fm(A.soll)+' °C';
placeFlag(sf,plot,pct(A.soll)/100*plot.offsetWidth,GL,GR);
$('ci-line').style.display=hasIst?'':'none';isf.style.display=hasIst?'':'none';
if(hasIst){
$('ci-line').style.left='calc('+pct(IST)+'% - 1px)';
isf.textContent='Ist-Temperatur '+fm(IST)+' °C';
placeFlag(isf,plot,pct(IST)/100*plot.offsetWidth,GL,GR);
}
var m=R.length;
$('lg-zone').innerHTML=A.kind==='overlap'
?'<b style="color:var(--text-primary);font-weight:500;">Gruppenbereich '+fr(A.a,A.b)+'</b>: '+A.n+' von '+m+' Wunschbereichen stimmen hier überein'
:'<b style="color:var(--text-primary);font-weight:500;">Gruppenbereich '+fr(A.a,A.b)+'</b>: keine Überschneidung, kleinste Lücke zwischen zwei Bereichen';
$('lg-soll').innerHTML='<b style="color:var(--text-primary);font-weight:500;">Gruppenwunschwert '+fm(A.soll)+' °C</b>: '+(A.kind==='overlap'?'niedrigster Wert des Gruppenbereichs (Energiesparen)':'Mittelwert aus '+fm(A.a)+' und '+fm(A.b)+' °C');
$('lg-ist').innerHTML=hasIst
?'<b style="color:var(--text-primary);font-weight:500;">Ist-Temperatur '+fm(IST)+' °C</b>: aktueller Wert des Sensors'
:'<b style="color:var(--text-primary);font-weight:500;">Ist-Temperatur</b>: unbekannt, der Arduino ist nicht verbunden';
}
/* ============ Diagramm Meine Präferenz ============ */
function buildPChart(){
var h='';
for(var v=5;v<=30;v+=5)h+='<div style="position:absolute;left:'+pct(v)+'%;top:50px;transform:translateX(-50%);font-size:11px;color:var(--text-muted);">'+v+'</div>';
h+='<div style="position:absolute;left:0;right:0;top:34px;height:12px;background:'+TRACK+';border-radius:6px;"></div>';
h+='<div id="pcommit" style="position:absolute;top:31px;height:18px;border:1.5px dashed var(--text-secondary);border-radius:9px;display:none;"></div>';
h+='<div id="pband" style="position:absolute;top:34px;height:12px;border-radius:6px;background:var(--text-accent);"></div>';
h+='<div id="pflag" style="position:absolute;top:2px;transform:translateX(-50%);white-space:nowrap;font-size:12px;font-weight:500;padding:3px 9px;border-radius:6px;background:var(--bg-accent);color:var(--text-accent);border:1px solid var(--border-accent);"></div>';
$('pchart').innerHTML=h;
}
/* ============ Aggregationsfunktion ansehen ============ */
function coverage(R){
var lo=Infinity,hi=-Infinity,arr=[];
R.forEach(function(r){lo=Math.min(lo,r[0]);hi=Math.max(hi,r[1])});
for(var T=lo;T<=hi+1e-9;T+=0.5){var c=0;R.forEach(function(r){if(r[0]<=T&&T<=r[1])c++});arr.push({T:T,c:c})}
return {lo:lo,hi:hi,arr:arr};
}
function fnHtml(R,lab){
var A=agg(R),cov=coverage(R),maxc=Math.max.apply(null,cov.arr.map(function(x){return x.c})),U=16;
var H3='font-size:13px;font-weight:500;margin:12px 0 4px;',P='font-size:13px;color:var(--text-secondary);line-height:1.55;';
var chips=R.map(function(r,i){return '<span style="display:inline-block;background:var(--surface-2);border:0.5px solid var(--border);border-radius:6px;padding:3px 8px;font-size:12px;margin:0 6px 6px 0;"><b style="font-weight:500;">'+lab[i]+'</b> '+fr(r[0],r[1])+'</span>'}).join('');
var bars=cov.arr.map(function(x){
var inz=x.T>=A.a-1e-9&&x.T<=A.b+1e-9;
return '<div title="'+fm(x.T)+' °C: '+x.c+' von '+R.length+' Bereichen" style="flex:1;min-width:2px;height:'+(maxc*U+4)+'px;display:flex;align-items:flex-end;background:'+(inz?'color-mix(in srgb, var(--fill-success) 22%, transparent)':'transparent')+';"><div style="width:100%;height:'+(x.c*U)+'px;background:'+(inz&&A.kind==='overlap'?'var(--fill-success)':'var(--text-muted)')+';opacity:'+(inz&&A.kind==='overlap'?1:0.55)+';"></div></div>';
}).join('');
var s2=A.kind==='overlap'
?'Für jede Temperatur wird gezählt, wie viele Wunschbereiche sie enthalten. Der Bereich mit den meisten Treffern wird zum Gruppenbereich: <b style="font-weight:500;color:var(--text-primary);">'+fr(A.a,A.b)+'</b> ('+A.n+' von '+R.length+' Bereichen).'
:'Kein Wert wird von mehr als einem Wunschbereich geteilt. Deshalb zählt die Lücke zwischen den nächsten zwei Temperaturen: Ende von <b style="font-weight:500;color:var(--text-primary);">'+lab[A.l]+'</b> ('+fm(A.a)+' °C) und Beginn von <b style="font-weight:500;color:var(--text-primary);">'+lab[A.u]+'</b> ('+fm(A.b)+' °C). Gruppenbereich: <b style="font-weight:500;color:var(--text-primary);">'+fr(A.a,A.b)+'</b>.';
var s3=A.kind==='overlap'
?'Weil Energiesparen im Vordergrund steht, gilt der <b style="font-weight:500;color:var(--text-primary);">niedrigste Wert</b> des Gruppenbereichs.'
:'Ohne Überschneidung gilt der <b style="font-weight:500;color:var(--text-primary);">Mittelwert</b> aus '+fm(A.a)+' und '+fm(A.b)+' °C.';
return '<div style="'+H3+'margin-top:0;">1 · Wunschbereiche sammeln</div><div>'+chips+'</div>'
+'<div style="'+H3+'">2 · Gruppenbereich bilden</div><div style="'+P+'">'+s2+'</div>'
+'<div style="margin-top:8px;"><div style="display:flex;gap:1px;align-items:flex-end;">'+bars+'</div>'
+'<div style="display:flex;justify-content:space-between;font-size:11px;color:var(--text-muted);margin-top:3px;"><span>'+fm(cov.lo)+' °C</span><span>Anzahl übereinstimmender Bereiche pro Temperatur (grün = Gruppenbereich)</span><span>'+fm(cov.hi)+' °C</span></div></div>'
+'<div style="'+H3+'">3 · Gruppenwunschwert festlegen</div><div style="'+P+'">'+s3+'</div>'
+'<div style="margin-top:8px;display:inline-block;background:var(--bg-success);color:var(--text-success);border:1px solid var(--border-success);border-radius:var(--radius);padding:6px 12px;font-size:16px;font-weight:500;">Gruppenwunschwert '+fm(A.soll)+' °C</div>';
}
function renderFn(){
var live=fnMode==='live';
$('fn').style.display=fnOpen&&tab==='group'?'':'none';
$('fn-open').setAttribute('aria-expanded',fnOpen);$('fn-open-t').textContent=fnOpen?'Aggregationsfunktion ausblenden':'Aggregationsfunktion ansehen';
$('fn-live').style.background=live?'var(--bg-accent)':'';$('fn-ex').style.background=live?'':'var(--bg-accent)';
$('fn-live').setAttribute('aria-pressed',live);$('fn-ex').setAttribute('aria-pressed',!live);
if(!fnOpen)return;
$('fn-body').innerHTML=live?fnHtml(allRanges(),NAMES):fnHtml([[16,17],[19,20],[21,22],[24,25]],['Bereich A','Bereich B','Bereich C','Bereich D']);
}
/* ============ Gesamtdarstellung ============ */
function render(){
var G=agg(allRanges());
var pending=G.soll!==confirmed.soll||G.a!==confirmed.a||G.b!==confirmed.b;
var tgt=source==='self'?selfTemp:confirmed.soll;
var hasIst=IST!==null,diff=hasIst?tgt-IST:0;
/* Verbindung */
var cn=$('conn');
if(srvErr){cn.textContent='Server nicht erreichbar';cn.style.color='var(--text-danger)'}
else if(online){cn.textContent='● Arduino verbunden';cn.style.color='var(--text-success)'}
else{cn.textContent='○ Arduino nicht verbunden';cn.style.color='var(--text-warning)'}
/* Betriebsart */
$('m-auto').setAttribute('aria-pressed',source==='group');
$('m-man').setAttribute('aria-pressed',source==='self');
$('mode-hint').textContent=source==='self'
?'Manuell: Die Heizung hält die Temperatur, die du in Tab 3 gewählt hast.'
:'Automatik: Die Heizung hält den bestätigten Gruppenwunschwert (Tab 2).';
/* Statuskarte: was macht die Heizung und warum */
var b=$('badge'),hot=online&&heating;
b.textContent=!online?'Offline':hot?'Heizt':'Aus';
b.style.background=!online?'var(--surface-2)':hot?'var(--bg-warning)':'var(--bg-success)';
b.style.color=!online?'var(--text-secondary)':hot?'var(--text-warning)':'var(--text-success)';
$('lvl-t').textContent=!online?'Keine Verbindung zum Arduino':hot?'Heizung läuft':'Heizung ist aus';
$('t-ist').textContent=hasIst?fm(IST)+' °C':'–';
$('t-tgt').textContent=fm(tgt)+' °C';
$('t-src').textContent=source==='self'?'selbst gewählt (manuell)':'Gruppenwunschwert, bestätigt';
$('t-diff').textContent=!hasIst?'–':diff>0?fm(diff)+' °C zu kalt':diff<0?fm(-diff)+' °C wärmer':'erreicht';
var why,next;
if(!online){
why='Der Arduino hat sich seit über 15 Sekunden nicht gemeldet. Ohne Verbindung schaltet er die Heizung nach 30 Sekunden selbst ab.';
next='Sobald er wieder verbunden ist, wird der Zielwert '+fm(tgt)+' °C wieder angewendet.';
}else if(!hasIst){
why='Der Temperatursensor liefert keinen gültigen Wert. Zur Sicherheit wird nicht geheizt.';
next='';
}else if(hot){
why='Die Ist-Temperatur ('+fm(IST)+' °C) liegt unter dem Zielwert ('+fm(tgt)+' °C), deshalb heizt die Heizung.';
next='Danach: Sobald '+fm(tgt)+' °C erreicht sind, schaltet die Heizung ab.';
}else if(IST>=tgt){
why='Die Ist-Temperatur ('+fm(IST)+' °C) hat den Zielwert ('+fm(tgt)+' °C) erreicht oder überschritten, deshalb wird nicht geheizt.';
next='Danach: Fällt die Temperatur unter '+fm(tgt-HYST)+' °C, heizt die Heizung wieder.';
}else{
why='Die Ist-Temperatur ('+fm(IST)+' °C) liegt nur knapp unter dem Zielwert ('+fm(tgt)+' °C). Die Heizung wartet, damit sie nicht ständig ein- und ausschaltet.';
next='Danach: Fällt die Temperatur unter '+fm(tgt-HYST)+' °C, heizt die Heizung wieder.';
}
$('why').textContent=why;
$('srcline').textContent=source==='self'
?'Zielwert: Deine selbst gewählte Temperatur. Der Gruppenwunschwert ('+fm(G.soll)+' °C) wird gerade nicht verwendet.'
:'Zielwert: Der Gruppenwunschwert, mit dem du einverstanden bist.';
$('next').textContent=next;
var pe=$('pend');pe.style.display=pending?'flex':'none';
$('pend-t').textContent=source==='self'
?'Der Gruppenwunschwert hat sich auf '+fm(G.soll)+' °C geändert und wartet auf deine Bestätigung.'
:'Neuer Gruppenwunschwert '+fm(G.soll)+' °C wartet auf deine Bestätigung. Bis dahin gilt '+fm(confirmed.soll)+' °C.';
var tt=$('toast');tt.style.display=toast?'block':'none';tt.textContent=toast?'✓ '+toast:'';
/* Tabs */
[['pref','t-pref'],['group','t-group'],['self','t-self']].forEach(function(x){
var on=tab===x[0],e=$(x[1]);
e.setAttribute('aria-selected',on);e.style.borderBottomColor=on?'var(--text-primary)':'transparent';
e.style.color=on?'var(--text-primary)':'var(--text-secondary)';e.style.fontWeight=on?'500':'400';
$('p-'+x[0]).style.display=on?'':'none';
});
var changed=draft[0]!==mine[0]||draft[1]!==mine[1];
$('dot-pref').style.display=changed?'inline':'none';$('dot-group').style.display=pending?'inline':'none';
/* Tab 1 */
$('plo').value=draft[0];$('phi').value=draft[1];
$('plo-o').textContent=fm(draft[0])+' °C';$('phi-o').textContent=fm(draft[1])+' °C';
$('pband').style.left=pct(draft[0])+'%';$('pband').style.width=Math.max(pct(draft[1])-pct(draft[0]),1.6)+'%';
var pc=$('pcommit');pc.style.display=changed?'block':'none';pc.style.left='calc('+pct(mine[0])+'% - 3px)';pc.style.width='calc('+Math.max(pct(mine[1])-pct(mine[0]),1.6)+'% + 6px)';
var pf=$('pflag');pf.textContent=fr(draft[0],draft[1]);
if($('p-pref').style.display!=='none'){var pw=$('pchart').offsetWidth,w=pf.offsetWidth;pf.style.left=Math.min(pw-w/2+8,Math.max(w/2-8,(pct(draft[0])+pct(draft[1]))/200*pw))+'px'}
$('apply').disabled=!changed;$('reset').style.display=changed?'':'none';
var ps=$('pstate');
ps.textContent=changed?'Entwurf, noch nicht übernommen (gestrichelt: bisher '+fr(mine[0],mine[1])+')':'Übernommen: '+fr(mine[0],mine[1]);
ps.style.color=changed?'var(--text-warning)':'var(--text-success)';
$('applied').style.display=applied&&!changed?'block':'none';
$('applied-t').textContent='Dein Bereich '+fr(mine[0],mine[1])+' ist übernommen und fließt in die Gruppe ein. '+(pending?'Der Gruppenwunschwert ändert sich dadurch auf '+fm(G.soll)+' °C und wartet auf deine Bestätigung.':'Der Gruppenwunschwert bleibt bei '+fm(G.soll)+' °C.');
document.querySelectorAll('[data-p]').forEach(function(x){
var p=x.dataset.p.split(',');var on=draft[0]===parseFloat(p[0])&&draft[1]===parseFloat(p[1]);
x.style.background=on?'var(--bg-accent)':'';x.setAttribute('aria-pressed',on);
});
/* Tab 2 */
if(tab==='group')updateChart(G);
var cf=$('confirm'),ag=$('agree');
if(pending){
cf.style.background='var(--bg-warning)';cf.style.color='var(--text-warning)';
$('confirm-t').textContent='Bist du mit dem Gruppenwunschwert von '+fm(G.soll)+' °C einverstanden?';
$('confirm-d').textContent='Bei Zustimmung regelt die Heizung auf '+fm(G.soll)+' °C (Automatik). Bis dahin gilt '+(source==='self'?'deine selbst gewählte Temperatur ('+fm(selfTemp)+' °C).':fm(confirmed.soll)+' °C.');
ag.style.display='';$('agree-t').textContent='Einverstanden';
}else if(source==='self'){
cf.style.background='var(--surface-1)';cf.style.color='var(--text-primary)';
$('confirm-t').textContent='Du nutzt gerade deine selbst gewählte Temperatur ('+fm(selfTemp)+' °C)';
$('confirm-d').textContent='Mit „Einverstanden“ wechselt die Heizung zurück auf Automatik mit dem Gruppenwunschwert '+fm(G.soll)+' °C.';
ag.style.display='';$('agree-t').textContent='Einverstanden, Gruppenwert nutzen';
}else{
cf.style.background='var(--bg-success)';cf.style.color='var(--text-success)';
$('confirm-t').textContent='✓ Du bist mit dem Gruppenwunschwert von '+fm(G.soll)+' °C einverstanden';
$('confirm-d').textContent='Die Heizung regelt auf diesen Wert. Änderst du deinen Bereich, musst du den neuen Wert erneut bestätigen.';
ag.style.display='none';
}
renderFn();
/* Tab 3 */
$('sst').value=selfDraft;$('sst-o').textContent=fm(selfDraft)+' °C';
$('self-cmp').textContent='Gruppenwunschwert aktuell: '+fm(G.soll)+' °C'+(selfDraft===G.soll?' (gleich deiner Auswahl)':' · deine Auswahl liegt '+fm(Math.abs(selfDraft-G.soll))+' °C '+(selfDraft>G.soll?'darüber':'darunter'));
var active=source==='self'&&selfTemp===selfDraft;
$('self-use').disabled=active;$('self-use-t').textContent=active?'Wird genutzt':'Diese Temperatur nutzen';
$('self-back').style.display=source==='self'?'':'none';
}
function go(t){tab=t;applied=false;toast='';render()}
/* ============ Ereignisse ============ */
['plo','phi'].forEach(function(id){$(id).addEventListener('input',function(e){
var lo=parseFloat($('plo').value),hi=parseFloat($('phi').value);
if(lo>hi){if(e.target.id==='plo')hi=lo;else lo=hi}
draft=[lo,hi];applied=false;toast='';render();
})});
$('apply').onclick=function(){send({mine:draft}).then(function(){applied=true;render()})};
$('reset').onclick=function(){draft=mine.slice();applied=false;render()};
$('to-group').onclick=function(){go('group')};
document.querySelectorAll('[data-p]').forEach(function(x){x.onclick=function(){var p=x.dataset.p.split(',');draft=[parseFloat(p[0]),parseFloat(p[1])];applied=false;toast='';render()}});
$('t-pref').onclick=function(){go('pref')};$('t-group').onclick=function(){go('group')};$('t-self').onclick=function(){go('self')};
$('pend-go').onclick=function(){go('group')};
$('fn-open').onclick=function(){fnOpen=!fnOpen;render()};
$('fn-close').onclick=function(){fnOpen=false;render()};
$('fn-live').onclick=function(){fnMode='live';render()};$('fn-ex').onclick=function(){fnMode='ex';render()};
$('m-auto').onclick=function(){if(source!=='group')send({mode:'auto'},SAVED)};
$('m-man').onclick=function(){if(source!=='self')send({mode:'manual'},SAVED)};
$('agree').onclick=function(){
var G=agg(allRanges());
send({confirmed:{a:G.a,b:G.b,soll:G.soll},mode:'auto'},SAVED);
};
$('adjust').onclick=function(){go('pref')};
$('sst').addEventListener('input',function(){selfDraft=parseFloat($('sst').value);toast='';render()});
$('self-use').onclick=function(){send({selfTemp:selfDraft,mode:'manual'},SAVED)};
$('self-back').onclick=function(){send({mode:'auto'},SAVED)};
window.addEventListener('resize',render);
buildChart();buildPChart();render();
refresh(true);
setInterval(function(){refresh(false)},POLL_MS);
</script>
</body>
</html>

271
UCPSMain/main.go 100644
View File

@ -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())
}