diff --git a/gauge.py b/gauge.py index 1e21172..fb0480b 100644 --- a/gauge.py +++ b/gauge.py @@ -384,6 +384,53 @@ def publish_backlight_states(client): log_err(f"Backlight state publish failed for gauge {i}: {e}") +def restore_backlight_state(gauge_idx, payload): + """Restore retained backlight state without republishing it back to MQTT.""" + global backlight_color, backlight_brightness, backlight_on, _bl_effect + + try: + data = ujson.loads(payload) + except Exception as e: + warn(f"Invalid retained backlight state for gauge {gauge_idx}: '{payload}' ({e})") + return + + state_on = data.get("state", "OFF").upper() != "OFF" + effect = data.get("effect") + if effect not in _EFFECTS: + effect = None + + if not state_on: + _bl_effect[gauge_idx] = None + backlight_on[gauge_idx] = False + set_backlight_brightness(gauge_idx, 0) + return + + color = data.get("color", {}) + r = max(0, min(255, int(color.get("r", backlight_color[gauge_idx][0])))) + g = max(0, min(255, int(color.get("g", backlight_color[gauge_idx][1])))) + b = max(0, min(255, int(color.get("b", backlight_color[gauge_idx][2])))) + raw_br = data.get("brightness", None) + if raw_br is not None: + brightness = max(0, min(100, round(int(raw_br) / 2.55))) + elif backlight_brightness[gauge_idx] > 0: + brightness = backlight_brightness[gauge_idx] + else: + brightness = 100 + + _bl_effect[gauge_idx] = effect + if effect: + scale = brightness / 100 + rs = int(r * scale) + gs = int(g * scale) + bs_ = int(b * scale) + _send_effect(gauge_idx, _LED_BACKLIGHT_RANGE, (rs, gs, bs_), effect) + backlight_color[gauge_idx] = (r, g, b) + backlight_brightness[gauge_idx] = brightness + backlight_on[gauge_idx] = True + else: + set_backlight_color(gauge_idx, r, g, b, brightness) + + def _flush_backlight_state(): global _bl_dirty_since if _bl_dirty_since is None: @@ -570,6 +617,11 @@ def on_message(topic, payload): return for i, gt in enumerate(gauge_topics): + if topic == gt["led_bl_state"]: + restore_backlight_state(i, payload) + info(f"Gauge {i} backlight state restored") + return + if topic == gt["zero"]: info(f"Home command received for gauge {i}") gauge_home(i) @@ -798,6 +850,7 @@ def _subscribe_all(c): c.subscribe(f"{prefix}/led/red/set") c.subscribe(f"{prefix}/led/green/set") c.subscribe(f"{prefix}/led/backlight/set") + c.subscribe(f"{prefix}/led/backlight/state") c.subscribe(f"{prefix}/status_led/red/set") c.subscribe(f"{prefix}/status_led/green/set")