Alerts
This commit is contained in:
+48
-4
@@ -9,6 +9,7 @@ from shared import get_lora, get_mqtt_client, deviceTypes, config, payloads, db
|
||||
from shared.logging import log
|
||||
from shared.cookingState import CookingStates
|
||||
from shared.lora_device import LoraCommands
|
||||
from shared.alerts import AlertManager, Alert, AlertType
|
||||
from sensors import ultrasonicRanger, temp_hum, button, camera, buzzer
|
||||
from lib.systemd_logs import get_systemd_logs
|
||||
|
||||
@@ -76,7 +77,6 @@ async_event_queue = None
|
||||
ir_data_cache = {} # mw_id -> dict of IR readings
|
||||
ir_data_events = {} # mw_id -> asyncio.Event()
|
||||
|
||||
|
||||
# --- HARDWARE & MQTT SETUP ---
|
||||
lora = get_lora()
|
||||
lora.configure()
|
||||
@@ -188,6 +188,28 @@ def button_callback():
|
||||
button.set_callback(button_callback)
|
||||
button.start_button_monitoring_thread()
|
||||
|
||||
# --- Alert manager ---
|
||||
alert_manager = None
|
||||
|
||||
def on_new_alert(alert):
|
||||
# Sends to cloud server
|
||||
alert_dict = alert.to_dict()
|
||||
alert_dict["orchestrator_id"] = DEVICE_ID
|
||||
|
||||
response = requests.post(
|
||||
"https://smartwave.matthiasg.dev/alert",
|
||||
json=alert_dict,
|
||||
)
|
||||
|
||||
response.raise_for_status()
|
||||
res_json = response.json()
|
||||
print(f"[Alert Handling] Alert sent to cloud: {alert_dict}, Response: {res_json}")
|
||||
|
||||
# Send the alert to the lora device
|
||||
lora.send_reliable(payloads.lora_new_alert(alert))
|
||||
|
||||
# TODO : envoi de l'alerte aux écrans externes
|
||||
|
||||
# --- HARDWARE CONTROLLERS ---
|
||||
def _stop_hardware(microwave_id: str):
|
||||
print(f"[{microwave_id}] /!\\ Emergency stop issued to hardware.")
|
||||
@@ -268,7 +290,7 @@ async def handle_new_dish(microwave_id, detected_height):
|
||||
|
||||
async def request_cloud_cooking_plan(microwave_id, sensors_data):
|
||||
"""Sends all data to the cloud with up to 3 retries (330s timeout for AI generation)."""
|
||||
global cloud_alert
|
||||
global cloud_alert, alert_manager
|
||||
microwave_states[microwave_id] = MicrowaveState.WAITING_FOR_CLOUD
|
||||
URL = "https://smartwave.matthiasg.dev/cooking-params"
|
||||
|
||||
@@ -306,8 +328,22 @@ async def request_cloud_cooking_plan(microwave_id, sensors_data):
|
||||
|
||||
response.raise_for_status()
|
||||
|
||||
# Robust JSON extraction: handles direct dict or nested {"cook_plan": {...}}
|
||||
# JSON extraction
|
||||
res_json = response.json()
|
||||
|
||||
# Error handling
|
||||
if "error" in res_json:
|
||||
print(f"[{microwave_id}] Cloud API returned error: {res_json['error']}")
|
||||
microwave_states[microwave_id] = MicrowaveState.DONE
|
||||
|
||||
if not res_json['is_safe']: # The cooking area is not safe, raise an alert
|
||||
alert = Alert(AlertType.COOKING_SAFETY, res_json['warning_message'])
|
||||
alert_manager.add_alert(alert)
|
||||
else:
|
||||
alert = Alert(AlertType.ERROR, f"Cloud API error for microwave {microwave_id}: {res_json['error']}")
|
||||
return
|
||||
|
||||
|
||||
plan = res_json.get("cook_plan", res_json)
|
||||
|
||||
c_time = plan.get("cook_time_seconds")
|
||||
@@ -316,7 +352,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] = MicrowaveState.DONE
|
||||
microwave_states[microwave_id] = None
|
||||
return
|
||||
|
||||
print(f"[{microwave_id}] Cloud Plan Received! Starting microwave: {c_time}s @ {c_power}W")
|
||||
@@ -335,6 +371,9 @@ async def request_cloud_cooking_plan(microwave_id, sensors_data):
|
||||
return
|
||||
|
||||
except Exception as e:
|
||||
# Print stacktrace
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
print(f"[{microwave_id}] Cloud API Error (Attempt {attempt}/{max_retries}): {e}")
|
||||
|
||||
if attempt < max_retries:
|
||||
@@ -540,6 +579,11 @@ async def main():
|
||||
global async_event_queue
|
||||
print("Orchestrateur prêt. Lancement des tâches...")
|
||||
|
||||
# Initialize the alert manager and set the callback
|
||||
global alert_manager
|
||||
alert_manager = AlertManager()
|
||||
alert_manager.set_on_alert_callback(on_new_alert)
|
||||
|
||||
# Initialize SQLite database table
|
||||
init_db()
|
||||
|
||||
|
||||
Reference in New Issue
Block a user