Compare commits
5 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 83b269cc88 | |||
| 01eccf47c6 | |||
| 9b0ecf944a | |||
| c6e56b58a0 | |||
| 1a77794fd3 |
@@ -2,6 +2,7 @@ import time
|
||||
from shared.cookingState import CookingState, CookingStates
|
||||
from shared import config
|
||||
import framebuf
|
||||
from shared.microwave_state import MicrowaveState
|
||||
|
||||
# Icon and bitmaps
|
||||
image_weather_frost_bits = bytearray(b'\x01\x00\x13\x901\x18s\x9c\x09 \x05@S\x94\xfe\xfeS\x94\x05@\x09 s\x9c1\x18\x13\x90\x01\x00\x00\x00')
|
||||
@@ -10,12 +11,16 @@ image_CoolHiSmall_bits = bytearray(b'\x1f\xff\xc0?\xff\xe0\x7f\xff\xf0\xff\xdf\x
|
||||
image_CoolLoSmall_bits = bytearray(b'\x1f\xff\xc0 \x00 @\x00\x10\x80 \x08\x80\xa8\x08\x82r\x08\x86#\x08\x81$\x08\x88\xa8\x88\x84q\x08\x9f\xff\xc8\x84q\x08\x88\xa8\x88\x81$\x08\x86#\x08\x82r\x08\x80\xa8\x08\x80 \x08@\x00\x10 \x00 \x1f\xff\xc0')
|
||||
image_music_sound_wave_bits = bytearray(b'\x00\x00\x00\x02\x00\x00\x02 \x00\x02 \x00\x02 \x00\x0a(\x00\x0a\xa8\x00*\xa8\x00\xaa\xaa\x80\x0a\xaa\x00\x0a\xa8\x00\x0a \x00\x02 \x00\x02 \x00\x02\x00\x00\x00\x00\x00')
|
||||
image_weather_temperature_bits = bytearray(b'\x1c\x00\x22\x00+\x00*\x00+\x00*\x00+\x00*\x00*\x00I\x00\x9c\x80\xae\x80\xbe\x80\x9c\x80A\x00>\x00')
|
||||
image_camera_bits = bytearray(b'\x00x\x000\x84\x00\x7f{\x00\xc0\x00\x80\x91\xc6\x80\x860\x80\x85\xd0\x80\x8a(\x80\x8a(\x80\x8a(\x80\x85\xd0\x80\x860\x80\x91\xc6\x80\xc0\x00\x80\x7f\xff\x00\x00\x00\x00')
|
||||
image_cloud_sync_bits = bytearray(b'\x00\x00\x00\x07\xc0\x00\x08 \x00\x10\x10\x000\x08\x00@\x0e\x00\x80\x01\x00\x82 \x80G \x80/\xaf\x00\x02 \x00\x02\xf8\x00\x02p\x00\x02 \x00\x00\x00\x00\x00\x00\x00')
|
||||
fb_image_weather_frost_bits = framebuf.FrameBuffer(image_weather_frost_bits, 15, 16, framebuf.MONO_HLSB)
|
||||
fb_image_CoolHiSmall_bits = framebuf.FrameBuffer(image_CoolHiSmall_bits, 21, 21, framebuf.MONO_HLSB)
|
||||
fb_image_weather_temperature_bits = framebuf.FrameBuffer(image_weather_temperature_bits, 9, 16, framebuf.MONO_HLSB)
|
||||
fb_image_Alert_bits = framebuf.FrameBuffer(image_Alert_bits, 9, 8, framebuf.MONO_HLSB)
|
||||
fb_image_music_sound_wave_bits = framebuf.FrameBuffer(image_music_sound_wave_bits, 17, 16, framebuf.MONO_HLSB)
|
||||
fb_image_CoolLoSmall_bits = framebuf.FrameBuffer(image_CoolLoSmall_bits, 21, 21, framebuf.MONO_HLSB)
|
||||
fb_image_camera_bits = framebuf.FrameBuffer(image_camera_bits, 17, 16, framebuf.MONO_HLSB)
|
||||
fb_image_cloud_sync_bits = framebuf.FrameBuffer(image_cloud_sync_bits, 17, 16, framebuf.MONO_HLSB)
|
||||
|
||||
# Constants
|
||||
CHARACTER_WIDTH = 6
|
||||
@@ -70,44 +75,54 @@ class MicrowaveScreen:
|
||||
|
||||
self.display.fill_rect(x, y, fill_width, height, color)
|
||||
|
||||
def update(self, cooking_state: CookingState | None, defrost_mode: bool = False):
|
||||
def update(self, cooking_state: CookingState | None, defrost_mode: bool = False, microwave_state: str | None = None):
|
||||
self.flick()
|
||||
|
||||
# self.lastUpdateTime = time.time() # Not Used right now
|
||||
|
||||
if not cooking_state or cooking_state.state == CookingStates.IDLE: # Is not currently cooking
|
||||
if (not microwave_state or microwave_state == MicrowaveState.DONE) and (not cooking_state or cooking_state.state == CookingStates.IDLE): # Is not currently cooking
|
||||
self.h_centered_text("Ready !", 28, 1)
|
||||
else:
|
||||
# Screen center
|
||||
if cooking_state.state == CookingStates.STIRRING_REQUIRED:
|
||||
if cooking_state and cooking_state.state == CookingStates.STIRRING_REQUIRED:
|
||||
self._message("Pls Stir", True)
|
||||
elif cooking_state.state == CookingStates.ALERT:
|
||||
self._message("Alert !", True)
|
||||
elif cooking_state.state == CookingStates.DONE:
|
||||
elif cooking_state and cooking_state.state == CookingStates.ALERT:
|
||||
# nothing to do, the alert will be displayed by the alert manager
|
||||
return
|
||||
elif cooking_state and cooking_state.state == CookingStates.DONE:
|
||||
self._message("Done !", False)
|
||||
else: # Progress bar
|
||||
elif microwave_state and microwave_state == MicrowaveState.ANALYZING:
|
||||
self.display.blit(fb_image_camera_bits, 56, 24)
|
||||
self._secondary_message("Analyzing...", False)
|
||||
elif microwave_state and microwave_state == MicrowaveState.WAITING_FOR_CLOUD:
|
||||
self.display.blit(fb_image_cloud_sync_bits, 55, 24)
|
||||
self._secondary_message("Receiving...", False)
|
||||
elif microwave_state and microwave_state == MicrowaveState.ALERT:
|
||||
# nothing to do, the alert will be displayed by the alert manager
|
||||
pass
|
||||
elif cooking_state: # Progress bar
|
||||
elapsed_time = cooking_state.get_elapsed_time()
|
||||
estimated_progress = elapsed_time / (elapsed_time + cooking_state.estimated_remaining_time)
|
||||
self._progressBar(estimated_progress, 21, 25)
|
||||
|
||||
# Estimated remaining time
|
||||
if cooking_state.paused:
|
||||
if cooking_state and cooking_state.paused:
|
||||
self.h_centered_text("Paused", 40, 1)
|
||||
elif cooking_state.state != CookingStates.DONE:
|
||||
elif cooking_state and cooking_state.state != CookingStates.DONE:
|
||||
remaining_time = int(cooking_state.estimated_remaining_time)
|
||||
minutes = remaining_time // 60
|
||||
seconds = remaining_time % 60
|
||||
self.h_centered_text(f"{minutes:02}:{seconds:02}", 40, 1)
|
||||
|
||||
# Current dish temperature
|
||||
if cooking_state.current_dish_temp is not None and cooking_state.current_dish_temp is not 0.0:
|
||||
if cooking_state and cooking_state.current_dish_temp is not None and cooking_state.current_dish_temp is not 0.0:
|
||||
self.display.blit(fb_image_weather_temperature_bits, 27, 2)
|
||||
self.display.text(str(int(cooking_state.current_dish_temp)), 37, 6, 1)
|
||||
self.display.ellipse(54, 6, 1, 1, 1, False)
|
||||
self.display.text("C", 56, 6, 1)
|
||||
|
||||
# Power level
|
||||
if cooking_state.power_level is not None:
|
||||
if cooking_state and cooking_state.power_level is not None:
|
||||
self.display.blit(fb_image_music_sound_wave_bits, 74, 2)
|
||||
self.display.text(f"{cooking_state.power_level}W", 92, 6, 1)
|
||||
if defrost_mode:
|
||||
@@ -118,12 +133,18 @@ class MicrowaveScreen:
|
||||
self.show()
|
||||
pass
|
||||
|
||||
def _message(self, text, alert):
|
||||
self.display.fill_rect(0, 27, self.width, CHARACTER_HEIGHT + 4, 1)
|
||||
def _message_at(self, y, text, alert):
|
||||
self.display.fill_rect(0, y, self.width, CHARACTER_HEIGHT + 4, 1)
|
||||
if alert:
|
||||
self.display.blit(fb_image_Alert_bits, 10, 29)
|
||||
self.display.blit(fb_image_Alert_bits, self.width - 10, 29)
|
||||
self.h_centered_text(text, 29, 0)
|
||||
self.display.blit(fb_image_Alert_bits, 1, y+2)
|
||||
self.display.blit(fb_image_Alert_bits, self.width - 10, y+2)
|
||||
self.h_centered_text(text, y+2, 0)
|
||||
|
||||
def _message(self, text, alert):
|
||||
self._message_at(27, text, alert)
|
||||
|
||||
def _secondary_message(self, text, alert):
|
||||
self._message_at(40, text, alert)
|
||||
|
||||
def message(self, text, alert):
|
||||
# self.flick()
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
import gc
|
||||
import sys
|
||||
import time
|
||||
import _thread
|
||||
from lib.microwaveScreen import MicrowaveScreen
|
||||
import uasyncio as asyncio
|
||||
from machine import Pin, SoftI2C
|
||||
import ssd1306
|
||||
@@ -18,6 +16,9 @@ from shared.sensors import RGBLED
|
||||
from shared.logging import log
|
||||
from shared.lora_device import LoraCommands
|
||||
from shared.alerts import Alert, AlertType, AlertManager
|
||||
from shared.microwave_state import MicrowaveState
|
||||
from shared.payloads import lora_new_alert
|
||||
from lib.microwaveScreen import MicrowaveScreen
|
||||
|
||||
# --- READ DEVICE ID ---
|
||||
try:
|
||||
@@ -29,6 +30,7 @@ except Exception:
|
||||
# --- GLOBAL VARIABLES ---
|
||||
cooking_state = None
|
||||
cooking_start_time = None # Track start timestamp
|
||||
microwave_state: str = None
|
||||
data_queue = SafeQueue()
|
||||
lora = None
|
||||
uart_device = None
|
||||
@@ -75,7 +77,7 @@ def send_cooking_update(state=None, start_time=None, estimated_remaining_time=No
|
||||
def on_new_alert(alert: Alert):
|
||||
global microwave_screen
|
||||
print(f"[Alert Manager] New alert received: {alert.to_dict()}")
|
||||
microwave_screen.message(alert.message, True)
|
||||
microwave_screen.message(alert.small_message if alert.small_message else alert.message, True)
|
||||
|
||||
def init_hardware():
|
||||
"""Initializes all hardware components."""
|
||||
@@ -110,10 +112,9 @@ def init_hardware():
|
||||
|
||||
print(f"[Main] ESP32 initialized with ID: '{DEVICE_ID}' (Type: {deviceTypes.DEVICE_TYPES['MICROWAVE']})")
|
||||
|
||||
|
||||
# --- DEDICATED LORA HARDWARE THREAD ---
|
||||
def lora_hardware_thread():
|
||||
"""Runs in a separate OS thread to keep the LoRa radio in continuous RX mode."""
|
||||
# --- ASYNC LORA TASK (REPLACES _THREAD) ---
|
||||
async def lora_rx_and_heartbeat_task():
|
||||
"""Replaces the hardware OS thread with a non-blocking async task to avoid SPI collisions."""
|
||||
last_heartbeat_time = 0
|
||||
|
||||
while True:
|
||||
@@ -122,19 +123,22 @@ def lora_hardware_thread():
|
||||
# 1. Send periodic heartbeat
|
||||
if now - last_heartbeat_time >= config.LORA_HEARTBEAT_INTERVAL:
|
||||
last_heartbeat_time = now
|
||||
log("\n[LoRa Thread] Sending Heartbeat...")
|
||||
log("\n[LoRa Task] Sending Heartbeat...")
|
||||
if lora:
|
||||
lora.send(PING_PAYLOAD)
|
||||
# CRITICAL: Force the radio chip out of Standby mode and back into RX mode
|
||||
if hasattr(lora, 'receive'):
|
||||
lora.receive()
|
||||
|
||||
# 2. Blocking 300ms RX listen window (keeps radio actively listening)
|
||||
# 2. Listen for incoming packets (Must be longer than LoRa Time-on-Air)
|
||||
if lora:
|
||||
paquet = lora.receive_reliable(timeout_ms=300)
|
||||
paquet = lora.receive_reliable(timeout_ms=500)
|
||||
if paquet is not None:
|
||||
log(f"[LoRa Thread] New Packet Received: {paquet}")
|
||||
log(f"[LoRa Task] New Packet Received: {paquet}")
|
||||
data_queue.put(paquet)
|
||||
|
||||
time.sleep_ms(10)
|
||||
|
||||
# Give control back to event loop
|
||||
await asyncio.sleep_ms(10)
|
||||
|
||||
# --- COOKING STATE CALLBACKS ---
|
||||
def cooking_state_temperature_provider():
|
||||
@@ -166,6 +170,21 @@ def cooking_state_temperature_provider():
|
||||
temps = [float(current_temp[0]), float(current_temp[1])]
|
||||
last_temp = [temps[0], temps[1]]
|
||||
current_temp = [None, None]
|
||||
|
||||
if config.DEBUG_TEMPERATURE_ALERT or temps[0] > config.MAX_ALLOWED_TEMPERATURE_COOKING_COMPARTMENT or temps[1] > config.MAX_ALLOWED_TEMPERATURE_TECHNICAL_COMPARTMENT:
|
||||
print(f"[CookingState] ALERT: Unsafe temperature detected! Dish: {temps[0]}°C, Ambient: {temps[1]}°C")
|
||||
# Send alert to orchestrator via LoRa
|
||||
alert = Alert(
|
||||
AlertType.TEMPERATURE_ALERT,
|
||||
f"Unsafe temperature detected! Dish: {temps[0]}/{config.MAX_ALLOWED_TEMPERATURE_COOKING_COMPARTMENT}°C, Ambient: {temps[1]}/{config.MAX_ALLOWED_TEMPERATURE_TECHNICAL_COMPARTMENT}°C",
|
||||
small_message=f"Temp too high"
|
||||
)
|
||||
alert_manager.add_alert(alert)
|
||||
if lora:
|
||||
lora.send_reliable(lora_new_alert(alert, with_message=True), max_retries=5)
|
||||
cooking_state.set_state(cookingState.CookingStates.ALERT)
|
||||
cooking_state.pause()
|
||||
|
||||
return temps
|
||||
|
||||
# 4. Fallback: Use last valid reading
|
||||
@@ -179,7 +198,7 @@ def cooking_state_on_state_change(state):
|
||||
global cooking_start_time
|
||||
print(f"[CookingState] State changed to: {state.state}")
|
||||
|
||||
if state.paused or state.state == cookingState.CookingStates.DONE or state.state == cookingState.CookingStates.IDLE:
|
||||
if state.paused or state.state in (cookingState.CookingStates.DONE, cookingState.CookingStates.IDLE, cookingState.CookingStates.ALERT):
|
||||
magnetron_led.off()
|
||||
else:
|
||||
magnetron_led.on()
|
||||
@@ -196,12 +215,11 @@ def cooking_state_on_state_change(state):
|
||||
paused=state.paused
|
||||
)
|
||||
|
||||
microwave_screen.update(cooking_state, defrost_mode)
|
||||
update_screen()
|
||||
|
||||
def cooking_state_on_refresh(state):
|
||||
# Update OLED display
|
||||
if microwave_screen:
|
||||
microwave_screen.update(state, defrost_mode)
|
||||
update_screen()
|
||||
|
||||
def cooking_state_on_pause(state):
|
||||
# If the cooking is unpaused and was in STIRRING_REQUIRED or ALERT state, we set the state back to COOKING.
|
||||
@@ -215,12 +233,19 @@ def cooking_state_on_pause(state):
|
||||
estimated_remaining_time=state.get_remaining_time()
|
||||
)
|
||||
|
||||
# --- SCREEN UPDATE ---
|
||||
def update_screen():
|
||||
global microwave_screen, cooking_state, defrost_mode, microwave_state
|
||||
|
||||
if microwave_screen:
|
||||
microwave_screen.update(cooking_state, defrost_mode, microwave_state)
|
||||
|
||||
|
||||
# --- ASYNC TASKS ---
|
||||
|
||||
async def uart_polling_task():
|
||||
"""Polls UART for incoming messages from the WiFi board."""
|
||||
global cooking_state, cooking_start_time, temperature_asked
|
||||
global cooking_state, cooking_start_time, temperature_asked, microwave_state
|
||||
|
||||
while True:
|
||||
if uart_device and uart_device.any():
|
||||
@@ -248,6 +273,7 @@ async def uart_polling_task():
|
||||
|
||||
await asyncio.sleep_ms(200)
|
||||
cooking_state_on_state_change(cooking_state)
|
||||
microwave_state = MicrowaveState.COOKING
|
||||
elif command.command_type == UARTCommandType.TEMPERATURE_RESPONSE:
|
||||
try:
|
||||
# Check if payload is already a dict or needs JSON decoding
|
||||
@@ -266,7 +292,7 @@ async def uart_polling_task():
|
||||
|
||||
async def lora_process_task():
|
||||
"""Consumes packets pushed to data_queue by the LoRa hardware thread."""
|
||||
global cooking_state, defrost_mode, microwave_screen
|
||||
global cooking_state, defrost_mode, microwave_screen, microwave_state
|
||||
|
||||
while True:
|
||||
while not data_queue.empty():
|
||||
@@ -274,32 +300,51 @@ async def lora_process_task():
|
||||
if paquet and not paquet.get("raw"):
|
||||
data = paquet.get("data", {})
|
||||
|
||||
# RECIPIENT FILTERING: Drop packets not addressed to this ESP32 or ALL
|
||||
target = data.get("target_id") or data.get("recipient")
|
||||
if target and target not in [DEVICE_ID, "ALL", "BROADCAST"]:
|
||||
log(f"[LoRa Process] Ignoring packet intended for {target}")
|
||||
continue
|
||||
|
||||
if "action" in data:
|
||||
if data["action"] == LoraCommands.TOGGLE_PAUSE:
|
||||
action = data["action"]
|
||||
if action == LoraCommands.TOGGLE_PAUSE:
|
||||
if cooking_state is not None:
|
||||
if cooking_state.state == cookingState.CookingStates.DONE:
|
||||
print("[LoRa Process] Cooking is done. Resetting microwave for the next session.")
|
||||
print("[LoRa Process] Cooking is done. Resetting microwave for next session.")
|
||||
cooking_state.set_state(cookingState.CookingStates.IDLE)
|
||||
await asyncio.sleep_ms(20)
|
||||
cooking_state = None
|
||||
else:
|
||||
cooking_state.toggle_pause()
|
||||
if cooking_state.paused:
|
||||
print("[LoRa Process] Cooking paused via orchestrator command.")
|
||||
else:
|
||||
print("[LoRa Process] Cooking resumed via orchestrator command.")
|
||||
print(f"[LoRa Process] Cooking paused state toggled to {cooking_state.paused}")
|
||||
else:
|
||||
log("[LoRa Process] No active cooking state to toggle pause/resume.")
|
||||
elif data["action"] == LoraCommands.TOGGLE_DEFROST:
|
||||
|
||||
elif action == LoraCommands.TOGGLE_DEFROST:
|
||||
print("[LoRa Process] Toggling defrost mode via orchestrator command.")
|
||||
defrost_mode = data["defrost_state"]
|
||||
microwave_screen.update(cooking_state, defrost_mode)
|
||||
elif data["action"] == LoraCommands.NEW_ALERT:
|
||||
alert = Alert(data.get("alert_type"), data.get("message", "Unsafe area"))
|
||||
defrost_mode = data.get("defrost_state", False)
|
||||
update_screen()
|
||||
|
||||
elif action == LoraCommands.NEW_ALERT:
|
||||
alert: Alert | None = None
|
||||
if data.get("alert_type") == AlertType.TEMPERATURE_ALERT:
|
||||
alert = Alert(data.get("alert_type"), data.get("alert_message", "Temp too high"), redistributed=True)
|
||||
elif data.get("alert_type") == AlertType.COOKING_SAFETY:
|
||||
alert = Alert(data.get("alert_type"), data.get("alert_message", "Unsafe area"), redistributed=True)
|
||||
|
||||
if alert:
|
||||
alert.timestamp = data.get("timestamp", time.time())
|
||||
print(f"[LoRa Process] New alert received via orchestrator: {alert.to_dict()}")
|
||||
alert_manager.add_alert(alert)
|
||||
|
||||
elif action == LoraCommands.MICROVAVE_STATE_UPDATE:
|
||||
new_state = data.get("new_microwave_state")
|
||||
if new_state:
|
||||
print(f"[LoRa Process] Microwave state update received: {new_state}")
|
||||
microwave_state = new_state
|
||||
if new_state not in (MicrowaveState.ALERT): # Not alert so we can show the error
|
||||
update_screen()
|
||||
|
||||
await asyncio.sleep_ms(100)
|
||||
|
||||
|
||||
@@ -334,7 +379,7 @@ async def memory_cleanup_task():
|
||||
|
||||
# --- BOOTSTRAP ---
|
||||
async def main():
|
||||
global cooking_state, defrost_mode, microwave_screen, alert_manager
|
||||
global alert_manager
|
||||
print("[Main] Starting application...")
|
||||
|
||||
init_hardware()
|
||||
@@ -342,15 +387,8 @@ async def main():
|
||||
alert_manager = AlertManager()
|
||||
alert_manager.set_on_alert_callback(on_new_alert)
|
||||
|
||||
# Launch dedicated hardware thread for LoRa RX
|
||||
try:
|
||||
_thread.stack_size(16 * 1024)
|
||||
except Exception:
|
||||
pass
|
||||
_thread.start_new_thread(lora_hardware_thread, ())
|
||||
print("[Main] LoRa hardware background thread started.")
|
||||
|
||||
# Launch background async tasks
|
||||
# Launch all tasks within the same single-threaded uasyncio event loop
|
||||
asyncio.create_task(lora_rx_and_heartbeat_task())
|
||||
asyncio.create_task(uart_polling_task())
|
||||
asyncio.create_task(lora_process_task())
|
||||
asyncio.create_task(cooking_loop_task())
|
||||
@@ -358,8 +396,7 @@ async def main():
|
||||
|
||||
print("[Main] All async tasks running concurrently!")
|
||||
|
||||
microwave_screen.update(None, defrost_mode)
|
||||
|
||||
update_screen()
|
||||
# Keep main task alive indefinitely
|
||||
while True:
|
||||
await asyncio.sleep(3600)
|
||||
|
||||
+47
-11
@@ -4,7 +4,7 @@ import time
|
||||
import asyncio
|
||||
import requests
|
||||
|
||||
from orchestrateur.microwave_state import MicrowaveState
|
||||
from shared.microwave_state import MicrowaveState, MicrowaveStateFields
|
||||
from orchestrateur.sensors import gps
|
||||
from shared import get_lora, get_mqtt_client, deviceTypes, config, payloads, db
|
||||
from shared.logging import log
|
||||
@@ -81,6 +81,15 @@ def notify_display_update():
|
||||
except RuntimeError:
|
||||
pass
|
||||
|
||||
def on_microwave_change(state: MicrowaveState, field: MicrowaveStateFields):
|
||||
if field != MicrowaveStateFields.STATE: # No external screen or lcd uses this field, so we can skip updates for it
|
||||
notify_display_update()
|
||||
|
||||
if field == MicrowaveStateFields.STATE and state.state in (MicrowaveState.DONE, MicrowaveState.ANALYZING, MicrowaveState.WAITING_FOR_CLOUD, MicrowaveState.ALERT):
|
||||
# Send to LoRa device if state changed
|
||||
lora.send_reliable(payloads.lora_microwave_state(state.state), max_retries=5)
|
||||
|
||||
|
||||
def set_cloud_alert(state: bool):
|
||||
"""Setter for cloud_alert that triggers a display update when changed."""
|
||||
global cloud_alert
|
||||
@@ -91,7 +100,7 @@ def set_cloud_alert(state: bool):
|
||||
update_lcd_cloud_alert()
|
||||
|
||||
# Global state trackers
|
||||
microwave_states = {"2": MicrowaveState("2", on_change_callback=notify_display_update)}
|
||||
microwave_states = {"2": MicrowaveState("2", on_change_callback=on_microwave_change)}
|
||||
button_state = False
|
||||
cloud_alert = None # Global status flag for screen / UI display
|
||||
async_event_queue = None
|
||||
@@ -257,13 +266,13 @@ async def display_broadcast_worker_task():
|
||||
def button_callback():
|
||||
"""Button physical interrupt callback."""
|
||||
global button_state
|
||||
if microwave_states.get("2").cooking_state == CookingStates.COOKING or microwave_states.get("2").cooking_state == CookingStates.DONE or microwave_states.get("2").cooking_state == CookingStates.STIRRING_REQUIRED:
|
||||
if microwave_states.get("2").cooking_state in (CookingStates.COOKING, CookingStates.DONE, CookingStates.STIRRING_REQUIRED, CookingStates.ALERT):
|
||||
print("[Button] Toggling pause/resume for microwave '2'.")
|
||||
lora.send_reliable({"id": DEVICE_ID, "microwave_id": "2", "action": LoraCommands.TOGGLE_PAUSE})
|
||||
lora.send_reliable({"id": DEVICE_ID, "microwave_id": "2", "action": LoraCommands.TOGGLE_PAUSE}, max_retries=6)
|
||||
else:
|
||||
button_state = not button_state
|
||||
print(f"[Button] Defrost state toggled to: {button_state}")
|
||||
lora.send_reliable({"id": DEVICE_ID, "microwave_id": "2", "action": LoraCommands.TOGGLE_DEFROST, "defrost_state": button_state})
|
||||
lora.send_reliable({"id": DEVICE_ID, "microwave_id": "2", "action": LoraCommands.TOGGLE_DEFROST, "defrost_state": button_state}, max_retries=5)
|
||||
|
||||
button.set_callback(button_callback)
|
||||
button.start_button_monitoring_thread()
|
||||
@@ -271,7 +280,7 @@ button.start_button_monitoring_thread()
|
||||
# --- Alert manager ---
|
||||
alert_manager = None
|
||||
|
||||
def on_new_alert(alert):
|
||||
def on_new_alert(alert: Alert):
|
||||
# Sends to cloud server
|
||||
alert_dict = alert.to_dict()
|
||||
alert_dict["orchestrator_id"] = DEVICE_ID
|
||||
@@ -285,9 +294,11 @@ def on_new_alert(alert):
|
||||
res_json = response.json()
|
||||
print(f"[Alert Handling] Alert sent to cloud: {alert_dict}, Response: {res_json}")
|
||||
|
||||
if not alert.redistributed: # If not redistributed from microwaves
|
||||
# Send the alert to the lora device
|
||||
lora.send_reliable(payloads.lora_new_alert(alert))
|
||||
|
||||
payload = payloads.lora_new_alert(alert)
|
||||
print(f"[Alert Handling] Sending alert to LoRa device: {payload}")
|
||||
if lora.send_reliable(payload):
|
||||
microwave_states["2"].set_cooking_state(CookingStates.ALERT)
|
||||
|
||||
# --- HARDWARE CONTROLLERS ---
|
||||
@@ -311,6 +322,14 @@ def read_local_sensors(microwave_id, initial_dish_height):
|
||||
if temp is not None:
|
||||
sensor_data["temperature"] = temp
|
||||
sensor_data["humidity"] = hum
|
||||
if config.DEBUG_TEMPERATURE_ALERT or temp > config.MAX_ALLOWED_TEMPERATURE_TECHNICAL_COMPARTMENT:
|
||||
print(f"[{microwave_id}] ALERT: Unsafe temperature in technical compartment detected! Temp: {temp}°C, Humidity: {hum}%")
|
||||
alert = Alert(
|
||||
AlertType.TEMPERATURE_ALERT,
|
||||
f"Unsafe temperature in technical compartment detected! Temp: {temp}/{config.MAX_ALLOWED_TEMPERATURE_COOKING_COMPARTMENT}°C, Humidity: {hum}%"
|
||||
)
|
||||
lora.send_reliable(payloads.lora_new_alert(alert), max_retries=5)
|
||||
return None # Abort further processing if unsafe temperature detected
|
||||
except Exception as e:
|
||||
log(f"[{microwave_id}] DHT read warning: {e}")
|
||||
|
||||
@@ -346,6 +365,11 @@ async def handle_new_dish(microwave_id, detected_height):
|
||||
# 4. Wait for local sensors to finish reading
|
||||
sensors_data = await sensor_task
|
||||
|
||||
if sensors_data is None:
|
||||
print(f"[{microwave_id}] Aborting cooking plan because of empty sensor data")
|
||||
microwave_states[microwave_id].set_state(MicrowaveState.ALERT)
|
||||
return
|
||||
|
||||
# Check if dish was removed while reading sensors
|
||||
if microwave_states.get(microwave_id).state != MicrowaveState.ANALYZING:
|
||||
print(f"[{microwave_id}] Dish removed during sensor read. Aborting.")
|
||||
@@ -434,7 +458,7 @@ async def request_cloud_cooking_plan(microwave_id, sensors_data):
|
||||
|
||||
if c_time is None or c_power is None or c_temp is None:
|
||||
print(f"[{microwave_id}] Invalid plan received: {res_json}")
|
||||
microwave_states[microwave_id].set_state(MicrowaveState.IDLE)
|
||||
microwave_states[microwave_id].set_state(MicrowaveState.DONE)
|
||||
return
|
||||
|
||||
print(f"[{microwave_id}] Cloud Plan Received! Starting microwave: {c_time}s @ {c_power}W")
|
||||
@@ -501,6 +525,9 @@ async def process_messages_task():
|
||||
microwave_states[mw_id].set_state(MicrowaveState.DONE)
|
||||
print(f"[{mw_id}] Cooking finished. Waiting for user to remove dish.")
|
||||
if "action" in data.get("data", {}):
|
||||
if type(data["data"]) != dict:
|
||||
print(f"[LoRa] Invalid data format received: {data['data']}")
|
||||
continue
|
||||
action = data["data"]["action"]
|
||||
if action == LoraCommands.COOKING_UPDATE:
|
||||
mw_id = data["data"].get("id")
|
||||
@@ -509,6 +536,12 @@ async def process_messages_task():
|
||||
microwave_states[mw_id].set_cooking_state(state_info.get("cooking_state", microwave_states[mw_id].cooking_state))
|
||||
microwave_states[mw_id].set_cooking_estimated_remaining_time(state_info.get("estimated_remaining_time", microwave_states[mw_id].cooking_estimated_remaining_time))
|
||||
microwave_states[mw_id].set_paused(state_info.get("paused", microwave_states[mw_id].paused))
|
||||
elif action == LoraCommands.NEW_ALERT:
|
||||
alert_type = data["data"].get("alert_type")
|
||||
alert_message = data["data"].get("alert_message")
|
||||
alert = Alert(alert_type, alert_message, redistributed=True)
|
||||
alert_manager.add_alert(alert)
|
||||
print(f"[LoRa] New alert received: {alert.to_dict()}")
|
||||
else:
|
||||
print(f"[LoRa] Unhandled action received: {action} with data: {data['data']}")
|
||||
elif source == "MQTT":
|
||||
@@ -530,7 +563,7 @@ async def process_messages_task():
|
||||
# Pass change callback to newly connected microwave
|
||||
microwave_states[component_id] = MicrowaveState(
|
||||
component_id,
|
||||
on_change_callback=notify_display_update
|
||||
on_change_callback=on_microwave_change
|
||||
)
|
||||
notify_display_update() # Update the external screens
|
||||
update_lcd_microwave_count() # Update the LCD with new microwave count
|
||||
@@ -641,7 +674,10 @@ async def monitor_dish_height_task():
|
||||
|
||||
while True:
|
||||
dist = await get_filtered_dish_height()
|
||||
current_state = microwave_states.get(mw_id, MicrowaveState.IDLE).state
|
||||
try:
|
||||
current_state = microwave_states.get(mw_id).state
|
||||
except AttributeError:
|
||||
current_state = MicrowaveState.IDLE
|
||||
|
||||
if dist is not None:
|
||||
# Hysteresis Thresholds:
|
||||
|
||||
@@ -7,6 +7,7 @@ import shared.payloads as payloads
|
||||
import shared.cookingState as cookingState
|
||||
import shared.safeQueue as safeQueue
|
||||
import shared.alerts as alerts
|
||||
import shared.microwave_state as microwave_state
|
||||
try:
|
||||
import shared.lora_device as lora_device
|
||||
except (ImportError, SyntaxError):
|
||||
|
||||
+4
-1
@@ -20,10 +20,12 @@ class AlertManager:
|
||||
self.alerts.clear()
|
||||
|
||||
class Alert:
|
||||
def __init__(self, alertType: "AlertType", message: str):
|
||||
def __init__(self, alertType: "AlertType", message: str, redistributed: bool = False, small_message: str = None):
|
||||
self.alertType = alertType
|
||||
self.message = message
|
||||
self.small_message = small_message
|
||||
self.timestamp = time.time()
|
||||
self.redistributed = redistributed
|
||||
|
||||
def to_dict(self):
|
||||
return {
|
||||
@@ -45,3 +47,4 @@ class Alert:
|
||||
|
||||
class AlertType:
|
||||
COOKING_SAFETY = "COOKING_SAFETY"
|
||||
TEMPERATURE_ALERT = "TEMPERATURE_ALERT"
|
||||
+3
-1
@@ -1,6 +1,7 @@
|
||||
# Debugging and others
|
||||
DEBUG=True
|
||||
DEBUG_DANGEROUS_AREA=False
|
||||
DEBUG_TEMPERATURE_ALERT=True
|
||||
|
||||
# LoRa
|
||||
LORA_HEARTBEAT_INTERVAL = 30
|
||||
@@ -19,8 +20,9 @@ MQTT_HELLO_INTERVAL = 30
|
||||
|
||||
# Microwave Model
|
||||
COOKING_COMPARTMENT_HEIGHT = 30 # cm
|
||||
|
||||
BUZZER_ACTIVATED = False
|
||||
MAX_ALLOWED_TEMPERATURE_TECHNICAL_COMPARTMENT = 70
|
||||
MAX_ALLOWED_TEMPERATURE_COOKING_COMPARTMENT = 200
|
||||
|
||||
# TELEMETRY
|
||||
TELEMETRY_SEND_INTERVAL = 3
|
||||
+29
-9
@@ -28,6 +28,12 @@ class BaseLoraDevice:
|
||||
self.pending_rx_queue = []
|
||||
self.default_group = 2
|
||||
|
||||
# NEW: Global TX lock to prevent concurrent overlapping transmissions
|
||||
if IS_MICROPYTHON:
|
||||
self.tx_lock = _thread.allocate_lock()
|
||||
else:
|
||||
self.tx_lock = threading.Lock()
|
||||
|
||||
def _generate_msg_id(self):
|
||||
return random.getrandbits(16)
|
||||
|
||||
@@ -77,6 +83,8 @@ class BaseLoraDevice:
|
||||
|
||||
def send_reliable(self, payload, max_retries=4, ack_timeout=3.0):
|
||||
"""Sends a payload and listens in a single continuous RX window for the ACK."""
|
||||
|
||||
with self.tx_lock:
|
||||
lock = getattr(self, 'lock', None)
|
||||
|
||||
if isinstance(payload, dict):
|
||||
@@ -93,12 +101,9 @@ class BaseLoraDevice:
|
||||
log(f"[ReliableLoRa] Attempt {attempt + 1}/{max_retries} transmitting msg_id {msg_id}")
|
||||
self.send(payload)
|
||||
|
||||
# 1. Open a single continuous RX window for the full timeout duration
|
||||
# (Defaulted to 3.0s to account for LA66 UART + transmission time)
|
||||
timeout_ms = int(ack_timeout * 1000)
|
||||
packet = self.receive_packet(timeout_ms=timeout_ms)
|
||||
|
||||
# 2. Process incoming packet if received
|
||||
if packet:
|
||||
if lock: lock.acquire()
|
||||
try:
|
||||
@@ -108,7 +113,6 @@ class BaseLoraDevice:
|
||||
finally:
|
||||
if lock: lock.release()
|
||||
|
||||
# 3. Check if matching ACK was received
|
||||
if lock: lock.acquire()
|
||||
try:
|
||||
if msg_id in self.received_acks:
|
||||
@@ -296,19 +300,28 @@ else:
|
||||
self.ser.reset_output_buffer()
|
||||
self.lock = threading.Lock()
|
||||
|
||||
# Initial configuration
|
||||
self._emergency_rx_buffer = []
|
||||
|
||||
self.configure(freq=868.1, sf=7, bw=125)
|
||||
|
||||
def _send_at_cmd(self, cmd, timeout=1.5):
|
||||
"""Sends AT command and reads response until line received or timeout."""
|
||||
"""Sends AT command and safely handles async incoming packets."""
|
||||
self.ser.write(f"{cmd}\r\n".encode('utf-8'))
|
||||
|
||||
start = time.time()
|
||||
resp = ""
|
||||
while (time.time() - start) < timeout:
|
||||
if self.ser.in_waiting > 0:
|
||||
line = self.ser.readline().decode('utf-8', errors='ignore')
|
||||
resp += line
|
||||
line = self.ser.readline().decode('utf-8', errors='ignore').strip()
|
||||
|
||||
if not line:
|
||||
continue
|
||||
|
||||
if any(marker in line for marker in ["+RECV:", "+RCV=", "+DRX:", "(HEX:)", "Data:"]):
|
||||
self._emergency_rx_buffer.append(line)
|
||||
continue
|
||||
|
||||
resp += line + "\n"
|
||||
if "OK" in line or "ERROR" in line or "AT_BUSY" in line:
|
||||
break
|
||||
time.sleep(0.02)
|
||||
@@ -364,8 +377,14 @@ else:
|
||||
timeout_s = timeout_ms / 1000.0
|
||||
|
||||
while (time.time() - start_time) < timeout_s:
|
||||
if self.ser.in_waiting > 0:
|
||||
line = ""
|
||||
|
||||
# NEW: Process emergency buffer first before checking serial
|
||||
if self._emergency_rx_buffer:
|
||||
line = self._emergency_rx_buffer.pop(0)
|
||||
elif self.ser.in_waiting > 0:
|
||||
line = self.ser.readline().decode('utf-8', errors='ignore').strip()
|
||||
|
||||
if line:
|
||||
payload_bytes = None
|
||||
|
||||
@@ -438,6 +457,7 @@ def get_lora_device(port_or_pins=None):
|
||||
|
||||
class LoraCommands:
|
||||
PING = "ping"
|
||||
MICROVAVE_STATE_UPDATE = "microwave_state_update"
|
||||
COOKING_STATE_UPDATE = "cooking_state_update"
|
||||
COOKING_UPDATE = "cooking_update"
|
||||
TOGGLE_PAUSE = "toggle_pause"
|
||||
|
||||
@@ -1,6 +1,13 @@
|
||||
from shared.cookingState import CookingStates
|
||||
import shared.config as config
|
||||
|
||||
class MicrowaveStateFields:
|
||||
STATE = "state"
|
||||
PAUSED = "paused"
|
||||
COOKING_STATE = "cooking_state"
|
||||
COOKING_ESTIMATED_REMAINING_TIME = "cooking_estimated_remaining_time"
|
||||
COOKING_START_TIME = "cooking_start_time"
|
||||
|
||||
class MicrowaveState:
|
||||
state = None
|
||||
paused = False
|
||||
@@ -14,11 +21,11 @@ class MicrowaveState:
|
||||
self.cooking_state = CookingStates.IDLE
|
||||
self.on_change_callback = on_change_callback
|
||||
|
||||
def _notify_change(self):
|
||||
def _notify_change(self, field: MicrowaveStateFields = None):
|
||||
"""Invokes callback if registered on state attribute changes."""
|
||||
if self.on_change_callback:
|
||||
try:
|
||||
self.on_change_callback()
|
||||
self.on_change_callback(self, field)
|
||||
except Exception as e:
|
||||
print(f"[MicrowaveState] Error in change callback: {e}")
|
||||
|
||||
@@ -29,21 +36,21 @@ class MicrowaveState:
|
||||
MicrowaveState.ANALYZING,
|
||||
MicrowaveState.WAITING_FOR_CLOUD,
|
||||
MicrowaveState.COOKING,
|
||||
MicrowaveState.DONE
|
||||
MicrowaveState.DONE,
|
||||
MicrowaveState.ALERT,
|
||||
), f"Invalid state: {new_state}"
|
||||
|
||||
if self.state != new_state:
|
||||
self.state = new_state
|
||||
# self._notify_change()
|
||||
self._notify_change(MicrowaveStateFields.STATE)
|
||||
|
||||
def set_paused(self, is_paused):
|
||||
if self.paused != is_paused:
|
||||
self.paused = is_paused
|
||||
self._notify_change()
|
||||
self._notify_change(MicrowaveStateFields.PAUSED)
|
||||
|
||||
def toggle_pause(self):
|
||||
self.paused = not self.paused
|
||||
self._notify_change()
|
||||
self.set_paused(not self.paused)
|
||||
|
||||
def set_cooking_state(self, new_cooking_state):
|
||||
if config.DEBUG:
|
||||
@@ -56,18 +63,20 @@ class MicrowaveState:
|
||||
), "Invalid cooking state: " + str(new_cooking_state)
|
||||
|
||||
if self.cooking_state != new_cooking_state:
|
||||
if self.cooking_state == CookingStates.COOKING and new_cooking_state == CookingStates.DONE:
|
||||
self.set_state(MicrowaveState.DONE)
|
||||
self.cooking_state = new_cooking_state
|
||||
self._notify_change()
|
||||
self._notify_change(MicrowaveStateFields.COOKING_STATE)
|
||||
|
||||
def set_cooking_estimated_remaining_time(self, time_seconds):
|
||||
if self.cooking_estimated_remaining_time != time_seconds:
|
||||
self.cooking_estimated_remaining_time = time_seconds
|
||||
self._notify_change()
|
||||
self._notify_change(MicrowaveStateFields.COOKING_ESTIMATED_REMAINING_TIME)
|
||||
|
||||
def set_cooking_start_time(self, start_time):
|
||||
if self.cooking_start_time != start_time:
|
||||
self.cooking_start_time = start_time
|
||||
self._notify_change()
|
||||
self._notify_change(MicrowaveStateFields.COOKING_START_TIME)
|
||||
|
||||
def to_dict(self):
|
||||
return {
|
||||
@@ -83,3 +92,4 @@ class MicrowaveState:
|
||||
WAITING_FOR_CLOUD = "WAITING_FOR_CLOUD" # Waiting for API parameters
|
||||
COOKING = "COOKING" # Microwave is active
|
||||
DONE = "DONE" # Finished/Stopped, waiting for dish removal
|
||||
ALERT = "ALERT" # Alert state, waiting for user action
|
||||
+19
-3
@@ -69,13 +69,29 @@ def telemetry_payload(device_id, microwave_states, button_state, cloud_alert, gp
|
||||
"logs": logs
|
||||
})
|
||||
|
||||
def lora_new_alert(alert: Alert):
|
||||
def lora_new_alert(alert: Alert, with_message=False):
|
||||
try:
|
||||
from shared.lora_device import LoraCommands
|
||||
except ImportError:
|
||||
pass # No need
|
||||
|
||||
payload = {
|
||||
"action": LoraCommands.NEW_ALERT,
|
||||
"alert_type": alert.alertType
|
||||
}
|
||||
|
||||
if with_message:
|
||||
payload["alert_message"] = alert.message
|
||||
|
||||
return payload
|
||||
|
||||
def lora_microwave_state(state: str):
|
||||
try:
|
||||
from shared.lora_device import LoraCommands
|
||||
except ImportError:
|
||||
pass # No need
|
||||
|
||||
return {
|
||||
"action": LoraCommands.NEW_ALERT,
|
||||
"alert_type": alert.alertType
|
||||
"action": LoraCommands.MICROVAVE_STATE_UPDATE,
|
||||
"new_microwave_state": state
|
||||
}
|
||||
Reference in New Issue
Block a user