Beginning of cooking cycle
Build, push image, and notify Watchtower / build-image (push) Successful in 1m21s
Build, push image, and notify Watchtower / notify (push) Successful in 17s

This commit is contained in:
2026-07-31 21:50:42 +02:00
parent 8ac5db22c1
commit 7299a50198
11 changed files with 552 additions and 86 deletions
+4 -1
View File
@@ -5,7 +5,10 @@ import shared.deviceTypes as deviceTypes
import shared.config as config
import shared.payloads as payloads
import shared.cookingState as cookingState
import shared.uart_comm as uart_comm
try:
import shared.uart_comm as uart_comm
except ImportError:
pass # No need as we are on the RPI
import shared.sensors
def get_lora(*args, **kwargs):
+199
View File
@@ -0,0 +1,199 @@
import time
class CookingState:
TEMPERATURE_TOLERANCE = 1.0
def __init__(self, cook_time: int, power_level: int, target_temp: float, temperature_provider=None, on_state_change=None, on_refresh=None):
self.cook_time = cook_time
self.power_level = power_level
self.target_temp = target_temp
self.start_time = time.time()
self.temperature_provider = temperature_provider
self.on_state_change = on_state_change
self.on_refresh = on_refresh
self.state = CookingStates.COOKING
self.paused = False
self._pause_started_at = None
self._paused_duration = 0.0
self.current_dish_temp = None
self.current_ambient_temp = None
self.estimated_remaining_time = float(cook_time)
self._last_temperature_sample = None
self._last_refresh_signature = None
def set_temperature_provider(self, temperature_provider):
self.temperature_provider = temperature_provider
def set_state_change_callback(self, callback):
self.on_state_change = callback
def set_refresh_callback(self, callback):
self.on_refresh = callback
def pause(self):
if self.paused:
return
self.paused = True
self._pause_started_at = time.time()
self._notify_refresh(force=True)
def unpause(self):
if not self.paused:
return
now = time.time()
if self._pause_started_at is not None:
self._paused_duration += now - self._pause_started_at
self._pause_started_at = None
self.paused = False
self._notify_refresh(force=True)
def toggle_pause(self):
if self.paused:
self.unpause()
else:
self.pause()
def set_state(self, state):
if self.state == state:
return
self.state = state
self._notify_state_change()
self._notify_refresh(force=True)
def get_elapsed_time(self) -> float:
now = time.time()
elapsed = now - self.start_time - self._paused_duration
if self.paused and self._pause_started_at is not None:
elapsed -= now - self._pause_started_at
return max(0.0, elapsed)
def get_remaining_time(self) -> int:
"""Returns the estimated remaining cooking time in seconds."""
return int(max(0.0, self.get_remaining_time_estimation()))
def get_remaining_time_estimation(self) -> float:
elapsed_time = self.get_elapsed_time()
timer_remaining = max(0.0, float(self.cook_time) - elapsed_time)
if self.current_dish_temp is None:
return timer_remaining
if self.current_dish_temp >= self.target_temp:
return timer_remaining
heating_rate = self._estimate_heating_rate()
if heating_rate <= 0:
return timer_remaining
target_remaining = (self.target_temp - self.current_dish_temp) / heating_rate
return max(timer_remaining, max(0.0, target_remaining))
def _read_temperatures(self):
if self.temperature_provider is None:
return None, None
temperatures = self.temperature_provider()
if temperatures is None:
return None, None
if isinstance(temperatures, (list, tuple)) and len(temperatures) >= 2:
return temperatures[0], temperatures[1]
raise ValueError("temperature_provider must return a pair: (dish_temp, ambient_temp)")
def _estimate_heating_rate(self):
if self._last_temperature_sample is None:
return 0.0
last_time, last_temp = self._last_temperature_sample
now = time.time()
current_temp = self.current_dish_temp
if current_temp is None:
return 0.0
delta_time = now - last_time
if delta_time <= 0:
return 0.0
return (current_temp - last_temp) / delta_time
def _notify_state_change(self):
if self.on_state_change is None:
return
self.on_state_change(self)
def _notify_refresh(self, force=False):
if self.on_refresh is None:
return
signature = (
int(self.get_elapsed_time()),
int(self.get_remaining_time_estimation()),
self.current_dish_temp,
self.current_ambient_temp,
self.state,
self.paused,
)
if not force and signature == self._last_refresh_signature:
return
self._last_refresh_signature = signature
self.on_refresh(self)
def update_tick(self):
if self.paused:
self._notify_refresh()
return self.state
previous_state = self.state
previous_temperature = self.current_dish_temp
try:
self.current_dish_temp, self.current_ambient_temp = self._read_temperatures()
except Exception:
self.current_dish_temp = previous_temperature
now = time.time()
elapsed_time = self.get_elapsed_time()
self.estimated_remaining_time = self.get_remaining_time_estimation()
if self.current_dish_temp is not None:
if elapsed_time < (self.cook_time / 2.0) and self.current_dish_temp >= self.target_temp:
self.state = CookingStates.STIRRING_REQUIRED
self.pause()
elif elapsed_time >= self.cook_time and self.current_dish_temp >= (self.target_temp - self.TEMPERATURE_TOLERANCE):
self.state = CookingStates.DONE
elif self.state == CookingStates.DONE and self.current_dish_temp < (self.target_temp - self.TEMPERATURE_TOLERANCE):
self.state = CookingStates.COOKING
elif elapsed_time >= self.cook_time * 1.25: # If the dish is not heating up
self.state = CookingStates.STIRRING_REQUIRED
self.pause()
self._last_temperature_sample = (now, self.current_dish_temp)
if self.state != previous_state:
self._notify_state_change()
self._notify_refresh()
return self.state
class CookingStates:
COOKING = 0
STIRRING_REQUIRED = 1
DONE = 2
ALERT = 3 # Microwave is too hot internally or other alerts
IDLE = 4 # Waiting for cooking parameters to be set, or after cooking is done
+8
View File
@@ -35,4 +35,12 @@ def mqtt_sensor_data(id_microwave, dish_temp, ambient_temp):
"id_microwave": id_microwave,
"dish_temp": dish_temp,
"ambient_temp": ambient_temp
})
def mqtt_cooking_config(id_microwave, cook_time, power_level, target_temp):
return as_json({
"id_microwave": id_microwave,
"cook_time": cook_time,
"power_level": power_level,
"target_temp": target_temp
})
+4 -1
View File
@@ -1 +1,4 @@
from shared.sensors.rgb_led import RGBLED
try:
from shared.sensors.rgb_led import RGBLED
except ImportError:
pass # No need as we are on the RPI
+50 -7
View File
@@ -1,27 +1,30 @@
from machine import Pin, PWM
from machine import Pin, PWM, Timer
import time
class RGBLED:
"""
MicroPython driver for 4-pin RGB LEDs on ESP32 / Heltec boards.
Supports state tracking, color setting, brightness scaling, and state toggling.
Supports state tracking, color setting, brightness scaling,
state toggling, and non-blocking blinking via machine.Timer.
"""
# Preset RGB tuples for quick use
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 150, 0)
YELLOW = (255, 120, 0)
WHITE_YELLOW = (150, 30, 0)
ORANGE = (255, 50, 0)
WHITE = (255, 255, 255)
OFF = (0, 0, 0)
def __init__(self, red_pin, green_pin, blue_pin, common_anode=False, freq=1000):
def __init__(self, red_pin, green_pin, blue_pin, common_anode=False, freq=1000, timer_id=1):
"""
:param red_pin: GPIO pin number for Red channel
:param green_pin: GPIO pin number for Green channel
:param blue_pin: GPIO pin number for Blue channel
:param common_anode: Set True if cathode is connected to 3.3V instead of GND
:param freq: PWM frequency in Hz (default 1000Hz)
:param timer_id: Hardware/software timer ID for non-blocking blinks (-1 uses soft timers on ESP32).
"""
self._r_pwm = PWM(Pin(red_pin, Pin.OUT), freq=freq)
self._g_pwm = PWM(Pin(green_pin, Pin.OUT), freq=freq)
@@ -34,6 +37,10 @@ class RGBLED:
self._brightness = 1.0 # Brightness factor [0.0 to 1.0]
self._is_on = True # Master power state
# Blink state variables
self._timer = Timer(timer_id)
self._is_blinking = False
self._apply()
def _apply(self):
@@ -88,7 +95,11 @@ class RGBLED:
"""Returns True if the LED is currently powered on."""
return self._is_on
# --- Helper Methods ---
@property
def is_blinking(self):
return self._is_blinking
# --- Basic Control Methods ---
def set_rgb(self, r, g, b):
"""Alternative setter for individual R, G, B integer values."""
@@ -109,8 +120,40 @@ class RGBLED:
self._is_on = not self._is_on
self._apply()
# --- Non-Blocking Blinking Methods ---
def _timer_callback(self, t):
"""Internal callback executed by machine.Timer."""
self.toggle()
def blink_on(self, interval_ms=500):
"""Starts background blinking at the specified interval in milliseconds."""
if self._is_blinking:
self._timer.deinit()
self._is_blinking = True
self.on() # Ensure initial state is on
self._timer.init(
period=interval_ms,
mode=Timer.PERIODIC,
callback=self._timer_callback
)
def blink_off(self):
"""Stops blinking and returns control to steady state."""
if self._is_blinking:
self._timer.deinit()
self._is_blinking = False
def blink_toggle(self, interval_ms=500):
"""Toggles blinking state (starts if stopped, stops if active)."""
if self._is_blinking:
self.blink_off()
else:
self.blink_on(interval_ms)
def deinit(self):
"""Releases the hardware PWM pins when finished."""
"""Releases the hardware PWM pins and timer when finished."""
self._r_pwm.deinit()
self._g_pwm.deinit()
self._b_pwm.deinit()
+121 -24
View File
@@ -1,12 +1,12 @@
# shared/uart_comm.py
import _thread
from machine import UART
import time
import ujson
class SafeUART:
def __init__(self, uart_id, tx_pin, rx_pin, baudrate=115200):
# Initialize the hardware UART channel
self.uart = UART(uart_id, baudrate=baudrate, tx=tx_pin, rx=rx_pin, timeout=10)
self.uart = UART(uart_id, baudrate=baudrate, tx=tx_pin, rx=rx_pin, timeout=10, rxbuf=1024)
# Core thread-safety assets
self.lock = _thread.allocate_lock()
@@ -21,37 +21,87 @@ class SafeUART:
print(f"[UART] Thread initialized on UART{uart_id} (TX:{tx_pin}, RX:{rx_pin})")
def _listener_worker(self):
"""Asynchronous internal loop parsing incoming stream lines into the queue."""
"""Worker loop that handles nested JSON structures by tracking brace depth."""
while True:
try:
messages_found = []
with self.lock:
if self.uart.any():
with self.lock:
# Pull all raw bytes waiting in the hardware ring buffer
chunk = self.uart.read(self.uart.any())
if chunk:
self.buffer += chunk
# Process complete lines terminated by a newline character
while b'\n' in self.buffer:
line, self.buffer = self.buffer.split(b'\n', 1)
try:
decoded_line = line.decode('utf-8').strip()
if decoded_line:
self.rx_queue.append(decoded_line)
except Exception:
pass # Discard corrupt data frames safely
except Exception as e:
print("[UART Thread Error]:", e)
chunk = self.uart.read()
if chunk is not None and isinstance(chunk, bytes):
self.buffer += chunk
time.sleep_ms(20) # Give other background threads breathing room
# Extract complete JSON objects while accounting for nested braces
while True:
start_idx = self.buffer.find(b'{')
if start_idx == -1:
# No starting brace; clear any garbage bytes currently in buffer
self.buffer = b""
break
# Trim any leading noise before the first '{'
if start_idx > 0:
self.buffer = self.buffer[start_idx:]
# Track depth to find the matching OUTER '}'
depth = 0
in_string = False
escape = False
end_idx = -1
for i in range(len(self.buffer)):
b = self.buffer[i]
# Ignore braces inside string literals ("...")
if b == 34 and not escape: # 34 is ASCII for '"'
in_string = not in_string
elif b == 92 and in_string: # 92 is ASCII for '\'
escape = not escape
continue
elif not in_string:
if b == 123: # '{'
depth += 1
elif b == 125: # '}'
depth -= 1
if depth == 0:
end_idx = i
break
escape = False
if end_idx != -1:
# Full nested JSON object extracted safely
json_bytes = self.buffer[:end_idx + 1]
self.buffer = self.buffer[end_idx + 1:]
messages_found.append(json_bytes)
else:
# The complete outer JSON hasn't fully arrived yet; wait for next UART chunk
break
# Process valid complete frames outside the lock
for json_bytes in messages_found:
try:
decoded_str = json_bytes.decode('utf-8')
with self.lock:
self.rx_queue.append(decoded_str)
except Exception as e:
print(f"[UART Parse Error]: {e}")
time.sleep_ms(10)
def send(self, message):
"""Safely pushes strings across the serial wire from any thread context."""
if not message.endswith('\n'):
message += '\n'
data = message.encode('utf-8')
with self.lock:
self.uart.write(message.encode('utf-8'))
self.uart.write(data)
def send_as_command(self, command: 'UARTCommand'):
"""Safely sends a structured command over UART."""
json_message = command.to_json()
self.send(json_message)
def any(self):
"""Checks if any complete messages are waiting to be read."""
@@ -63,4 +113,51 @@ class SafeUART:
with self.lock:
if self.rx_queue:
return self.rx_queue.pop(0)
return None
return None
def read_as_command(self) -> 'UARTCommand | None':
"""Attempts to read the oldest unread string and parse it as a UARTCommand. Returns None if empty or invalid."""
raw_message = self.read()
if raw_message is not None:
cmd = UARTCommand.from_json(raw_message)
if cmd is None:
print("[UART] Impossible de traiter le message brut :", raw_message)
return cmd
return None
class UARTCommand:
"""A simple wrapper for commands sent over UART, allowing for structured data."""
def __init__(self, command_type: str, payload):
self.command_type = command_type
self.payload = payload
def to_json(self):
"""Serializes the command to a JSON string."""
return ujson.dumps({
"command_type": self.command_type,
"payload": self.payload
})
@staticmethod
def from_json(json_string: str) -> 'UARTCommand | None':
"""Deserializes a JSON string into a UARTCommand object."""
try:
# Remplacement préventif si des guillemets simples sont reçus
clean_str = json_string.replace("'", '"') if "'" in json_string else json_string
data = ujson.loads(clean_str)
if not isinstance(data, dict):
return None
return UARTCommand(data.get("command_type"), data.get("payload"))
except Exception as err:
# Affiche l'erreur exacte rencontrée par ujson (ex: syntax error)
print(f"[UARTCommand Parsing Error]: {err} -> Contenu: {json_string}")
return None
class UARTCommandType:
"""Enumeration of known UART command types."""
COOKING_PARAMS = "COOKING_PARAMS"
COOKING_STATE_UPDATE = "COOKING_STATE_UPDATE"