MQTT学习笔记——Yeelink MQTT服务 使用mqtt.js和paho-mqtt
0 前言
var mqtt = require('mqtt'); var username = 'U-ApiKey'; var password = 'ffa3826972d6cc7ba5b17e104ec5xxxx'; var hostname = 'mqtt.yeelink.net'; var topic = '/v1.1/device/1949/sensor/2511/datapoints'; var url = 'mqtt://' + username + ':' + password + '@' + hostname; console.log(url); var client = mqtt.connect(url); // 订阅主题 client.subscribe(topic); client.on('message', function(topic, message) { console.log(topic); console.log(message); });
/v1.1/device/1949/sensor/2511/datapoints
{"sensor_id":2511,"timestamp":1410835745,"value":1}
/v1.1/device/1949/sensor/2511/datapoints
{"sensor_id":2511,"timestamp":1410835754,"value":0}
# -*- coding: utf-8 -*- import paho.mqtt.client as mqtt import RPi.GPIO as GPIO import json hostname = 'mqtt.yeelink.net' username = 'U-ApiKey' password = 'ffa3826972d6cc7ba5b17e104ec5xxxx' topic = '/v1.1/device/1949/sensor/2511/datapoints' # BCM GPIO编号 pins = [17,18,27,22,23,24,25,4] pin = 18 def gpio_setup(): # 采用BCM编号 GPIO.setmode(GPIO.BCM) # 设置所有GPIO为输出状态,且输出低电平 for pin in pins: GPIO.setup(pin, GPIO.OUT) GPIO.output(pin, GPIO.LOW) def gpio_destroy(): for pin in pins: GPIO.output(pin, GPIO.LOW) GPIO.setup(pin, GPIO.IN) # 连接成功回调函数 def on_connect(client, userdata, flags, rc): print("Connected with result code " + str(rc)) # 连接完成之后订阅主题 client.subscribe(topic) # 消息推送回调函数 def on_message(client, userdata, msg): print(msg.topic+" "+str(msg.payload)) # 获得负载中的pin 和 value gpio = json.loads(str(msg.payload)) if gpio['value'] == 0: GPIO.output(pin, GPIO.LOW) else: GPIO.output(pin, GPIO.HIGH) if __name__ == '__main__': client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message gpio_setup() try: # 配置用户名和密码 client.username_pw_set(username, password) client.connect(hostname, 1883, 60) client.loop_forever() except KeyboardInterrupt: client.disconnect() gpio_destroy()
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。