def get_second(request):
client_id = time.strftime(’%Y%m%d%H%M%S’, time.localtime(time.time()))
client = mqtt.Client(client_id)
client.username_pw_set("admin", "password") # 必须设置,否则会返回「Connected with result code 4」
client.on_connect = mqtt_on_connect_callback
client.on_message = mqtt_on_message_callback
HOST = "r.ayaki.cn"
PORT = 1883
client.connect(HOST, PORT, 60)
client.loop_forever()
def mqtt_on_connect_callback(client, userdata, flags, rc):
print("Info: Connected with result code " + str(rc))
client.subscribe(“test”) # 订阅所有topic
def mqtt_on_message_callback(client, userdata, msg):
print(‘MQTT message received from %s’ % msg.topic)
print(’ Payload: %s’ % msg.payload.decode(‘utf-8’))
# 从MQTT消息中获取JSON对象
json_payload = json.loads(msg.payload.decode('utf-8'))
# 判断type字段决定是否继续运行
if json_payload.get('type') != 'reply':
print('Err: Incorrect message format!')
return
# 获取整数类型id用于数据库查询
int_device_id = int(json_payload.get('id'))
# 执行查询
db_device_info = HaDevices.objects.get(id=int_device_id)
# 判断查询结果 为空退出
if db_device_info is None:
print('Err: Cannot found matched \' id \' in database!')
return
# print(db_device_info.id)
# 判断JSON对象中command类型
if json_payload.get('command') == "on":
db_device_info.switch = 1
elif json_payload.get('command') == "off":
db_device_info.switch = 0
else:
print('Warn: Invaild command!')
print(db_device_info.switch)
# 提交
db_device_info.save()