From 370ae642999799a4cbaffa563dca89a1b735d8a4 Mon Sep 17 00:00:00 2001 From: caoqianming Date: Sun, 17 Mar 2024 22:14:23 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=B7=BB=E5=8A=A0mqtt=E8=84=9A?= =?UTF-8?q?=E6=9C=AC=E5=B9=B6=E5=A2=9E=E5=8A=A0require?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/mqtt/__init__.py | 0 apps/mqtt/client.py | 44 +++++++++++++++++++++++++++++++++++++++++++ requirements.txt | 1 + 3 files changed, 45 insertions(+) create mode 100644 apps/mqtt/__init__.py create mode 100644 apps/mqtt/client.py diff --git a/apps/mqtt/__init__.py b/apps/mqtt/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/apps/mqtt/client.py b/apps/mqtt/client.py new file mode 100644 index 00000000..04452d14 --- /dev/null +++ b/apps/mqtt/client.py @@ -0,0 +1,44 @@ +import os +import sys +import django +import paho.mqtt.client as mqtt +import logging +import json +from django.conf import settings + +BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +sys.path.insert(0, BASE_DIR) + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'server.settings') +django.setup() + +_logger = logging.getLogger('log') + +def on_connect(mqttc, userdata, flags, rc, properties): + if rc == 0: + _logger.info('Mqtt Connected successfully') + if settings.KING_ENABLED: # 订阅亚控的mqtt转发 + mqttc.subscribe('datachange_S_KIO_Project') # 订阅主题 + _logger.info('订阅亚控主题成功') + else: + _logger.error('Mqtt Bad connection. Code:', rc) + +def on_message(mqttc: mqtt, userdata, msg): + print(f'Received message on topic: {msg.topic} with payload: {msg.payload}') + topic = msg.topic + payload = json.loads(msg.payload) + if topic == 'datachange_S_KIO_Project': + print(payload) + mqttc.publish('testtopic/#', 'ok') + +def start_mqtt(): + if settings.MQTT_ENABLE: + client = mqtt.Client(callback_api_version=mqtt.CallbackAPIVersion.VERSION2, client_id=settings.BASE_PROJECT_CODE) + client.on_connect = on_connect + client.on_message = on_message + # client.enable_logger(_logger) + client.connect(host=settings.MQTT_HOST,port=settings.MQTT_PORT) + client.loop_forever() + +if __name__ == '__main__': + start_mqtt() \ No newline at end of file diff --git a/requirements.txt b/requirements.txt index e532be9e..ed37fcc6 100755 --- a/requirements.txt +++ b/requirements.txt @@ -32,4 +32,5 @@ cron-descriptor==1.2.35 pymysql==1.0.3 # face-recognition==1.3.0 docxtpl==0.16.7 +paho-mqtt==2.0.0 # deepface==0.0.79