scd_transpond_new.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. # -*- coding: utf-8 -*-
  2. # File Name:mqtt_chat_client.py
  3. # Python Version:3.5.1
  4. import os
  5. import django
  6. import sys
  7. BASE_DIR = os.path.dirname(os.path.abspath(__file__)) # 定位到你的django根目录
  8. sys.path.append(os.path.abspath(os.path.join(BASE_DIR, os.pardir)))
  9. os.environ.setdefault("DJANGO_SETTINGS_MODULE",
  10. "yfwlw_pro.settings") # project_name 项目名称
  11. django.setup()
  12. print("<-----python_mqtt_transpond_scd is run----->")
  13. import paho.mqtt.client as mqtt
  14. import json
  15. from apps.AppInfoManage.models import Alarm_record, Equip, Equip_Forward, Equip_type, MyUser, RecentSCDdata, SCDdata, SCDstatus, SCDstatus_all
  16. from apps.ReportManage.all_dict import transpont_equip_scd
  17. import re
  18. import requests
  19. import datetime
  20. import time
  21. class CJSONEncoder(json.JSONEncoder):
  22. def default(self, obj):
  23. if isinstance(obj, datetime):
  24. return obj.strftime('%Y-%m-%d %H:%M:%S')
  25. elif isinstance(obj, date):
  26. return obj.strftime('%Y-%m-%d')
  27. else:
  28. return json.JSONEncoder.default(self, obj)
  29. # 连接后的操作: 0为成功
  30. def on_connect(client, userdata, flags, rc):
  31. # print("Connected with result code "+str(rc))
  32. # for x in transpont_equip_scd:
  33. # client.subscribe("/yfkj/scd/pub/%s"%x)
  34. # client.subscribe("/yfkj/scd/offline/%s"%x)
  35. client.subscribe("/yfkj/scd/pub/862285036189284")
  36. client.subscribe("/yfkj/scd/pub/866950040591157")
  37. client.subscribe("/yfkj/scd/offline/862285036189284")
  38. client.subscribe("/yfkj/scd/offline/866950040591157")
  39. # *****成功发布******
  40. def on_publish(msg, rc):
  41. if rc == 0:
  42. print("publish success,msg = "+msg)
  43. # 从服务器接受到消息后回调此函数 :
  44. def on_message(client, userdata, msg):
  45. print('\r')
  46. print('=================================================')
  47. print('\r')
  48. print("<-----topic:\n" + msg.topic + ';\n')
  49. print("Message:\n" + str(msg.payload) + "----->\n")
  50. # 从主题中获取imei
  51. # imei = msg.topic[14:len(msg.topic)]
  52. imei = re.sub("\D", "", msg.topic)
  53. print("<-----imei:", imei, "----->")
  54. # url = "http://127.0.0.1:8000/test"
  55. payload = json.loads(msg.payload.decode())
  56. if "pub" in msg.topic:
  57. if payload.get("cmd") == "data":
  58. print("<-----uploading data!----->")
  59. extdata = payload.get("ext")
  60. print(type(extdata))
  61. t= time.time()
  62. _time = int(round(t * 1000))
  63. try:
  64. clt = extdata['clt']
  65. except:
  66. clt = ""
  67. data = {
  68. "id": "123",
  69. "version": "1.0",
  70. "params": {
  71. "ah": {
  72. "value": extdata['ah'],
  73. "time": _time
  74. },
  75. "bv": {
  76. "value": extdata['bv'],
  77. "time": _time
  78. },
  79. "tps": {
  80. "value": extdata['tps'],
  81. "time": _time
  82. },
  83. "ws": {
  84. "value": extdata['ws'],
  85. "time": _time
  86. },
  87. "cv": {
  88. "value": extdata['cv'],
  89. "time": _time
  90. },
  91. "at": {
  92. "value": extdata['at'],
  93. "time": _time
  94. },
  95. "rps": {
  96. "value": extdata['rps'],
  97. "time": _time
  98. },
  99. "ct": {
  100. "value": extdata['ct'],
  101. "time": _time
  102. },
  103. "lps": {
  104. "value": extdata['lps'],
  105. "time": _time
  106. },
  107. "clt": {
  108. "value": clt,
  109. "time": _time
  110. },
  111. "ds": {
  112. "value": extdata['ds'],
  113. "time": _time
  114. },
  115. "lat": {
  116. "value": extdata['lat'],
  117. "time": _time
  118. },
  119. "lng": {
  120. "value": extdata['lng'],
  121. "time": _time
  122. }
  123. },
  124. "method": "thing.event.property.post"
  125. }
  126. if imei == "862285036189284":
  127. device_name = "scd1"
  128. product_key = "a1FF0vxypV0"
  129. username = device_name + "&" + product_key
  130. password = "DD6CE0A8D19F24EEEBA518D7E59DCEA23C087FB1"
  131. # publish(主题:Topic; 消息内容)
  132. client_id = "86123456|securemode=3,signmethod=hmacsha1|"
  133. TASK_TOPIC = '/sys/%s/scd1/thing/event/property/post'%product_key # 客户端发布消息主题
  134. broker_addr = "%s.iot-as-mqtt.cn-shanghai.aliyuncs.com"%product_key
  135. """
  136. 客户端发布消息
  137. :param message: 消息主体
  138. :return:
  139. """
  140. # payload = data
  141. client = mqtt.Client(client_id, transport='tcp')
  142. client.username_pw_set(username, password)
  143. client.connect(broker_addr, 1883, 60) # 此处端口默认为1883,通信端口期keepalive默认60
  144. client.loop_start()
  145. client.publish(TASK_TOPIC, json.dumps(data, ensure_ascii=False))
  146. print("邢志宁客户信息发送成功",data)
  147. elif imei == "866950040591157":
  148. device_name = "scd2"
  149. product_key = "a1FF0vxypV0"
  150. username = device_name + "&" + product_key
  151. password = "04ABD84F9A46E84F20034FDE4B32E9CE6A309E46"
  152. # publish(主题:Topic; 消息内容)
  153. client_id = "861234567|securemode=3,signmethod=hmacsha1|"
  154. TASK_TOPIC = '/sys/%s/scd2/thing/event/property/post'%product_key # 客户端发布消息主题
  155. broker_addr = "%s.iot-as-mqtt.cn-shanghai.aliyuncs.com"%product_key
  156. """
  157. 客户端发布消息
  158. :param message: 消息主体
  159. :return:
  160. """
  161. # payload = data
  162. client = mqtt.Client(client_id, transport='tcp')
  163. client.username_pw_set(username, password)
  164. client.connect(broker_addr, 1883, 60) # 此处端口默认为1883,通信端口期keepalive默认60
  165. client.loop_start()
  166. client.publish(TASK_TOPIC, json.dumps(data, ensure_ascii=False))
  167. print("邢志宁客户信息发送成功",data)
  168. if __name__ == '__main__':
  169. client = mqtt.Client(
  170. client_id="SCD_TRANSPOND_NEW",
  171. clean_session=True,
  172. userdata=None,
  173. # protocol=MQTTv311,# 数据库版本
  174. )
  175. # 必须设置,否则会返回「Connected with result code 4」
  176. client.username_pw_set("admin", "password")
  177. client.on_connect = on_connect
  178. client.on_message = on_message
  179. HOST = "127.0.0.1"
  180. client.connect(HOST, 1883, 60)
  181. client.loop_forever()
  182. # # 输入发布的话题名称:
  183. # # user = input("请输入名称:")
  184. # topic = "/yfkj/scd/cmd/2001"
  185. # client.user_data_set(topic)
  186. # client.loop_start()
  187. # while True:
  188. # str = input()
  189. # if str:
  190. # client.publish("/yfkj/scd/cmd/2001", json.dumps({"topic": topic, "cmd": str}))