1. 准备工作

1.1 注册阿里云账号

使用个人淘宝账号或手机号,开通阿里云账号,并通过实名认证(可以用支付宝认证)

1.2 免费开通IoT物联网套件

产品官网 https://www.aliyun.com/product/iot

1.3 软件环境

python3安装: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 设备端开发

我们以python3程序来模拟设备,建立连接,上报数据。
1. 创建文件夹 aliyun-iot-demo-python
2. pip install paho-mqtt
3. 创建thermometer.py文件,添加内容

2) 下载安装SDK

在aliyun-iot-demo-python文件夹下,执行命令
$ pip install paho-mqtt

3) 应用程序目录结构

4) 模拟设备thermometer.py代码

# -*- coding: utf-8 -*-
import paho.mqtt.client as mqtt
import time
import hashlib
import hmac
import random
import json

options = {
    'productKey':'你的productKey',
    'deviceName':'你的deviceName',
    'deviceSecret':'你的deviceSecret',
    'regionId':'cn-shanghai'
}

HOST = options['productKey'] + '.iot-as-mqtt.'+options['regionId']+'.aliyuncs.com'
PORT = 1883 
PUB_TOPIC = "/sys/" + options['productKey'] + "/" + options['deviceName'] + "/thing/event/property/post";


# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))
    # client.subscribe("the/topic")

# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
    print(msg.topic+" "+str(msg.payload))

def hmacsha1(key, msg):
    return hmac.new(key.encode(), msg.encode(), hashlib.sha1).hexdigest()

def getAliyunIoTClient():
	timestamp = str(int(time.time()))
	CLIENT_ID = "paho.py|securemode=3,signmethod=hmacsha1,timestamp="+timestamp+"|"
	CONTENT_STR_FORMAT = "clientIdpaho.pydeviceName"+options['deviceName']+"productKey"+options['productKey']+"timestamp"+timestamp
	# set username/password.
	USER_NAME = options['deviceName']+"&"+options['productKey']
	PWD = hmacsha1(options['deviceSecret'],CONTENT_STR_FORMAT)
	client = mqtt.Client(client_id=CLIENT_ID, clean_session=False)
	client.username_pw_set(USER_NAME, PWD)
	return client


if __name__ == '__main__':

	client = getAliyunIoTClient()
	client.on_connect = on_connect
	client.on_message = on_message
	
	client.connect(HOST, 1883, 300)
    
	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(PUB_TOPIC,payload=str(payload_json),qos=1)
	client.loop_forever()

3. 启动运行

3.1 设备启动

$ python thermometer.py

3.2 云端查看设备运行状态

IoT物联网技术