Wifi and MQTT checks and reconnects added
This commit is contained in:
@@ -32,19 +32,33 @@ from gauge_vid6008 import Gauge
|
|||||||
# Logging
|
# Logging
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
def _ts():
|
def _ts():
|
||||||
ms = utime.ticks_ms()
|
ms = utime.ticks_ms()
|
||||||
return f"{(ms // 3600000) % 24:02d}:{(ms // 60000) % 60:02d}:{(ms // 1000) % 60:02d}.{ms % 1000:03d}"
|
return f"{(ms // 3600000) % 24:02d}:{(ms // 60000) % 60:02d}:{(ms // 1000) % 60:02d}.{ms % 1000:03d}"
|
||||||
|
|
||||||
def log(level, msg): print(f"[{_ts()}] {level:5s} {msg}")
|
|
||||||
def info(msg): log("INFO", msg)
|
def log(level, msg):
|
||||||
def warn(msg): log("WARN", msg)
|
print(f"[{_ts()}] {level:5s} {msg}")
|
||||||
def log_err(msg): log("ERROR", msg)
|
|
||||||
|
|
||||||
|
def info(msg):
|
||||||
|
log("INFO", msg)
|
||||||
|
|
||||||
|
|
||||||
|
def warn(msg):
|
||||||
|
log("WARN", msg)
|
||||||
|
|
||||||
|
|
||||||
|
def log_err(msg):
|
||||||
|
log("ERROR", msg)
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
# Configuration
|
# Configuration
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
def _load_config():
|
def _load_config():
|
||||||
try:
|
try:
|
||||||
with open("/config.json") as f:
|
with open("/config.json") as f:
|
||||||
@@ -58,6 +72,7 @@ def _load_config():
|
|||||||
log_err(f"config.json parse error: {e} — cannot continue")
|
log_err(f"config.json parse error: {e} — cannot continue")
|
||||||
raise
|
raise
|
||||||
|
|
||||||
|
|
||||||
_cfg = _load_config()
|
_cfg = _load_config()
|
||||||
|
|
||||||
WIFI_SSID = _cfg["wifi_ssid"]
|
WIFI_SSID = _cfg["wifi_ssid"]
|
||||||
@@ -124,37 +139,82 @@ _DEVICE = {
|
|||||||
# WiFi
|
# WiFi
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
_wifi_reconnect_delay_s = 5
|
||||||
|
_wifi_check_interval_ms = 5000
|
||||||
|
_last_wifi_check = 0
|
||||||
|
_wifi_sta = None
|
||||||
|
|
||||||
|
|
||||||
def connect_wifi(ssid, password, timeout_s=15):
|
def connect_wifi(ssid, password, timeout_s=15):
|
||||||
sta = network.WLAN(network.STA_IF)
|
global _wifi_sta
|
||||||
sta.active(True)
|
_wifi_sta = network.WLAN(network.STA_IF)
|
||||||
if sta.isconnected():
|
_wifi_sta.active(True)
|
||||||
ip, mask, gw, dns = sta.ifconfig()
|
if _wifi_sta.isconnected():
|
||||||
|
ip, mask, gw, dns = _wifi_sta.ifconfig()
|
||||||
info("WiFi already connected")
|
info("WiFi already connected")
|
||||||
info(f" IP:{ip} mask:{mask} gw:{gw} dns:{dns}")
|
info(f" IP:{ip} mask:{mask} gw:{gw} dns:{dns}")
|
||||||
return ip
|
return ip
|
||||||
info(f"WiFi connecting to '{ssid}' ...")
|
info(f"WiFi connecting to '{ssid}' ...")
|
||||||
sta.connect(ssid, password)
|
_wifi_sta.connect(ssid, password)
|
||||||
deadline = utime.time() + timeout_s
|
deadline = utime.time() + timeout_s
|
||||||
while not sta.isconnected():
|
while not _wifi_sta.isconnected():
|
||||||
if utime.time() > deadline:
|
if utime.time() > deadline:
|
||||||
log_err(f"WiFi connect timeout after {timeout_s}s")
|
log_err(f"WiFi connect timeout after {timeout_s}s")
|
||||||
raise OSError("WiFi connect timeout")
|
raise OSError("WiFi connect timeout")
|
||||||
utime.sleep_ms(200)
|
utime.sleep_ms(200)
|
||||||
ip, mask, gw, dns = sta.ifconfig()
|
ip, mask, gw, dns = _wifi_sta.ifconfig()
|
||||||
mac = ':'.join(f'{b:02x}' for b in sta.config('mac'))
|
mac = ":".join(f"{b:02x}" for b in _wifi_sta.config("mac"))
|
||||||
info("WiFi connected!")
|
info("WiFi connected!")
|
||||||
info(f" SSID : {ssid}")
|
info(f" SSID : {ssid}")
|
||||||
info(f" MAC : {mac}")
|
info(f" MAC : {mac}")
|
||||||
info(f" IP : {ip} mask:{mask} gw:{gw} dns:{dns}")
|
info(f" IP : {ip} mask:{mask} gw:{gw} dns:{dns}")
|
||||||
return ip
|
return ip
|
||||||
|
|
||||||
|
|
||||||
|
def check_wifi():
|
||||||
|
global _last_wifi_check, _wifi_reconnect_delay_s
|
||||||
|
now = utime.ticks_ms()
|
||||||
|
if utime.ticks_diff(now, _last_wifi_check) < _wifi_check_interval_ms:
|
||||||
|
return
|
||||||
|
_last_wifi_check = now
|
||||||
|
|
||||||
|
if _wifi_sta is None:
|
||||||
|
_wifi_sta = network.WLAN(network.STA_IF)
|
||||||
|
|
||||||
|
if _wifi_sta.isconnected():
|
||||||
|
return
|
||||||
|
|
||||||
|
log_err("WiFi lost connection — attempting reconnect...")
|
||||||
|
try:
|
||||||
|
_wifi_sta.active(True)
|
||||||
|
_wifi_sta.connect(WIFI_SSID, WIFI_PASSWORD)
|
||||||
|
deadline = utime.time() + 15
|
||||||
|
while not _wifi_sta.isconnected():
|
||||||
|
if utime.time() > deadline:
|
||||||
|
log_err("WiFi reconnect timeout")
|
||||||
|
return
|
||||||
|
utime.sleep_ms(200)
|
||||||
|
ip, mask, gw, dns = _wifi_sta.ifconfig()
|
||||||
|
info(f"WiFi reconnected! IP:{ip}")
|
||||||
|
except Exception as e:
|
||||||
|
log_err(f"WiFi reconnect failed: {e}")
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
# Gauge
|
# Gauge
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
info("Initialising gauge ...")
|
info("Initialising gauge ...")
|
||||||
gauge = Gauge(pins=GAUGE_PINS, mode=GAUGE_MODE, min_val=GAUGE_MIN, max_val=GAUGE_MAX, step_us=GAUGE_STEP_US)
|
gauge = Gauge(
|
||||||
info(f"Gauge ready pins={GAUGE_PINS} mode={GAUGE_MODE} range=[{GAUGE_MIN}, {GAUGE_MAX}] step_us={GAUGE_STEP_US}")
|
pins=GAUGE_PINS,
|
||||||
|
mode=GAUGE_MODE,
|
||||||
|
min_val=GAUGE_MIN,
|
||||||
|
max_val=GAUGE_MAX,
|
||||||
|
step_us=GAUGE_STEP_US,
|
||||||
|
)
|
||||||
|
info(
|
||||||
|
f"Gauge ready pins={GAUGE_PINS} mode={GAUGE_MODE} range=[{GAUGE_MIN}, {GAUGE_MAX}] step_us={GAUGE_STEP_US}"
|
||||||
|
)
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
# LEDs
|
# LEDs
|
||||||
@@ -170,25 +230,37 @@ _backlight_on = False
|
|||||||
_bl_dirty_since = None
|
_bl_dirty_since = None
|
||||||
_BL_SAVE_DELAY_MS = 5000
|
_BL_SAVE_DELAY_MS = 5000
|
||||||
|
|
||||||
|
|
||||||
def _flush_backlight(client):
|
def _flush_backlight(client):
|
||||||
payload = {
|
payload = {
|
||||||
"state": "ON" if _backlight_on else "OFF",
|
"state": "ON" if _backlight_on else "OFF",
|
||||||
"color": {"r": _backlight_color[0], "g": _backlight_color[1], "b": _backlight_color[2]},
|
"color": {
|
||||||
|
"r": _backlight_color[0],
|
||||||
|
"g": _backlight_color[1],
|
||||||
|
"b": _backlight_color[2],
|
||||||
|
},
|
||||||
"brightness": int(_backlight_brightness * 2.55),
|
"brightness": int(_backlight_brightness * 2.55),
|
||||||
}
|
}
|
||||||
client.publish(T_LED_BL, ujson.dumps(payload), retain=True)
|
client.publish(T_LED_BL, ujson.dumps(payload), retain=True)
|
||||||
info(f"Backlight state retained: {payload['state']} {_backlight_color} @ {_backlight_brightness}%")
|
info(
|
||||||
|
f"Backlight state retained: {payload['state']} {_backlight_color} @ {_backlight_brightness}%"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def _backlight_changed(new_color, new_on, new_brightness):
|
def _backlight_changed(new_color, new_on, new_brightness):
|
||||||
"""Return True if any backlight property differs from current state."""
|
"""Return True if any backlight property differs from current state."""
|
||||||
return (new_color != _backlight_color or
|
return (
|
||||||
new_on != _backlight_on or
|
new_color != _backlight_color
|
||||||
(new_on and new_brightness != _backlight_brightness))
|
or new_on != _backlight_on
|
||||||
|
or (new_on and new_brightness != _backlight_brightness)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def _mark_bl_dirty():
|
def _mark_bl_dirty():
|
||||||
global _bl_dirty_since
|
global _bl_dirty_since
|
||||||
_bl_dirty_since = utime.ticks_ms()
|
_bl_dirty_since = utime.ticks_ms()
|
||||||
|
|
||||||
|
|
||||||
def set_backlight_color(r, g, b, brightness=None):
|
def set_backlight_color(r, g, b, brightness=None):
|
||||||
global _backlight_color, _backlight_brightness, _backlight_on
|
global _backlight_color, _backlight_brightness, _backlight_on
|
||||||
if brightness is None:
|
if brightness is None:
|
||||||
@@ -206,6 +278,7 @@ def set_backlight_color(r, g, b, brightness=None):
|
|||||||
led_bl.write()
|
led_bl.write()
|
||||||
_mark_bl_dirty()
|
_mark_bl_dirty()
|
||||||
|
|
||||||
|
|
||||||
def set_backlight_brightness(brightness):
|
def set_backlight_brightness(brightness):
|
||||||
global _backlight_brightness, _backlight_on
|
global _backlight_brightness, _backlight_on
|
||||||
clamped = max(0, min(100, brightness))
|
clamped = max(0, min(100, brightness))
|
||||||
@@ -222,6 +295,7 @@ def set_backlight_brightness(brightness):
|
|||||||
led_bl.write()
|
led_bl.write()
|
||||||
_mark_bl_dirty()
|
_mark_bl_dirty()
|
||||||
|
|
||||||
|
|
||||||
info(f"LEDs ready red={LED_RED_PIN} green={LED_GREEN_PIN} backlight={LED_BL_PIN}")
|
info(f"LEDs ready red={LED_RED_PIN} green={LED_GREEN_PIN} backlight={LED_BL_PIN}")
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
@@ -231,11 +305,26 @@ info(f"LEDs ready red={LED_RED_PIN} green={LED_GREEN_PIN} backlight={LED_BL_P
|
|||||||
_target_value = GAUGE_MIN
|
_target_value = GAUGE_MIN
|
||||||
_last_rezero_ms = None # set to ticks_ms() in main()
|
_last_rezero_ms = None # set to ticks_ms() in main()
|
||||||
client_ref = None
|
client_ref = None
|
||||||
|
_mqtt_connected = False
|
||||||
|
|
||||||
|
|
||||||
|
def _publish(topic, payload, retain=False):
|
||||||
|
"""Safely publish MQTT message, returning True on success."""
|
||||||
|
if client_ref is None:
|
||||||
|
return False
|
||||||
|
try:
|
||||||
|
client_ref.publish(topic, payload, retain=retain)
|
||||||
|
return True
|
||||||
|
except Exception as e:
|
||||||
|
log_err(f"MQTT publish failed: {e}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
# MQTT callbacks
|
# MQTT callbacks
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
def on_message(topic, payload):
|
def on_message(topic, payload):
|
||||||
if client_ref is None:
|
if client_ref is None:
|
||||||
return
|
return
|
||||||
@@ -254,14 +343,14 @@ def on_message(topic, payload):
|
|||||||
if topic == T_LED_RED:
|
if topic == T_LED_RED:
|
||||||
state = payload.upper() == "ON"
|
state = payload.upper() == "ON"
|
||||||
led_red.value(1 if state else 0)
|
led_red.value(1 if state else 0)
|
||||||
client_ref.publish(T_LED_RED_STATE, "ON" if state else "OFF", retain=True)
|
_publish(T_LED_RED_STATE, "ON" if state else "OFF", retain=True)
|
||||||
info(f"Red LED → {'ON' if state else 'OFF'}")
|
info(f"Red LED → {'ON' if state else 'OFF'}")
|
||||||
return
|
return
|
||||||
|
|
||||||
if topic == T_LED_GREEN:
|
if topic == T_LED_GREEN:
|
||||||
state = payload.upper() == "ON"
|
state = payload.upper() == "ON"
|
||||||
led_green.value(1 if state else 0)
|
led_green.value(1 if state else 0)
|
||||||
client_ref.publish(T_LED_GREEN_STATE, "ON" if state else "OFF", retain=True)
|
_publish(T_LED_GREEN_STATE, "ON" if state else "OFF", retain=True)
|
||||||
info(f"Green LED → {'ON' if state else 'OFF'}")
|
info(f"Green LED → {'ON' if state else 'OFF'}")
|
||||||
return
|
return
|
||||||
|
|
||||||
@@ -269,10 +358,12 @@ def on_message(topic, payload):
|
|||||||
info(f"Backlight raw payload: '{payload}'")
|
info(f"Backlight raw payload: '{payload}'")
|
||||||
try:
|
try:
|
||||||
data = ujson.loads(payload)
|
data = ujson.loads(payload)
|
||||||
info(f"Backlight parsed: state={data.get('state')} color={data.get('color')} brightness={data.get('brightness')}")
|
info(
|
||||||
|
f"Backlight parsed: state={data.get('state')} color={data.get('color')} brightness={data.get('brightness')}"
|
||||||
|
)
|
||||||
if data.get("state", "ON").upper() == "OFF":
|
if data.get("state", "ON").upper() == "OFF":
|
||||||
set_backlight_brightness(0)
|
set_backlight_brightness(0)
|
||||||
client_ref.publish(T_LED_BL_STATE, ujson.dumps({"state": "OFF"}), retain=True)
|
_publish(T_LED_BL_STATE, ujson.dumps({"state": "OFF"}), retain=True)
|
||||||
info("Backlight → OFF")
|
info("Backlight → OFF")
|
||||||
return
|
return
|
||||||
color = data.get("color", {})
|
color = data.get("color", {})
|
||||||
@@ -292,9 +383,13 @@ def on_message(topic, payload):
|
|||||||
return
|
return
|
||||||
set_backlight_color(r, g, b, brightness)
|
set_backlight_color(r, g, b, brightness)
|
||||||
color_hex = f"#{r:02x}{g:02x}{b:02x}"
|
color_hex = f"#{r:02x}{g:02x}{b:02x}"
|
||||||
state = {"state": "ON", "color_mode": "rgb", "brightness": int(brightness * 2.55),
|
state = {
|
||||||
"color": {"r": r, "g": g, "b": b}}
|
"state": "ON",
|
||||||
client_ref.publish(T_LED_BL_STATE, ujson.dumps(state), retain=True)
|
"color_mode": "rgb",
|
||||||
|
"brightness": int(brightness * 2.55),
|
||||||
|
"color": {"r": r, "g": g, "b": b},
|
||||||
|
}
|
||||||
|
_publish(T_LED_BL_STATE, ujson.dumps(state), retain=True)
|
||||||
info(f"Backlight → {color_hex} @ {brightness}%")
|
info(f"Backlight → {color_hex} @ {brightness}%")
|
||||||
return
|
return
|
||||||
|
|
||||||
@@ -306,12 +401,14 @@ def on_message(topic, payload):
|
|||||||
except ValueError:
|
except ValueError:
|
||||||
warn(f"Invalid set value: '{payload}'")
|
warn(f"Invalid set value: '{payload}'")
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
# MQTT connect + discovery
|
# MQTT connect + discovery
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
def connect_mqtt():
|
def connect_mqtt():
|
||||||
global client_ref
|
global client_ref, _mqtt_connected
|
||||||
info(f"Connecting to MQTT broker {MQTT_BROKER}:{MQTT_PORT} ...")
|
info(f"Connecting to MQTT broker {MQTT_BROKER}:{MQTT_PORT} ...")
|
||||||
client = MQTTClient(
|
client = MQTTClient(
|
||||||
client_id=MQTT_CLIENT_ID,
|
client_id=MQTT_CLIENT_ID,
|
||||||
@@ -324,23 +421,72 @@ def connect_mqtt():
|
|||||||
client.set_last_will(T_STATUS, b"offline", retain=True, qos=0)
|
client.set_last_will(T_STATUS, b"offline", retain=True, qos=0)
|
||||||
client.set_callback(on_message)
|
client.set_callback(on_message)
|
||||||
client.connect()
|
client.connect()
|
||||||
# Set client_ref AFTER connect so retained messages during subscribe
|
|
||||||
# are handled safely
|
|
||||||
client_ref = client
|
client_ref = client
|
||||||
client.subscribe(T_SET)
|
client.subscribe(T_SET)
|
||||||
client.subscribe(T_ZERO)
|
client.subscribe(T_ZERO)
|
||||||
client.subscribe(T_LED_RED)
|
client.subscribe(T_LED_RED)
|
||||||
client.subscribe(T_LED_GREEN)
|
client.subscribe(T_LED_GREEN)
|
||||||
client.subscribe(T_LED_BL)
|
client.subscribe(T_LED_BL)
|
||||||
|
_mqtt_connected = True
|
||||||
info(f"MQTT connected client_id={MQTT_CLIENT_ID}")
|
info(f"MQTT connected client_id={MQTT_CLIENT_ID}")
|
||||||
return client
|
return client
|
||||||
|
|
||||||
|
|
||||||
|
def check_mqtt():
|
||||||
|
global client_ref, _mqtt_connected
|
||||||
|
if client_ref is None:
|
||||||
|
return False
|
||||||
|
|
||||||
|
try:
|
||||||
|
client_ref.ping()
|
||||||
|
_mqtt_connected = True
|
||||||
|
return True
|
||||||
|
except Exception as e:
|
||||||
|
log_err(f"MQTT connection lost: {e}")
|
||||||
|
_mqtt_connected = False
|
||||||
|
|
||||||
|
# Try to reconnect
|
||||||
|
log_err("Attempting MQTT reconnection...")
|
||||||
|
for attempt in range(3):
|
||||||
|
try:
|
||||||
|
client_ref = MQTTClient(
|
||||||
|
client_id=MQTT_CLIENT_ID,
|
||||||
|
server=MQTT_BROKER,
|
||||||
|
port=MQTT_PORT,
|
||||||
|
user=MQTT_USER,
|
||||||
|
password=MQTT_PASSWORD,
|
||||||
|
keepalive=60,
|
||||||
|
)
|
||||||
|
client_ref.set_last_will(T_STATUS, b"offline", retain=True, qos=0)
|
||||||
|
client_ref.set_callback(on_message)
|
||||||
|
client_ref.connect()
|
||||||
|
client_ref.subscribe(T_SET)
|
||||||
|
client_ref.subscribe(T_ZERO)
|
||||||
|
client_ref.subscribe(T_LED_RED)
|
||||||
|
client_ref.subscribe(T_LED_GREEN)
|
||||||
|
client_ref.subscribe(T_LED_BL)
|
||||||
|
_mqtt_connected = True
|
||||||
|
info("MQTT reconnected!")
|
||||||
|
publish_discovery(client_ref)
|
||||||
|
publish_state(client_ref)
|
||||||
|
return True
|
||||||
|
except Exception as e2:
|
||||||
|
log_err(f"MQTT reconnect attempt {attempt + 1} failed: {e2}")
|
||||||
|
utime.sleep_ms(2000)
|
||||||
|
|
||||||
|
log_err("MQTT reconnection failed after 3 attempts")
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
def publish_discovery(client):
|
def publish_discovery(client):
|
||||||
"""Publish all HA MQTT discovery payloads using short-form keys to stay under 512 bytes."""
|
"""Publish all HA MQTT discovery payloads using short-form keys to stay under 512 bytes."""
|
||||||
# Full device block only on first payload; subsequent use identifiers-only ref
|
# Full device block only on first payload; subsequent use identifiers-only ref
|
||||||
_dev_ref = {"identifiers": [MQTT_CLIENT_ID]}
|
_dev_ref = {"identifiers": [MQTT_CLIENT_ID]}
|
||||||
|
|
||||||
client.publish(T_DISC_GAUGE, ujson.dumps({
|
client.publish(
|
||||||
|
T_DISC_GAUGE,
|
||||||
|
ujson.dumps(
|
||||||
|
{
|
||||||
"name": GAUGE_ENTITY,
|
"name": GAUGE_ENTITY,
|
||||||
"unique_id": MQTT_CLIENT_ID,
|
"unique_id": MQTT_CLIENT_ID,
|
||||||
"cmd_t": T_SET,
|
"cmd_t": T_SET,
|
||||||
@@ -352,10 +498,16 @@ def publish_discovery(client):
|
|||||||
"unit_of_meas": GAUGE_UNIT,
|
"unit_of_meas": GAUGE_UNIT,
|
||||||
"icon": "mdi:gauge",
|
"icon": "mdi:gauge",
|
||||||
"dev": _DEVICE,
|
"dev": _DEVICE,
|
||||||
}), retain=True)
|
}
|
||||||
|
),
|
||||||
|
retain=True,
|
||||||
|
)
|
||||||
info("Discovery: gauge")
|
info("Discovery: gauge")
|
||||||
|
|
||||||
client.publish(T_DISC_RED, ujson.dumps({
|
client.publish(
|
||||||
|
T_DISC_RED,
|
||||||
|
ujson.dumps(
|
||||||
|
{
|
||||||
"name": RED_ENTITY,
|
"name": RED_ENTITY,
|
||||||
"uniq_id": f"{MQTT_CLIENT_ID}_led_red",
|
"uniq_id": f"{MQTT_CLIENT_ID}_led_red",
|
||||||
"cmd_t": T_LED_RED,
|
"cmd_t": T_LED_RED,
|
||||||
@@ -365,10 +517,16 @@ def publish_discovery(client):
|
|||||||
"icon": "mdi:led-on",
|
"icon": "mdi:led-on",
|
||||||
"dev": _dev_ref,
|
"dev": _dev_ref,
|
||||||
"ret": True,
|
"ret": True,
|
||||||
}), retain=True)
|
}
|
||||||
|
),
|
||||||
|
retain=True,
|
||||||
|
)
|
||||||
info("Discovery: red LED")
|
info("Discovery: red LED")
|
||||||
|
|
||||||
client.publish(T_DISC_GREEN, ujson.dumps({
|
client.publish(
|
||||||
|
T_DISC_GREEN,
|
||||||
|
ujson.dumps(
|
||||||
|
{
|
||||||
"name": GREEN_ENTITY,
|
"name": GREEN_ENTITY,
|
||||||
"uniq_id": f"{MQTT_CLIENT_ID}_led_green",
|
"uniq_id": f"{MQTT_CLIENT_ID}_led_green",
|
||||||
"cmd_t": T_LED_GREEN,
|
"cmd_t": T_LED_GREEN,
|
||||||
@@ -378,10 +536,16 @@ def publish_discovery(client):
|
|||||||
"icon": "mdi:led-on",
|
"icon": "mdi:led-on",
|
||||||
"dev": _dev_ref,
|
"dev": _dev_ref,
|
||||||
"ret": True,
|
"ret": True,
|
||||||
}), retain=True)
|
}
|
||||||
|
),
|
||||||
|
retain=True,
|
||||||
|
)
|
||||||
info("Discovery: green LED")
|
info("Discovery: green LED")
|
||||||
|
|
||||||
client.publish(T_DISC_BL, ujson.dumps({
|
client.publish(
|
||||||
|
T_DISC_BL,
|
||||||
|
ujson.dumps(
|
||||||
|
{
|
||||||
"name": BL_ENTITY,
|
"name": BL_ENTITY,
|
||||||
"uniq_id": f"{MQTT_CLIENT_ID}_led_bl",
|
"uniq_id": f"{MQTT_CLIENT_ID}_led_bl",
|
||||||
"cmd_t": T_LED_BL,
|
"cmd_t": T_LED_BL,
|
||||||
@@ -391,19 +555,25 @@ def publish_discovery(client):
|
|||||||
"icon": "mdi:led-strip",
|
"icon": "mdi:led-strip",
|
||||||
"dev": _dev_ref,
|
"dev": _dev_ref,
|
||||||
"ret": True,
|
"ret": True,
|
||||||
}), retain=True)
|
}
|
||||||
|
),
|
||||||
|
retain=True,
|
||||||
|
)
|
||||||
info("Discovery: backlight")
|
info("Discovery: backlight")
|
||||||
|
|
||||||
|
|
||||||
def publish_state(client):
|
def publish_state(client):
|
||||||
val = gauge.get()
|
val = gauge.get()
|
||||||
client.publish(T_STATE, str(round(val, 1)), retain=True)
|
client.publish(T_STATE, str(round(val, 1)), retain=True)
|
||||||
client.publish(T_STATUS, "online", retain=True)
|
client.publish(T_STATUS, "online", retain=True)
|
||||||
info(f"State published value={val:.1f} step={gauge._current_step}")
|
info(f"State published value={val:.1f} step={gauge._current_step}")
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
# Main
|
# Main
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
info("=" * 48)
|
info("=" * 48)
|
||||||
info("Gauge MQTT controller starting")
|
info("Gauge MQTT controller starting")
|
||||||
@@ -425,6 +595,7 @@ def main():
|
|||||||
|
|
||||||
try:
|
try:
|
||||||
import ota
|
import ota
|
||||||
|
|
||||||
ota.mark_ok()
|
ota.mark_ok()
|
||||||
info("OTA OK flag set")
|
info("OTA OK flag set")
|
||||||
except ImportError:
|
except ImportError:
|
||||||
@@ -442,6 +613,12 @@ def main():
|
|||||||
|
|
||||||
while True:
|
while True:
|
||||||
try:
|
try:
|
||||||
|
check_wifi()
|
||||||
|
|
||||||
|
if not check_mqtt():
|
||||||
|
utime.sleep_ms(1000)
|
||||||
|
continue
|
||||||
|
|
||||||
client.check_msg()
|
client.check_msg()
|
||||||
|
|
||||||
now = utime.ticks_ms()
|
now = utime.ticks_ms()
|
||||||
@@ -455,40 +632,54 @@ def main():
|
|||||||
moved = True
|
moved = True
|
||||||
|
|
||||||
# Publish state during movement at intervals
|
# Publish state during movement at intervals
|
||||||
if moved and utime.ticks_diff(now, last_move_state) >= MOVE_STATE_INTERVAL_MS:
|
if (
|
||||||
publish_state(client)
|
moved
|
||||||
|
and utime.ticks_diff(now, last_move_state) >= MOVE_STATE_INTERVAL_MS
|
||||||
|
):
|
||||||
|
publish_state(client_ref)
|
||||||
last_move_state = now
|
last_move_state = now
|
||||||
|
|
||||||
# Sleep to achieve constant speed
|
# Sleep to achieve constant speed
|
||||||
if moved or (current_target == gauge._current_step and gauge._current_step != gauge._val_to_step(_target_value)):
|
if moved or (
|
||||||
|
current_target == gauge._current_step
|
||||||
|
and gauge._current_step != gauge._val_to_step(_target_value)
|
||||||
|
):
|
||||||
delay_us = 1_000_000 // MICROSTEPS_PER_SECOND
|
delay_us = 1_000_000 // MICROSTEPS_PER_SECOND
|
||||||
utime.sleep_us(delay_us)
|
utime.sleep_us(delay_us)
|
||||||
|
|
||||||
# Periodic auto-rezero (disabled when interval is 0)
|
# Periodic auto-rezero (disabled when interval is 0)
|
||||||
if REZERO_INTERVAL_MS > 0 and utime.ticks_diff(now, _last_rezero_ms) >= REZERO_INTERVAL_MS:
|
if (
|
||||||
|
REZERO_INTERVAL_MS > 0
|
||||||
|
and utime.ticks_diff(now, _last_rezero_ms) >= REZERO_INTERVAL_MS
|
||||||
|
):
|
||||||
info("Auto-rezero triggered")
|
info("Auto-rezero triggered")
|
||||||
saved = _target_value
|
saved = _target_value
|
||||||
gauge.zero()
|
gauge.zero()
|
||||||
if saved > GAUGE_MIN:
|
if saved > GAUGE_MIN:
|
||||||
gauge.set(saved)
|
gauge.set(saved)
|
||||||
publish_state(client)
|
publish_state(client_ref)
|
||||||
_last_rezero_ms = now
|
_last_rezero_ms = now
|
||||||
info(f"Auto-rezero complete, restored to {saved:.1f}")
|
info(f"Auto-rezero complete, restored to {saved:.1f}")
|
||||||
|
|
||||||
# Retain backlight state via MQTT after settling
|
# Retain backlight state via MQTT after settling
|
||||||
if _bl_dirty_since is not None and utime.ticks_diff(now, _bl_dirty_since) >= _BL_SAVE_DELAY_MS:
|
if (
|
||||||
_flush_backlight(client)
|
_bl_dirty_since is not None
|
||||||
|
and utime.ticks_diff(now, _bl_dirty_since) >= _BL_SAVE_DELAY_MS
|
||||||
|
):
|
||||||
|
_flush_backlight(client_ref)
|
||||||
_bl_dirty_since = None
|
_bl_dirty_since = None
|
||||||
|
|
||||||
# Heartbeat
|
# Heartbeat
|
||||||
if utime.ticks_diff(now, last_heartbeat) >= HEARTBEAT_MS:
|
if utime.ticks_diff(now, last_heartbeat) >= HEARTBEAT_MS:
|
||||||
publish_state(client)
|
publish_state(client_ref)
|
||||||
info(f"step={gauge._current_step} phase={gauge._phase} target_step={gauge._val_to_step(_target_value)} expected_phase={gauge._current_step % 4}")
|
info(
|
||||||
|
f"step={gauge._current_step} phase={gauge._phase} target_step={gauge._val_to_step(_target_value)} expected_phase={gauge._current_step % 4}"
|
||||||
|
)
|
||||||
last_heartbeat = now
|
last_heartbeat = now
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
log_err(f"Main loop error: {e} — continuing")
|
log_err(f"Main loop error: {e} — continuing")
|
||||||
utime.sleep_ms(100)
|
utime.sleep_ms(100)
|
||||||
|
|
||||||
main()
|
|
||||||
|
|
||||||
|
main()
|
||||||
|
|||||||
Reference in New Issue
Block a user