# -*- coding: utf-8 -*- # !/usr/bin/env python import os, sys import uuid import time import simplejson as json from django.conf import settings PROJECT_ROOT = os.path.join(os.path.abspath(os.path.split(os.path.realpath(__file__))[0] + "/.."), '..') sys.path.insert(0, PROJECT_ROOT) os.environ.update({"DJANGO_SETTINGS_MODULE": "configs.production"}) import django django.setup() from apps.web.core.networking import MessageSender from apps.web.core.mqtt_client import MqttClient from apps.web.device.models import Device IMEI = '866262048025463' server = '120.27.251.159' port = 1884 event_received = False mqttc = MqttClient(client_id = 'webapp_' + str(uuid.uuid1())) def on_connect(client, userdata, flags, rc): # 订阅设备的120响应事件,用于检查 device_topic = 'server/{}/120'.format(IMEI) client.subscribe(device_topic, qos = 0) device_topic = 'server/{}/110'.format(IMEI) client.subscribe(device_topic, qos = 0) device_topic = 'server/{}/100'.format(IMEI) client.subscribe(device_topic, qos = 0) device_topic = 'server/{}/301'.format(IMEI) client.subscribe(device_topic, qos = 0) device_topic = 'server/{}/307'.format(IMEI) client.subscribe(device_topic, qos = 0) def on_message(mqttc, obj, msg): msgDict = json.loads(bytes.decode(msg.payload)) print('received event msg = {}'.format(msgDict)) global event_received event_received = True mqttc.loop_stop() mqttc.disconnect() mqttc.close() try: mqttc.on_message = on_message mqttc.on_connect = on_connect mqttc.username_pw_set(settings.MQTT_USER, settings.MQTT_PSWD) mqttc.connect(server, port, 60) mqttc.loop_start() finally: pass cmd_list = [ {"funCode": "01", "data": "00"}, {"funCode": "02", "data": "00"}, {"funCode": "03", "data": "00010100F0"}, {"funCode": "04", "data": "0100C8"}, ] # count = 0 # # while True: # count = count + 1 # if count > 100: # break # # for cmd in cmd_list: # payload = {'cmd': 210, 'IMEI': IMEI} # payload.update(cmd) # # dev = Device.get_dev(IMEI) # # result = MessageSender.send(dev, 210, payload) # if result['rst'] != 0: # print 'error. cmd = {}'.format(str(cmd)) # exit(1) for cmd in cmd_list: payload = {'cmd': 210, 'IMEI': IMEI} payload.update(cmd) dev = Device.get_dev(IMEI) result = MessageSender.send(dev, 210, payload) if result['rst'] != 0: print 'error. cmd = {}'.format(str(cmd)) exit(1) for cmd in cmd_list: payload = {'cmd': 210, 'IMEI': IMEI} payload.update(cmd) dev = Device.get_dev(IMEI) result = MessageSender.send(dev, 210, payload) if result['rst'] != 0: print 'error. cmd = {}'.format(str(cmd)) exit(1) # for cmd in cmd_list: payload = {'cmd': 210, 'IMEI': IMEI} payload.update(cmd) dev = Device.get_dev(IMEI) MessageSender.async_send(dev, 210, payload) while True: if event_received == False: print('wait event to received.') time.sleep(5) continue else: exit(0) print 'finished'