# -*- 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.testing"}) 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 = '868956048677870' server = '211.159.224.10' port = 1883 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": "07", "data": "0000"}, {"funCode": "0F", "data": "00"}, {"funCode": "14", "data": "01000100140001"}, # {"funCode": "05", "data": "0103"}, {"funCode": "15", "data": "01"}, {"funCode": "01", "data": "00"}, {"funCode": "02", "data": "00"}, {"funCode": "18", "data": "001800180000000A00C8012C0190025864500F01011E78FF"}, {"funCode": "1E", "data": "00"} ] 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) 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'