haas506 2.0开发教程-高级组件库-mqtt
1.通过mqtt连接阿里云物联网平台
案例说明
main.py
import mqtt
import ujson
import utime as time
import _thread
import network
from driver import GPIO
d2_led = GPIO()
cloud_led = GPIO()
d2_led.open("d2_led")
cloud_led.open("cloud_led")
qos = 1
_get_topic = "/sys/{}/{}/thing/service/property/set"
_update_topic = "/sys/{}/{}/thing/event/property/post"
g_connect_status = False
def on_4g_cb(args):
global g_connect_status
pdp = args[0]
netwk_sta = args[1]
if netwk_sta == 1:
g_connect_status = True
else:
g_connect_status = False
def connect_network():
global Net,on_4g_cb,g_connect_status
Net = network.NetWorkClient()
g_register_network = False
if Net._stagecode is not None and Net._stagecode == 3 and Net._subcode == 1:
g_register_network = True
else:
g_register_network = False
if g_register_network:
Net.on(1,on_4g_cb)
Net.connect(None)
else:
print('network register failed')
while True:
if g_connect_status==False:
cloud_led.write(0)
if g_connect_status:
print('network register successed')
cloud_led.write(1)
break
time.sleep_ms(20)
return 0
def on_subcribe(topic,payload):
global client
global update_topic
print("on_subcribe: topic is:" + topic)
print("on_subcribe: payload is:" + payload)
cloudmsg = ujson.loads(payload)
if "method" in cloudmsg:
if 'property.set' in cloudmsg['method']:
params = cloudmsg['params']
if 'd2_led' in params:
if params["d2_led"] == 1:
d2_led.write(1)
if params["d2_led"] == 0:
d2_led.write(0)
print('param_msg {}'.format(params))
client.publish(update_topic,update_data(),qos)
else :
pass
def mqttloop_func(delay, id):
global client
global mqtt_state
while True:
time.sleep_ms(delay)
print('Running thread %d'%id)
ret = client.loop(1000)
print('client ret ={}'.format(ret))
if ret < 0:
cloud_led.write(0)
print('------------------mqtt disconnect!')
client.disconnect()
mqtt_reconnect()
else:
pass
def mqtt_reconnect():
global client
global mqtt_state
global update_topic
productKey = "a1S4vyFFMdL"
deviceName = "867082058707142"
deviceSecret = "7567432854953fc9b71f4fbcf4b25650"
REGION_ID="cn-shanghai"
username = "867082058707142&a1S4vyFFMdL"
clientId = "Test123456|securemode=3,timestamp=1234567890,signmethod=hmacsha1|"
password = "b48b20fdb4a2800943c325e62b72cfc50f6d234c"
mqttaddr = productKey +".iot-as-mqtt."+REGION_ID+".aliyuncs.com"
serverport = 1883
hearttime = 40
get_topic = _get_topic.format(productKey,deviceName)
update_topic = _update_topic.format(productKey,deviceName)
client = mqtt.client(clientId)
client.on_subcribe(on_subcribe)
client.username_pw_set(username,password)
ret = client.connect(mqttaddr,serverport,hearttime)
if ret == 0:
mqtt_state = 1
client.subscribe(get_topic,qos)
client.publish(update_topic,update_data(),qos)
def mqtt_connect():
mqtt_reconnect()
_thread.start_new_thread(mqttloop_func,(1000, 1))
def update_data():
d2_led_state=d2_led.read()
print("----------------d2_led state:",d2_led_state)
d={}
d["d2_led"]=d2_led_state
send_data = {
"id":"1",
"version":"1.0",
"params":d,
"sys":{"ack":1}
}
MSG = ujson.dumps(send_data)
return MSG
def main():
print('main enter')
ret = connect_network()
if ret == 0:
mqtt_connect()
else:
print('network-connection failed')
if __name__ == '__main__':
main()
board.json
{
"name": "haas506",
"version": "1.0.0",
"io": {
"ADC0": {
"type": "ADC",
"port": 0,
"sampling": 12000000
},
"mpu6050": {
"type": "I2C",
"port": 1,
"addrWidth": 7,
"freq": 400000,
"mode": "master",
"devAddr": 105
},
"KEY1": {
"type": "GPIO",
"port": 44,
"dir": "irq",
"pull": "pullup",
"intMode": "rising"
},
"work_led": {
"type": "GPIO",
"port": 0,
"dir": "output",
"pull": "pulldown"
},
"net_led": {
"type": "GPIO",
"port": 7,
"dir": "output",
"pull": "pulldown"
},
"cloud_led": {
"type": "GPIO",
"port": 9,
"dir": "output",
"pull": "pulldown"
},
"d2_led": {
"type": "GPIO",
"port": 6,
"dir": "output",
"pull": "pulldown"
},
"d3_led": {
"type": "GPIO",
"port": 8,
"dir": "output",
"pull": "pulldown"
},
"SPI0": {
"type": "SPI",
"port": 0,
"mode": "master",
"freq": 2000000
},
"serial1":{
"type":"UART",
"port":0,
"dataWidth":8,
"baudRate":115200,
"stopBits":1,
"flowControl":"disable",
"parity":"none"
},
"serial2":{
"type":"UART",
"port":1,
"dataWidth":8,
"baudRate":115200,
"stopBits":1,
"flowControl":"disable",
"parity":"none"
},
"serial3":{
"type":"UART",
"port":2,
"dataWidth":8,
"baudRate":115200,
"stopBits":1,
"flowControl":"disable",
"parity":"none"
}
},
"debugLevel": "DEBUG",
"repl":"disable"
}
2.操作步骤
(1)在阿里云物联网平台创建产品 填写产品名称、选择自定义品类,选择直连设备,选择联网方式-蜂窝,数据格式-ICA,点击确认。 (2)编辑自定义功能 点击所建立的产品:选择查看、点击功能定义和选择编辑草稿 添加自定义功能:属性、功能名称、标识符、数据类型、布尔值、读写类型 发布上线 3)添加设备 在产品下,添加一个设备:选择产品名、填写DeviceName(自定义,最好将设备的IMEI作为该名称)
(4)获取三元组,mqtt参数填入程序。
(5)烧录程序 (6)查看设备的物模型
(7)在线调试 点亮小灯 查看物模型的小灯状态 熄灭小灯 查看物模型的小灯状态
3. Class-mqtt
mqtt.client
on_subcribe | username_pw_set | connect | subcribe | publish | loop | disconnect |
---|
设置MQTT订阅回调函数 | 设置用户名和密码 | MQTT连接 | MQTT订阅的主题 | MQTT发布主题 | 设置MQTT等待时间 | 断开MQTT连接 |
-
mqtt -
实例化:mq=mqtt.client(clientId)
- 参数:按照”xxxx|securemode=3,timestamp=1234567890,signmethod=hmacsha1|”格式填写,’xxxx’和timestamp可以任意填写
-
mq.on_subcribe(callback)
- 作用:设置MQTT订阅回调函数
- 参数:callback-订阅的回调函数,回调函数中可以接收云平台下发的指令,并实现相应的功能
- 返回:0成功,其他失败
-
mq.username_pw_set(username,password)
- 作用:设置用户名和密码
- 参数:username-用户名;password-密码
- 返回:0成功,其他失败
-
mq.connect(host,port,interval)
- 作用:MQTT连接
- 参数:host-连接的主机;port-连接的端口号;interval-重试周期,单位为毫秒
- 返回:0成功,其他失败
-
mq.subcribe(subtopic,qos)
- 作用:MQTT订阅的主题
- 参数:subtopic-MQTT订阅的主题;qos-服务质量
- 返回:0成功,其他失败
-
mq.publish(topic,payload,qos)
- 作用:MQTT发布主题
- 参数:topic-MQTT发布的主题;payload-MQTT发布的消息;qos-服务质量
- 返回:0成功,其他失败
-
mq.loop(timeout)
- 作用:设置MQTT等待时间
- 参数:timeout-等待时间,单位是毫秒
- 返回:0成功,其他失败
-
mq.disconnect()
4.总结
本节介绍了如何使用haas506高级组件库的mqtt模块,实现了连接阿里云物联网平台,并使用在线调试成功点亮/熄灭小灯。
|