1. 准备工作
1.1 注册阿里云账号
使用个人淘宝账号或手机号,开通阿里云账号,并通过__实名认证(可以用支付宝认证)__
1.2 免费开通IoT物联网套件
产品官网 https://www.aliyun.com/product/iot
1.3 软件环境
__python2__安装:https://www.python.org/downloads/
编辑器 sublimeText/nodepad++/vscode
2. 开发步骤
2.1 云端开发
1) 创建高级版产品
2) 功能定义,产品物模型添加属性
添加产品属性定义
属性名 | 标识符 | 数据类型 | 范围 |
---|---|---|---|
温度 | temperature | float | -50~100 |
湿度 | humidity | float | 0~100 |
物模型对应属性上报topic
/sys/替换为productKey/替换为deviceName/thing/event/property/post
物模型对应的属性上报payload
{
id: 123452452,
params: {
temperature: 26.2,
humidity: 60.4
},
method: "thing.event.property.post"
}
3) 设备管理>注册设备,获得身份三元组
2.2 设备端开发
我们以python2程序来模拟设备,建立连接,上报数据。
1. 创建文件夹 aliyun-iot-demo-python
2. pip install aliyun-python-sdk-iot-client
3. 创建thermometer.py文件,添加内容
2) 下载安装SDK
在aliyun-iot-demo-python文件夹下,执行命令
$ pip install aliyun-python-sdk-iot-client
3) 应用程序目录结构
4) 模拟设备thermometer.js代码
# -*- coding: utf-8 -*-
import aliyunsdkiotclient.AliyunIotMqttClient as iot
import json
import multiprocessing
import time
import random
options = {
'productKey':'你的productKey',
'deviceName':'你的deviceName',
'deviceSecret':'你的deviceSecret',
'port':1883,
'host':'iot-as-mqtt.cn-shanghai.aliyuncs.com'
}
host = options['productKey'] + '.' + options['host']
# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
#topic = '/' + productKey + '/' + deviceName + '/update'
print(msg.payload)
def on_connect(client, userdata, flags_dict, rc):
print("Connected with result code " + str(rc))
def on_disconnect(client, userdata, flags_dict, rc):
print("Disconnected.")
def worker(client):
topic = '/sys/'+options['productKey']+'/'+options['deviceName']+'/thing/event/property/post'
while True:
time.sleep(5)
payload_json = {
'id': int(time.time()),
'params': {
'temperature': random.randint(20, 30),
'humidity': random.randint(40, 50)
},
'method': "thing.event.property.post"
}
print('send data to iot server: ' + str(payload_json))
client.publish(topic, payload=str(payload_json))
if __name__ == '__main__':
client = iot.getAliyunIotMqttClient(options['productKey'], options['deviceName'], options['deviceSecret'], secure_mode=3)
client.on_connect = on_connect
client.connect(host=host, port=options['port'], keepalive=60)
p = multiprocessing.Process(target=worker, args=(client,))
p.start()
client.loop_forever()
3. 启动运行
3.1 设备启动
$ python thermometer.py