| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215 |
- # -*- coding: utf-8 -*-
- # File Name:mqtt_chat_client.py
- # Python Version:3.5.1
- import os
- import django
- import sys
- BASE_DIR = os.path.dirname(os.path.abspath(__file__)) # 定位到你的django根目录
- sys.path.append(os.path.abspath(os.path.join(BASE_DIR, os.pardir)))
- os.environ.setdefault("DJANGO_SETTINGS_MODULE",
- "yfwlw_pro.settings") # project_name 项目名称
- django.setup()
- print("<-----python_mqtt_transpond_scd is run----->")
- import paho.mqtt.client as mqtt
- import json
- from apps.AppInfoManage.models import Alarm_record, Equip, Equip_Forward, Equip_type, MyUser, RecentSCDdata, SCDdata, SCDstatus, SCDstatus_all
- from apps.ReportManage.all_dict import transpont_equip_scd
- import re
- import requests
- import datetime
- import time
- class CJSONEncoder(json.JSONEncoder):
- def default(self, obj):
- if isinstance(obj, datetime):
- return obj.strftime('%Y-%m-%d %H:%M:%S')
- elif isinstance(obj, date):
- return obj.strftime('%Y-%m-%d')
- else:
- return json.JSONEncoder.default(self, obj)
- # 连接后的操作: 0为成功
- def on_connect(client, userdata, flags, rc):
- # print("Connected with result code "+str(rc))
- # for x in transpont_equip_scd:
- # client.subscribe("/yfkj/scd/pub/%s"%x)
- # client.subscribe("/yfkj/scd/offline/%s"%x)
- client.subscribe("/yfkj/scd/pub/862285036189284")
- client.subscribe("/yfkj/scd/pub/866950040591157")
- client.subscribe("/yfkj/scd/offline/862285036189284")
- client.subscribe("/yfkj/scd/offline/866950040591157")
- # *****成功发布******
- def on_publish(msg, rc):
- if rc == 0:
- print("publish success,msg = "+msg)
- # 从服务器接受到消息后回调此函数 :
- def on_message(client, userdata, msg):
- print('\r')
- print('=================================================')
- print('\r')
- print("<-----topic:\n" + msg.topic + ';\n')
- print("Message:\n" + str(msg.payload) + "----->\n")
- # 从主题中获取imei
- # imei = msg.topic[14:len(msg.topic)]
- imei = re.sub("\D", "", msg.topic)
- print("<-----imei:", imei, "----->")
- # url = "http://127.0.0.1:8000/test"
- payload = json.loads(msg.payload.decode())
- if "pub" in msg.topic:
- if payload.get("cmd") == "data":
- print("<-----uploading data!----->")
- extdata = payload.get("ext")
- print(type(extdata))
-
- t= time.time()
- _time = int(round(t * 1000))
- try:
- clt = extdata['clt']
- except:
- clt = ""
- data = {
- "id": "123",
- "version": "1.0",
- "params": {
- "ah": {
- "value": extdata['ah'],
- "time": _time
- },
- "bv": {
- "value": extdata['bv'],
- "time": _time
- },
- "tps": {
- "value": extdata['tps'],
- "time": _time
- },
- "ws": {
- "value": extdata['ws'],
- "time": _time
- },
- "cv": {
- "value": extdata['cv'],
- "time": _time
- },
- "at": {
- "value": extdata['at'],
- "time": _time
- },
- "rps": {
- "value": extdata['rps'],
- "time": _time
- },
- "ct": {
- "value": extdata['ct'],
- "time": _time
- },
- "lps": {
- "value": extdata['lps'],
- "time": _time
- },
- "clt": {
- "value": clt,
- "time": _time
- },
- "ds": {
- "value": extdata['ds'],
- "time": _time
- },
- "lat": {
- "value": extdata['lat'],
- "time": _time
- },
- "lng": {
- "value": extdata['lng'],
- "time": _time
- }
- },
- "method": "thing.event.property.post"
- }
- if imei == "862285036189284":
- device_name = "scd1"
- product_key = "a1FF0vxypV0"
- username = device_name + "&" + product_key
- password = "DD6CE0A8D19F24EEEBA518D7E59DCEA23C087FB1"
- # publish(主题:Topic; 消息内容)
- client_id = "86123456|securemode=3,signmethod=hmacsha1|"
- TASK_TOPIC = '/sys/%s/scd1/thing/event/property/post'%product_key # 客户端发布消息主题
- broker_addr = "%s.iot-as-mqtt.cn-shanghai.aliyuncs.com"%product_key
- """
- 客户端发布消息
- :param message: 消息主体
- :return:
- """
- # payload = data
- client = mqtt.Client(client_id, transport='tcp')
- client.username_pw_set(username, password)
- client.connect(broker_addr, 1883, 60) # 此处端口默认为1883,通信端口期keepalive默认60
- client.loop_start()
- client.publish(TASK_TOPIC, json.dumps(data, ensure_ascii=False))
- print("邢志宁客户信息发送成功",data)
- elif imei == "866950040591157":
- device_name = "scd2"
- product_key = "a1FF0vxypV0"
- username = device_name + "&" + product_key
- password = "04ABD84F9A46E84F20034FDE4B32E9CE6A309E46"
- # publish(主题:Topic; 消息内容)
- client_id = "861234567|securemode=3,signmethod=hmacsha1|"
- TASK_TOPIC = '/sys/%s/scd2/thing/event/property/post'%product_key # 客户端发布消息主题
- broker_addr = "%s.iot-as-mqtt.cn-shanghai.aliyuncs.com"%product_key
- """
- 客户端发布消息
- :param message: 消息主体
- :return:
- """
- # payload = data
- client = mqtt.Client(client_id, transport='tcp')
- client.username_pw_set(username, password)
- client.connect(broker_addr, 1883, 60) # 此处端口默认为1883,通信端口期keepalive默认60
- client.loop_start()
- client.publish(TASK_TOPIC, json.dumps(data, ensure_ascii=False))
- print("邢志宁客户信息发送成功",data)
-
-
- if __name__ == '__main__':
- client = mqtt.Client(
- client_id="SCD_TRANSPOND_NEW",
- clean_session=True,
- userdata=None,
- # protocol=MQTTv311,# 数据库版本
- )
- # 必须设置,否则会返回「Connected with result code 4」
- client.username_pw_set("admin", "password")
- client.on_connect = on_connect
- client.on_message = on_message
- HOST = "127.0.0.1"
- client.connect(HOST, 1883, 60)
- client.loop_forever()
- # # 输入发布的话题名称:
- # # user = input("请输入名称:")
- # topic = "/yfkj/scd/cmd/2001"
- # client.user_data_set(topic)
- # client.loop_start()
- # while True:
- # str = input()
- # if str:
- # client.publish("/yfkj/scd/cmd/2001", json.dumps({"topic": topic, "cmd": str}))
|