from typing import Any import time from app.config import settings from app.mqtt.client import MqttService from app.services.course_service import CourseService SYNC_COURSE_TASK_ACTION = "SYNC_COURSE_TASK" class InitTaskDispatcher: def __init__(self, mqtt: MqttService, course_service: CourseService) -> None: self.mqtt = mqtt self.course_service = course_service def dispatch_device_init(self, device_id: str) -> list[dict[str, Any]]: tasklist = self.course_service.get_tasklist() commands: list[dict[str, Any]] = [] for task in tasklist.get("tasks", []): action = task["action"] payload = dict(task.get("payload", {})) channel = task.get("channel", "ctl") if action == "SET_CLOCK" and payload.get("ts") == 0: payload["ts"] = int(time.time()) cmd = self._send(device_id, action, payload, channel, task.get("ttl", 60)) commands.append(cmd) return commands def dispatch_base_courses_sync(self, device_id: str) -> list[dict[str, Any]]: commands: list[dict[str, Any]] = [] for payload in self.course_service.build_base_course_sync_payloads(settings.base_url): cmd = self.mqtt.publish_task(device_id, SYNC_COURSE_TASK_ACTION, payload, ttl=7200) commands.append(cmd) return commands def dispatch_course_init(self, device_id: str, course_id: str) -> list[dict[str, Any]]: payload = self.course_service.build_course_task_sync_payload(course_id, settings.base_url) cmd = self.mqtt.publish_task(device_id, SYNC_COURSE_TASK_ACTION, payload, ttl=7200) return [cmd] def _send(self, device_id: str, action: str, payload: dict[str, Any], channel: str, ttl: int) -> dict[str, Any]: if channel == "task": return self.mqtt.publish_task(device_id, action, payload, ttl) return self.mqtt.publish_ctl(device_id, action, payload, ttl)