在Django中写mqtt脚本并使用
Python环境下安装MQTT也很简单,需要注意的就是不要输错命令
在Python3环境下安装Python MQTT的命令是:
pip3 install paho-mqtt
使用Python MQTT
编写Python MQTT脚本
代码如下:
# 为了能在外部脚本中调用Django ORM模型,必须配置脚本环境变量,将脚本注册到Django的环境变量中 import os, sys import django # 第一个参数固定,第二个参数是工程名称.settings os.environ.setdefault('DJANGO_SETTING_MODULE', 'my_django.settings') django.setup() # 引入mqtt包 import paho.mqtt.client as mqtt # 使用独立线程运行 from threading import Thread from app名 import models import time import json # 建立mqtt连接 def on_connect(client, userdata, flag, rc): print("Connect with the result code " + str(rc)) client.subscribe('test/#', qos=2) # 接收、处理mqtt消息 def on_message(client, userdata, msg): out = str(msg.payload.decode('utf-8')) print(msg.topic) print(out) out = json.loads(out) # 收到消息后执行任务 if msg.topic == 'test/newdata': print(out) # mqtt客户端启动函数 def mqttfunction(): global client # 使用loop_start 可以避免阻塞Django进程,使用loop_forever()可能会阻塞系统进程 # client.loop_start() # client.loop_forever() 有掉线重连功能 client.loop_forever(retry_first_connection=True) client = mqtt.Client(client_id="test", clean_session=False) # 启动函数 def mqtt_run(): client.on_connect = on_connect client.on_message = on_message # 绑定 MQTT 服务器地址 broker = '192.168.1.88' # MQTT服务器的端口号 client.connect(broker, 1883, 62) client.username_pw_set('user', 'user') client.reconnect_delay_set(min_delay=1, max_delay=2000) # 启动 mqttthread = Thread(target=mqttfunction) mqttthread.start() # 启动 MQTT # mqtt_run() if __name__ == "__main__": mqtt_run()
在Django项目中启动脚本
在Django2.1下,只需要在 wsgi.py 中引入要执行的脚本文件,然后执行启动函数即可。
如:
from 存放MQTT脚本的模块 import 脚本名 # 假如脚本名是:mqtt_functions mqtt_functions.mqtt_run()
到此这篇关于在Django中使用MQTT的方法的文章就介绍到这了,更多相关Django使用MQTT内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!
在Django中使用MQTT的方法
- Author -
安心写bug声明:登载此文出于传递更多信息之目的,并不意味着赞同其观点或证实其描述。
转载:https://3water.com/article/0MTM18OTI23LmEw
-------------------------------------------------------------------自己项目---------------------------------------------------------------------------------------------
用djnago 自定义命令去执行mqtt
getmqtt.py
from django.core.management.base import BaseCommand, CommandError # 引入mqtt包 import paho.mqtt.client as mqtt import datetime,json,time # 导入数据库模型 from polls.models import MqttMsg # 使用独立线程运行 from threading import Thread class Command(BaseCommand): help = 'get mqtt' def handle(self, *args, **options): print('getmqtt') # The callback for when the client receives a CONNACK response from the server. def on_connect(client, userdata, flags, rc): print("Connected with result code " + str(rc)) # Subscribing in on_connect() means that if we lose the connection and # reconnect then subscriptions will be renewed. client.subscribe("BOX/+/exxxnt/prxxx/pxx/ppi/#") # The callback for when a PUBLISH message is received from the server. def on_message(client, userdata, msg): # print(msg.topic + " " + str(msg.payload)) mqtt_topic = msg.topic.split('/') c_gateway_identifier = mqtt_topic[1] c_gateway_number = mqtt_topic[6] msg_payload = str(msg.payload) msg_payload_new = msg_payload[2:][:-1] aa = json.loads(msg_payload_new) # 13位时间戳转时间 tre_timeArray = time.localtime(aa['time'] / 1000) report_time = time.strftime("%Y-%m-%d %H:%M:%S", tre_timeArray) params = aa['params'] # 插入数据 user = MqttMsg( c_gateway_identifier=c_gateway_identifier, c_gateway_number=c_gateway_number, report_time=report_time, alarm_clear_command=params['alarm_clear_command'], box1_humidity=params['box1_humidity'],box1_temperature1=params['box1_temperature1'],box1_temperature2=params['box1_temperature2'], box2_humidity=params['box2_humidity'], box2_temperature1=params['box2_temperature1'], box2_temperature2=params['box2_temperature2'], box3_humidity=params['box3_humidity'], box3_temperature1=params['box3_temperature1'], box3_temperature2=params['box3_temperature2'], compressor_running_hour=params['compressor_running_hour'], compressor_running_minute=params['compressor_running_minute'], ice_plate1_temperature1=params['ice_plate1_temperature1'], ice_plate1_temperature2=params['ice_plate1_temperature2'], ice_plate1_temperature3=params['ice_plate1_temperature3'], ice_plate1_temperature4=params['ice_plate1_temperature4'], ice_plate2_temperature1=params['ice_plate2_temperature1'], ice_plate2_temperature2=params['ice_plate2_temperature2'], ice_plate2_temperature3=params['ice_plate2_temperature3'], ice_plate2_temperature4=params['ice_plate2_temperature4'], ice_plate3_temperature1=params['ice_plate3_temperature1'], ice_plate3_temperature2=params['ice_plate3_temperature2'], ice_plate3_temperature3=params['ice_plate3_temperature3'], ice_plate3_temperature4=params['ice_plate3_temperature4'], in_box_fan1=params['in_box_fan1'], in_box_fan2=params['in_box_fan2'], in_box_fan3=params['in_box_fan3'], door_magnetic_switch1=params['door_magnetic_switch1'], door_magnetic_switch2=params['door_magnetic_switch2'], door_magnetic_switch3=params['door_magnetic_switch3'], ice_board1_switch=params['ice_board1_switch'], ice_board2_switch=params['ice_board2_switch'], ice_board3_switch=params['ice_board3_switch'], liquid_supply_valve1=params['liquid_supply_valve1'], liquid_supply_valve2=params['liquid_supply_valve2'], liquid_supply_valve3=params['liquid_supply_valve3'], ) user.save() print('success') # print(msg_payload_new['params']) client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message client.connect("inxxxce.cxxxe.com", 1xx, 60) client.username_pw_set('emxxxckend', 'fsxxx86n') # Blocking call that processes network traffic, dispatches callbacks and # handles reconnecting. # Other loop*() functions are available that give a threaded interface and a # manual interface. client.loop_forever()
宝塔面板上
本地命令
PyCharm中