# -*- coding:utf-8 -*- """ @Created on : 2023/7/24 13:11 @Author: hxl @Des: """ # !/usr/bin/env python # encoding: utf-8 """ @author: tx @file: task.py @time: 2023/5/15 19:18 @desc: """ import httpx from apscheduler.schedulers.asyncio import AsyncIOScheduler from pytz import timezone from conf import setting from helper.logger import logger from models import Cabinet, EnvironmentLogs async def fetch_environment_info(cabinet): if not cabinet.ip: return {} url = f'http://{cabinet.ip}/api/cabinet/v1/sensor' async with httpx.AsyncClient() as client: response = await client.get(url, timeout=5) environment_info = response.json() return environment_info async def create_environment_logs(environment_info, cabinet): temperature_type = len(environment_info['temperature']) temperature = environment_info['temperature'] if temperature_type == 1: environment_info['right_temperature'] = temperature[0] elif temperature_type == 2: environment_info['left_temperature'] = temperature[0] environment_info['right_temperature'] = temperature[1] # 下位机协议存在修改(兼容下位机的数据上报) if environment_info["voc"] == [] or environment_info["voc"] == None: environment_info["voc"]=None else: environment_info["voc"]=",".join(map(lambda x:str(x),environment_info["voc"])) if environment_info["humidity"] == [] or environment_info["humidity"] == None: environment_info["humidity"]=None else: environment_info["humidity"]=",".join(map(lambda x:str(x),environment_info["humidity"])) await EnvironmentLogs.create(**environment_info, temperature_type=temperature_type, cabinet=cabinet) async def environment_log_job(): cabinets = await Cabinet.filter(terminal=setting.TERMINAL_ID) for cabinet in cabinets: try: environment_info = await fetch_environment_info(cabinet) await create_environment_logs(environment_info, cabinet) except Exception as e: logger.error(f"传感器数据获取失败-{e}") # def start_scheduler(): # """启动定时任务,早上8点与晚上8点执行一次获取一次下位机环境数据""" # scheduler = AsyncIOScheduler(timezone=timezone('Asia/Shanghai')) # scheduler.add_job(environment_log_job, 'interval', minutes=30) # # scheduler.add_job(environment_log_job, 'cron', hour="8,20") # scheduler.start() async def start_scheduler(): """启动定时任务,早上8点与晚上8点执行一次获取一次下位机环境数据""" scheduler = AsyncIOScheduler(timezone=timezone('Asia/Shanghai')) try: cabinets = await Cabinet.filter(terminal=setting.TERMINAL_ID) minute = int(cabinets[0].params.get("minute")) print("minute-->",minute) except Exception as e: minute = 30 logger.info(f"准备启动环境监控定时任务, 间隔时间: {minute}") scheduler.add_job(environment_log_job, 'interval', minutes=int(minute)) # scheduler.add_job(environment_log_job, 'cron', hour="8,20") scheduler.start()