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
+62 -7
View File
@@ -1,6 +1,9 @@
import _thread
from machine import Pin
from sensors import RGBLED
from shared import get_lora, get_uart, deviceTypes, config, cookingState
from shared.uart_comm import UARTCommand, UARTCommandType
from shared.sensors import RGBLED
from shared.logging import log
import time
# --- Configuration Matérielle ---
@@ -21,7 +24,7 @@ lora.configure(freq=868.1, sf=7)
# --- Création des lEDs RGB ---
magnetron_led = RGBLED(red_pin=48, green_pin=47, blue_pin=33)
magnetron_led.set_color(RGBLED.YELLOW)
magnetron_led.color = RGBLED.WHITE_YELLOW
magnetron_led.off()
print(f"ESP32 initialisé avec l'ID : '{DEVICE_ID}' (Type : {deviceTypes.DEVICE_TYPES['MICROWAVE']})")
@@ -58,17 +61,69 @@ uart_device = get_uart(uart_id=1, tx_pin=46, rx_pin=45)
# Lancer la boucle de heartbeat dans un thread séparé
_thread.start_new_thread(heartbeat_loop, ())
# Cooking parameters
cooking_state = None
def cooking_state_temperature_provider():
return 22.0, 29.0 # TODO Remplacer par la lecture réelle de la température du plat et de l'air ambiant
def cooking_state_on_state_change(state):
print(f"[Main] Cooking state changed to: {state.state}")
# Send to the Wifi board the current state
uart_device.send_as_command(UARTCommand(UARTCommandType.COOKING_STATE_UPDATE, {"state": state.state}))
if state.paused or state.state == cookingState.CookingStates.DONE:
magnetron_led.off()
else:
magnetron_led.on()
if state.state == cookingState.CookingStates.COOKING:
pass
if state.state == cookingState.CookingStates.STIRRING_REQUIRED:
pass
if state.state == cookingState.CookingStates.DONE:
global cooking_state
cooking_state = None
if state.state == cookingState.CookingStates.ALERT:
pass
def cooking_state_on_refresh(state):
# TODO Show screen information
pass
# --- MAIN APPLICATION THREAD ---
print("[Main] Main execution path active.")
while True:
# 1. Listen for incoming UART serial packets from the WROOM board
while uart_device.any():
command = uart_device.read()
print(f"[Main] Received command from WiFi Board: {command}")
command = uart_device.read_as_command()
if command:
print(f"[Main] Received command from WiFi Board: {command.command_type}")
if command.command_type == UARTCommandType.COOKING_PARAMS:
# Handle cooking parameters command
params = command.payload
print(f"[Main] Cooking parameters received: {params}")
cooking_state = cookingState.CookingState(
cook_time=params["cook_time"],
power_level=params["power_level"],
target_temp=params["target_temp"]
)
cooking_state.set_temperature_provider(cooking_state_temperature_provider)
cooking_state.set_state_change_callback(cooking_state_on_state_change)
cooking_state.set_refresh_callback(cooking_state_on_refresh)
time.sleep_ms(20) # Before sending back right away
cooking_state_on_state_change(cooking_state)
else:
print(f"[Main] Unknown command type received: {command.command_type}")
# uart_device.send(f"Hello from esp-32 lora ID {DEVICE_ID}")
# 2. Send local metrics over the wire to the WiFi board every few seconds
# uart_device.send("Data Pack: LoRa Link RSSI -72dBm")
# Cooking State Update
if cooking_state:
cooking_state.update_tick()
print(f"[Main] Cooking state : State : {cooking_state.state}, Temperature: {cooking_state.current_dish_temp}, Paused: {cooking_state.paused}, Remaining Time: {cooking_state.get_remaining_time():.2f}s, Estimated Remaining Time: {cooking_state.get_remaining_time_estimation():.2f}s")
time.sleep_ms(200)
+5
View File
@@ -1,5 +1,6 @@
# This file is executed on every boot (including wake-boot from deepsleep)
import esp
from machine import Pin
esp.osdebug(True)
#import webrepl
#webrepl.start()
@@ -17,3 +18,7 @@ def do_connect(ssid, pwd):
# Attempt to connect to WiFi network
do_connect("Smartwave-1", 'Smartwave-prot-1')
# Set PIN 27 as GND for the temperature sensor (MLX90614)
sensor_gnd = Pin(27, Pin.OUT)
sensor_gnd.value(0)
+83 -37
View File
@@ -2,7 +2,10 @@ import _thread
import select
from machine import Pin, I2C
from sensors import temperature_sensor
from shared import get_mqtt_client, get_uart, config, payloads
from shared import get_mqtt_client, get_uart, config, payloads, cookingState
from shared.uart_comm import UARTCommand, UARTCommandType
from shared.sensors import RGBLED
from shared.logging import log
import time
import ujson as json
import sys
@@ -22,7 +25,10 @@ try:
DEVICE_ID = f.read().strip()
except Exception:
DEVICE_ID = "ESP32_Inconnu"
# --- Cooking State ---
cooking_state = None # This will hold the current cooking state if any
# --- MQTT SETUP ---
MQTT_CA_FILE = "/certs/ca.crt"
@@ -59,16 +65,25 @@ def on_mqtt_message(message):
# Handle cooking messages
elif message['topic'] == config.MQTT_TOPIC_COOKING and payload_data and payload_data["id_microwave"] == DEVICE_ID:
# Cooking sensors init request
if not "cook_time_seconds" in payload_data:
if not "cook_time" in payload_data:
print("[MQTT Thread] Cooking sensors init received from the orchestrator")
obj_temp = temperature_sensor.read_object_temp()
amb_temp = temperature_sensor.read_ambient_temp()
obj_temp = mlx_temperature_sensor.read_object_temp()
amb_temp = mlx_temperature_sensor.read_ambient_temp()
queue_publish(config.MQTT_TOPIC_SENSOR, payloads.mqtt_sensor_data(DEVICE_ID, obj_temp, amb_temp))
# Received cooking parameters from the orchestrator
else:
print("[MQTT Thread] Cooking parameters received from the orchestrator:", payload_data)
# Here you would handle the cooking parameters, e.g., start a cooking process
# For now, we just print them
global cooking_state
cooking_state = cookingState.CookingState(
cook_time=payload_data["cook_time"],
power_level=payload_data["power_level"],
target_temp=payload_data["target_temp"]
)
cooking_state.set_state_change_callback(on_cooking_state_change)
cooking_state.set_state(cookingState.CookingStates.IDLE) # Set initial state to IDLE
# Send to the LoRa board the cooking parameters
uart_device.send_as_command(UARTCommand(UARTCommandType.COOKING_PARAMS, payload_data))
print("[MQTT Thread] Cooking parameters sent to LoRa board.")
print("[MQTT Thread] Message processing complete.")
@@ -135,39 +150,47 @@ def mqtt_background_thread():
pass
time.sleep(5)
# --- UART BACKGROUND THREAD ---
def uart_background_thread():
"""Background UART worker handling all serial operations safely."""
print("[Thread] Background UART worker started.")
uart_device = get_uart(uart_id=2, tx_pin=17, rx_pin=16)
while True:
try:
# 1. Check for incoming messages from the Heltec board
while uart_device.any():
incoming_msg = uart_device.read()
print(f"[Thread] Received from esp-lora over UART: {incoming_msg}")
# 2. Example: Send data to the Heltec board every 5 seconds
# uart_device.send("Status Check: WiFi Active")
time.sleep(5) # Fast responsive polling loop for local UART
except Exception as e:
print("[Thread] UART error encountered:", e)
time.sleep(5)
# --- Launch background worker ---
_thread.start_new_thread(mqtt_background_thread, ())
_thread.start_new_thread(uart_background_thread, ())
# UART
uart_device = get_uart(uart_id=2, tx_pin=17, rx_pin=16)
# Cooking Cycle
cooking_state = None
def on_received_cooking_state_update(new_state):
global cooking_state
if cooking_state is None:
print("[Main] No active cooking state to update.")
return
log(f"[Main] Updating cooking state to: {new_state}")
cooking_state.set_state(new_state)
# Status LED
status_led = RGBLED(red_pin=21, green_pin=19, blue_pin=18)
def on_cooking_state_change(state):
print(f"[Main] Cooking state changed to: {state.state}")
# === STATUS LED UPDATE ===
BLINK_INTERVAL_MS = 500 # Blink every 500ms
if state.state == cookingState.CookingStates.IDLE:
status_led.color = RGBLED.OFF
status_led.blink_off()
if state.state == cookingState.CookingStates.COOKING:
status_led.color = RGBLED.YELLOW
status_led.blink_off()
if state.state == cookingState.CookingStates.STIRRING_REQUIRED:
status_led.color = RGBLED.ORANGE
status_led.blink_on(BLINK_INTERVAL_MS)
if state.state == cookingState.CookingStates.DONE:
status_led.color = RGBLED.GREEN
status_led.blink_off()
if state.state == cookingState.CookingStates.ALERT:
status_led.color = RGBLED.RED
status_led.blink_on(BLINK_INTERVAL_MS)
# --- MAIN APPLICATION THREAD (Core 0) ---
print("[Main] Main execution path active.")
time.sleep(2) # Give the thread a moment to initial connect
mqtt_hello_sent_timestamp = -config.MQTT_HELLO_INTERVAL
mqtt_client.subscribe(config.MQTT_TOPIC_HELLO, qos=config.MQTT_QOS)
# Temperature sensor setup
temperature_sensor_i2c = I2C(0, scl=Pin(25, Pin.IN, Pin.PULL_UP), sda=Pin(26, Pin.IN, Pin.PULL_UP), freq=100000)
@@ -178,7 +201,13 @@ if 0x5A in devices:
print("MLX90614 found at address 0x5A!")
else:
print("MLX90614 not found. Please check your wiring.")
temperature_sensor = temperature_sensor.MLX90614(temperature_sensor_i2c)
mlx_temperature_sensor = temperature_sensor.MLX90614(temperature_sensor_i2c)
# --- Launch background worker ---
_thread.start_new_thread(mqtt_background_thread, ())
time.sleep(2) # Give the thread a moment to initial connect
mqtt_hello_sent_timestamp = -config.MQTT_HELLO_INTERVAL
mqtt_client.subscribe(config.MQTT_TOPIC_HELLO, qos=config.MQTT_QOS)
while True:
# MQTT HELLO sent every x seconds until we get a response from the orchestrator
@@ -187,6 +216,23 @@ while True:
queue_publish(config.MQTT_TOPIC_HELLO, payloads.mqtt_hello(DEVICE_ID))
mqtt_hello_sent_timestamp = time.time()
pass
# 1. Listen for incoming UART serial packets from the WROOM board
while uart_device.any():
command = uart_device.read_as_command()
if command:
print(f"[Main] Received command from LoRa Board: {command.command_type}")
if command.command_type == UARTCommandType.COOKING_STATE_UPDATE:
# Handle cooking state update command
new_state = command.payload.get("state", None)
print(f"[Main] Cooking state update received: {new_state}")
on_received_cooking_state_update(new_state)
else:
print(f"[Main] Unknown command type received: {command.command_type}")
else:
# Fallback to reading as a raw string if parsing fails
raw_command = uart_device.read()
print(f"[Main] Received raw command from WiFi Board: {raw_command}")
# 2. Example: Send data to the Heltec board every 5 seconds
# uart_device.send("Status Check: WiFi Active")