fix: 优化更新逻辑,添加异常处理
This commit is contained in:
parent
656e062040
commit
ff51c50a4f
|
@ -1,12 +1,18 @@
|
||||||
import json
|
|
||||||
import os
|
import os
|
||||||
|
import sys
|
||||||
|
import json
|
||||||
import django
|
import django
|
||||||
from typing import Dict
|
from typing import Dict
|
||||||
|
from pathlib import Path
|
||||||
from enum import Enum
|
from enum import Enum
|
||||||
import paho.mqtt.client as mqtt
|
import paho.mqtt.client as mqtt
|
||||||
|
|
||||||
|
|
||||||
pwd = os.path.dirname(os.path.realpath(__file__))
|
pwd = os.path.dirname(os.path.realpath(__file__))
|
||||||
|
project_path = Path(pwd).parent.parent
|
||||||
|
if project_path not in sys.path:
|
||||||
|
sys.path.append(str(project_path))
|
||||||
|
|
||||||
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mosqkiller.settings")
|
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mosqkiller.settings")
|
||||||
django.setup()
|
django.setup()
|
||||||
|
|
||||||
|
@ -37,15 +43,17 @@ def on_message(client, userdata, message):
|
||||||
topic_parts = topic.split('/')
|
topic_parts = topic.split('/')
|
||||||
device_id = topic_parts[2]
|
device_id = topic_parts[2]
|
||||||
|
|
||||||
# 将消息打印到控制台(或处理数据,例如存入数据库)
|
|
||||||
print(f"Device: {device_id} update & create post")
|
|
||||||
payload = message.payload.decode('utf-8')
|
payload = message.payload.decode('utf-8')
|
||||||
# print(f"Message Payload: {payload}")
|
|
||||||
|
|
||||||
# update and create
|
# update and create
|
||||||
post_data = json.loads(payload)
|
post_data = json.loads(payload)
|
||||||
|
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)
|
||||||
|
print(f"Device: {device_id} update & create post success")
|
||||||
|
except KeyError:
|
||||||
|
print(f"Device: {device_id} update & create post failed")
|
||||||
|
print(payload)
|
||||||
|
|
||||||
|
|
||||||
def update_device_info(device_id: str, post_data: Dict):
|
def update_device_info(device_id: str, post_data: Dict):
|
||||||
|
|
Loading…
Reference in New Issue