feat: 2代设备上报数据更新统计表

This commit is contained in:
fxxian 2024-03-31 22:21:37 +08:00
parent 78749dffa6
commit 2c79d8dcd9
1 changed files with 22 additions and 1 deletions

View File

@ -5,6 +5,7 @@ import django
from typing import Dict from typing import Dict
from pathlib import Path from pathlib import Path
from enum import Enum from enum import Enum
from datetime import datetime
import paho.mqtt.client as mqtt import paho.mqtt.client as mqtt
@ -16,7 +17,7 @@ if project_path not in sys.path:
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mosqkiller.settings") os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mosqkiller.settings")
django.setup() django.setup()
from mosquito.models import MosqPost, DeviceInfo from mosquito.models import MosqPost, DeviceInfo, DevicePostStatistic, Org
# MQTT 配置 # MQTT 配置
MQTT_BROKER = "8.217.112.255" MQTT_BROKER = "8.217.112.255"
@ -50,6 +51,7 @@ def on_message(client, userdata, message):
try: try:
update_device_info(device_id, post_data=post_data) update_device_info(device_id, post_data=post_data)
create_mosq_post(device_id, post_data=post_data) create_mosq_post(device_id, post_data=post_data)
update_mosq_device_statistic(device_id, post_data=post_data)
print(f"Device: {device_id} update & create post success") print(f"Device: {device_id} update & create post success")
except KeyError as e: except KeyError as e:
print(f"Device: {device_id} update & create post failed") print(f"Device: {device_id} update & create post failed")
@ -120,6 +122,25 @@ def create_mosq_post(device_id: str, post_data: Dict):
dc_power=dc_power) dc_power=dc_power)
def update_mosq_device_statistic(device_id: str, post_data: Dict):
datetime_format = "%Y-%m-%d %H:%M:%S"
cur_date = datetime.strptime(post_data['time'], datetime_format).date()
old_record = DevicePostStatistic.objects.filter(device_id=device_id, date=cur_date).first()
org = Org.objects.get(id=1)
incr = 0
cur_total = post_data['count']
if old_record:
device = DeviceInfo.objects.filter(device_id=device_id).first()
if device:
org = device.org
incr = cur_total - old_record.total
DevicePostStatistic.objects.create(device_id=device_id,
date=cur_date,
total=cur_total,
increment=incr,
org=org)
def to_string(post_data: Dict, power_type: PowerType) -> str: def to_string(post_data: Dict, power_type: PowerType) -> str:
_type = power_type.value _type = power_type.value
load_v = post_data[_type]['voltage'] load_v = post_data[_type]['voltage']