Switch control and schedules to JSON payloads
This commit is contained in:
@@ -1,10 +1,16 @@
|
||||
import logging
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Any, Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
|
||||
from app.api.deps import require_admin
|
||||
from app.api.schemas import (
|
||||
DeleteStatusResponse,
|
||||
ScheduleCreateResponse,
|
||||
ScheduleCronRequest,
|
||||
ScheduleOnceRequest,
|
||||
ScheduleTasksResponse,
|
||||
)
|
||||
from app.core.scheduler import (
|
||||
app_tz,
|
||||
create_schedule_task,
|
||||
@@ -31,39 +37,6 @@ def _validate_target(target_id: str, is_group: bool):
|
||||
return "device"
|
||||
|
||||
|
||||
def _build_action_params(
|
||||
state: Optional[bool],
|
||||
brightness: Optional[int],
|
||||
scene: Optional[str],
|
||||
temp: Optional[int],
|
||||
r: Optional[int],
|
||||
g: Optional[int],
|
||||
b: Optional[int],
|
||||
) -> dict[str, Any]:
|
||||
params: dict[str, Any] = {}
|
||||
|
||||
if state is not None:
|
||||
params["state"] = state
|
||||
if brightness is not None:
|
||||
params["dimming"] = brightness
|
||||
|
||||
if scene is not None:
|
||||
if scene not in WizDriver.SCENES:
|
||||
raise HTTPException(status_code=400, detail="Неизвестная сцена")
|
||||
params["sceneId"] = WizDriver.SCENES[scene]
|
||||
elif temp is not None:
|
||||
params["temp"] = temp
|
||||
elif any(channel is not None for channel in (r, g, b)):
|
||||
params["r"] = r or 0
|
||||
params["g"] = g or 0
|
||||
params["b"] = b or 0
|
||||
|
||||
if not params:
|
||||
raise HTTPException(status_code=400, detail="Никаких команд не передано")
|
||||
|
||||
return params
|
||||
|
||||
|
||||
async def run_group_command(target_id: str, is_group: bool, params: dict):
|
||||
"""
|
||||
Универсальное выполнение команды по расписанию.
|
||||
@@ -113,31 +86,19 @@ async def run_group_command(target_id: str, is_group: bool, params: dict):
|
||||
)
|
||||
|
||||
|
||||
@router.post("/once")
|
||||
async def schedule_once(
|
||||
target_id: str,
|
||||
state: Optional[bool] = None,
|
||||
run_at: Optional[datetime] = None,
|
||||
hours_from_now: Optional[int] = None,
|
||||
is_group: bool = True,
|
||||
brightness: Optional[int] = None,
|
||||
scene: Optional[str] = None,
|
||||
temp: Optional[int] = None,
|
||||
r: Optional[int] = None,
|
||||
g: Optional[int] = None,
|
||||
b: Optional[int] = None,
|
||||
):
|
||||
if hours_from_now is not None:
|
||||
if hours_from_now < 0:
|
||||
raise HTTPException(
|
||||
status_code=400, detail="hours_from_now не может быть отрицательным"
|
||||
)
|
||||
exec_time = datetime.now(app_tz) + timedelta(hours=hours_from_now)
|
||||
elif run_at:
|
||||
if run_at.tzinfo is None:
|
||||
exec_time = app_tz.localize(run_at)
|
||||
@router.post(
|
||||
"/once",
|
||||
response_model=ScheduleCreateResponse,
|
||||
response_model_exclude_none=True,
|
||||
)
|
||||
async def schedule_once(payload: ScheduleOnceRequest):
|
||||
if payload.hours_from_now is not None:
|
||||
exec_time = datetime.now(app_tz) + timedelta(hours=payload.hours_from_now)
|
||||
elif payload.run_at is not None:
|
||||
if payload.run_at.tzinfo is None:
|
||||
exec_time = app_tz.localize(payload.run_at)
|
||||
else:
|
||||
exec_time = run_at.astimezone(app_tz)
|
||||
exec_time = payload.run_at.astimezone(app_tz)
|
||||
else:
|
||||
raise HTTPException(status_code=400, detail="Нужно время или отступ в часах")
|
||||
|
||||
@@ -146,13 +107,13 @@ async def schedule_once(
|
||||
status_code=400, detail="Время запуска должно быть в будущем"
|
||||
)
|
||||
|
||||
target_type = _validate_target(target_id, is_group)
|
||||
action_params = _build_action_params(state, brightness, scene, temp, r, g, b)
|
||||
target_type = _validate_target(payload.target_id, payload.is_group)
|
||||
action_params = payload.to_wiz_params()
|
||||
|
||||
try:
|
||||
task = await create_schedule_task(
|
||||
trigger_type="once",
|
||||
target_id=target_id,
|
||||
target_id=payload.target_id,
|
||||
target_type=target_type,
|
||||
trigger_args={"run_at": exec_time.isoformat()},
|
||||
action_params=action_params,
|
||||
@@ -167,33 +128,24 @@ async def schedule_once(
|
||||
}
|
||||
|
||||
|
||||
@router.post("/cron")
|
||||
async def add_cron_task(
|
||||
target_id: str,
|
||||
hour: str,
|
||||
minute: str,
|
||||
day_of_week: str = "*",
|
||||
is_group: bool = True,
|
||||
state: Optional[bool] = None,
|
||||
brightness: Optional[int] = None,
|
||||
scene: Optional[str] = None,
|
||||
temp: Optional[int] = None,
|
||||
r: Optional[int] = None,
|
||||
g: Optional[int] = None,
|
||||
b: Optional[int] = None,
|
||||
):
|
||||
target_type = _validate_target(target_id, is_group)
|
||||
action_params = _build_action_params(state, brightness, scene, temp, r, g, b)
|
||||
@router.post(
|
||||
"/cron",
|
||||
response_model=ScheduleCreateResponse,
|
||||
response_model_exclude_none=True,
|
||||
)
|
||||
async def add_cron_task(payload: ScheduleCronRequest):
|
||||
target_type = _validate_target(payload.target_id, payload.is_group)
|
||||
action_params = payload.to_wiz_params()
|
||||
|
||||
trigger_args = {
|
||||
"hour": hour,
|
||||
"minute": minute,
|
||||
"day_of_week": day_of_week,
|
||||
"hour": payload.hour,
|
||||
"minute": payload.minute,
|
||||
"day_of_week": payload.day_of_week,
|
||||
}
|
||||
try:
|
||||
task = await create_schedule_task(
|
||||
trigger_type="cron",
|
||||
target_id=target_id,
|
||||
target_id=payload.target_id,
|
||||
target_type=target_type,
|
||||
trigger_args=trigger_args,
|
||||
action_params=action_params,
|
||||
@@ -204,12 +156,12 @@ async def add_cron_task(
|
||||
return {"status": "cron_scheduled", "job_id": task.job_id}
|
||||
|
||||
|
||||
@router.get("/tasks")
|
||||
@router.get("/tasks", response_model=ScheduleTasksResponse)
|
||||
async def get_all_tasks():
|
||||
return {"tasks": await list_schedule_tasks()}
|
||||
|
||||
|
||||
@router.delete("/{job_id}")
|
||||
@router.delete("/{job_id}", response_model=DeleteStatusResponse)
|
||||
async def cancel_task(job_id: str):
|
||||
if is_internal_job_id(job_id):
|
||||
raise HTTPException(status_code=403, detail="Нельзя удалить служебную задачу")
|
||||
|
||||
Reference in New Issue
Block a user