From ff51c50a4fac10189699f1d0341993905dfe7032 Mon Sep 17 00:00:00 2001 From: fxxian Date: Mon, 25 Mar 2024 21:35:03 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E4=BC=98=E5=8C=96=E6=9B=B4=E6=96=B0?= =?UTF-8?q?=E9=80=BB=E8=BE=91=EF=BC=8C=E6=B7=BB=E5=8A=A0=E5=BC=82=E5=B8=B8?= =?UTF-8?q?=E5=A4=84=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/mosquito/mqtt_task.py | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/apps/mosquito/mqtt_task.py b/apps/mosquito/mqtt_task.py index 462de18..ad5d0b5 100644 --- a/apps/mosquito/mqtt_task.py +++ b/apps/mosquito/mqtt_task.py @@ -1,12 +1,18 @@ -import json import os +import sys +import json import django from typing import Dict +from pathlib import Path from enum import Enum import paho.mqtt.client as mqtt 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") django.setup() @@ -37,15 +43,17 @@ def on_message(client, userdata, message): topic_parts = topic.split('/') device_id = topic_parts[2] - # 将消息打印到控制台(或处理数据,例如存入数据库) - print(f"Device: {device_id} update & create post") payload = message.payload.decode('utf-8') - # print(f"Message Payload: {payload}") # update and create post_data = json.loads(payload) - update_device_info(device_id, post_data=post_data) - create_mosq_post(device_id, post_data=post_data) + try: + update_device_info(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):