搭建整套物联网系统的方法有很多,最近四处捣鼓,使用python + 阿里云搭建一套最简单的物联系统,可以将单片机上的数据通过阿里云传输到PC端。
一、基本结构
先看架构图
<tt-image data-tteditor-tag="tteditorTag" contenteditable="false" class="syl1555054878027 ql-align-center" data-render-status="finished" data-syl-blot="image" style="box-sizing: border-box; cursor: text; text-align: left; color: rgb(34, 34, 34); font-family: "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "WenQuanYi Micro Hei", "Helvetica Neue", Arial, sans-serif; font-size: 16px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; white-space: pre-wrap; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial; display: block;"> image<input class="pgc-img-caption-ipt" placeholder="图片描述(最多50字)" value="" style="box-sizing: border-box; outline: 0px; color: rgb(102, 102, 102); position: absolute; left: 187.5px; transform: translateX(-50%); padding: 6px 7px; max-width: 100%; width: 375px; text-align: center; cursor: text; font-size: 12px; line-height: 1.5; background-color: rgb(255, 255, 255); background-image: none; border: 0px solid rgb(217, 217, 217); border-radius: 4px; transition: all 0.2s cubic-bezier(0.645, 0.045, 0.355, 1) 0s;"></tt-image>
二、设备端接入
物联网终端是用的ESP32,是一款自带蓝牙和Wifi的单片机。利用它可以直接接入互联网,无需其他模块。当然你可以将现在流行的NB-Iot模块来联网,不过需要自己写一下驱动程序。我买的模块是支持micropython开发的,在淘宝上可以搜索到,用起来很方便。有时间我会补上这一块的初步教程。
<tt-image data-tteditor-tag="tteditorTag" contenteditable="false" class="syl1555054878035" data-render-status="finished" data-syl-blot="image" style="box-sizing: border-box; cursor: text; color: rgb(34, 34, 34); font-family: "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "WenQuanYi Micro Hei", "Helvetica Neue", Arial, sans-serif; font-size: 16px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: left; text-indent: 0px; text-transform: none; white-space: pre-wrap; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial; display: block;"> image<input class="pgc-img-caption-ipt" placeholder="图片描述(最多50字)" value="" style="box-sizing: border-box; outline: 0px; color: rgb(102, 102, 102); position: absolute; left: 187.5px; transform: translateX(-50%); padding: 6px 7px; max-width: 100%; width: 375px; text-align: center; cursor: text; font-size: 12px; line-height: 1.5; background-color: rgb(255, 255, 255); background-image: none; border: 0px solid rgb(217, 217, 217); border-radius: 4px; transition: all 0.2s cubic-bezier(0.645, 0.045, 0.355, 1) 0s;"></tt-image>
Micropython是可以在低端硬件上运行的python,可以使用python语言直接操作IO 和MCU的外设比如UART、I2C等,用起来非常方便,不要搭建复杂的开发环境,也不需要学习寄存器配置。
作为一个对传统MCU开发非常熟悉的硬件工程师来说,感觉操作起来非常简单。目前Micropython已经支持很多硬件了,应该用比较广泛的STM32部分系列也被支持。Micropython也已经支持很多常用的库,比如蓝牙,telnet,mqtt等。下面这个链接是micropython的中文论坛。
http://www.micropython.org.cn/bbs/forum.php
ESP32 通过wifi 接入互联网,使用mqtt协议接入阿里云,将温度数据上传至阿里云。在云端通过消息订阅可以直接查看温度信息。在PC端使用python调用MQTT协议,接入到阿里云。但是PC端和ESP32在阿里云上是两个不同的设备,需要通过阿里云来转发信息,这样PC就可以拿到ESP32上传的数据了。
ESP32 上的代码如下:
<pre spellcheck="false" style="box-sizing: border-box; margin: 5px 0px; padding: 5px 10px; border: 0px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-variant-numeric: inherit; font-variant-east-asian: inherit; font-weight: 400; font-stretch: inherit; font-size: 16px; line-height: inherit; font-family: inherit; vertical-align: baseline; cursor: text; counter-reset: list-1 0 list-2 0 list-3 0 list-4 0 list-5 0 list-6 0 list-7 0 list-8 0 list-9 0; background-color: rgb(240, 240, 240); border-radius: 3px; white-space: pre-wrap; color: rgb(34, 34, 34); letter-spacing: normal; orphans: 2; text-align: left; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">from umqtt.simple import MQTTClient
import usocket as socket
import time
import wifi
wifi.connect()
Demo_01
ProductKey = "*********"#使用你自己的
ClientId = "1234|securemode=3,signmethod=hmacsha1|"
DeviceName = "Demo_01"
DeviceSecret = "*******************************"#使用你自己的
strBroker = ProductKey + ".iot-as-mqtt.cn-shanghai.aliyuncs.com"
Brokerport = 1883
user_name = "Demo_01&*********"#使用你自己的
user_password = "**********************************************"#使用你自己的
print("clientid:",ClientId,"
","Broker:",strBroker,"
","User Name:",user_name,"
","Password:",user_password,"
")
def connect():
client = MQTTClient(client_id = ClientId,server= strBroker,port=Brokerport,user=user_name, password=user_password,keepalive=60)
#please make sure keepalive value is not 0
client.connect()
temperature =25.00
while temperature < 30:
temperature += 0.5
send_mseg = '{"params": {"IndoorTemperature": %s},"method": "thing.event.property.post"}' % (temperature)
client.publish(topic="/sys/*************/Demo_01/thing/event/property/post", msg=send_mseg,qos=1, retain=False)#*号处为product id
time.sleep(3)
while True:
pass
#client.disconnect()
</pre>
有几点需要说明:
1.代码中的wifi.connect()函数需要自己编写,网上能搜到类似的,也可以打赏私信我所要源码。
2.阿里云物联网平台的接入需要进行三元组认证,会根据一定的规则生成登录名和密码,这个网上信息还是比较全面的。
3.向阿里云物联网平台发布消息的格式一定要按照代码中所写,网上很多代码,但是对这一块的描述都不清楚。
4.Micropython使用的umqtt.simple库,一定要设置keepalive时间,否则无法连接。这一点我是摸索了好久,最终通过查看库的源码才发现的问题。
三、云端设置
在云端建立一个高级产品,并创建两个设备,以供ESP32 和PC连接。
<tt-image data-tteditor-tag="tteditorTag" contenteditable="false" class="syl1555054878057" data-render-status="finished" data-syl-blot="image" style="box-sizing: border-box; cursor: text; color: rgb(34, 34, 34); font-family: "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "WenQuanYi Micro Hei", "Helvetica Neue", Arial, sans-serif; font-size: 16px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: left; text-indent: 0px; text-transform: none; white-space: pre-wrap; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial; display: block;"> image<input class="pgc-img-caption-ipt" placeholder="图片描述(最多50字)" value="" style="box-sizing: border-box; outline: 0px; color: rgb(102, 102, 102); position: absolute; left: 187.5px; transform: translateX(-50%); padding: 6px 7px; max-width: 100%; width: 375px; text-align: center; cursor: text; font-size: 12px; line-height: 1.5; background-color: rgb(255, 255, 255); background-image: none; border: 0px solid rgb(217, 217, 217); border-radius: 4px; transition: all 0.2s cubic-bezier(0.645, 0.045, 0.355, 1) 0s;"></tt-image>
需要在产品中定义一下功能。
<tt-image data-tteditor-tag="tteditorTag" contenteditable="false" class="syl1555054878061" data-render-status="finished" data-syl-blot="image" style="box-sizing: border-box; cursor: text; color: rgb(34, 34, 34); font-family: "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "WenQuanYi Micro Hei", "Helvetica Neue", Arial, sans-serif; font-size: 16px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: left; text-indent: 0px; text-transform: none; white-space: pre-wrap; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial; display: block;"> image<input class="pgc-img-caption-ipt" placeholder="图片描述(最多50字)" value="" style="box-sizing: border-box; outline: 0px; color: rgb(102, 102, 102); position: absolute; left: 187.5px; transform: translateX(-50%); padding: 6px 7px; max-width: 100%; width: 375px; text-align: center; cursor: text; font-size: 12px; line-height: 1.5; background-color: rgb(255, 255, 255); background-image: none; border: 0px solid rgb(217, 217, 217); border-radius: 4px; transition: all 0.2s cubic-bezier(0.645, 0.045, 0.355, 1) 0s;"></tt-image>
云端和设备端都建立好了之后,可以查看设备运行状态看到数据上传
<tt-image data-tteditor-tag="tteditorTag" contenteditable="false" class="syl1555054878066" data-render-status="finished" data-syl-blot="image" style="box-sizing: border-box; cursor: text; color: rgb(34, 34, 34); font-family: "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "WenQuanYi Micro Hei", "Helvetica Neue", Arial, sans-serif; font-size: 16px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: left; text-indent: 0px; text-transform: none; white-space: pre-wrap; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial; display: block;"> image<input class="pgc-img-caption-ipt" placeholder="图片描述(最多50字)" value="" style="box-sizing: border-box; outline: 0px; color: rgb(102, 102, 102); position: absolute; left: 187.5px; transform: translateX(-50%); padding: 6px 7px; max-width: 100%; width: 375px; text-align: center; cursor: text; font-size: 12px; line-height: 1.5; background-color: rgb(255, 255, 255); background-image: none; border: 0px solid rgb(217, 217, 217); border-radius: 4px; transition: all 0.2s cubic-bezier(0.645, 0.045, 0.355, 1) 0s;"></tt-image>
这是查看数据记录得到的结果
<tt-image data-tteditor-tag="tteditorTag" contenteditable="false" class="syl1555054878068" data-render-status="finished" data-syl-blot="image" style="box-sizing: border-box; cursor: text; color: rgb(34, 34, 34); font-family: "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "WenQuanYi Micro Hei", "Helvetica Neue", Arial, sans-serif; font-size: 16px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: left; text-indent: 0px; text-transform: none; white-space: pre-wrap; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial; display: block;"> image<input class="pgc-img-caption-ipt" placeholder="图片描述(最多50字)" value="" style="box-sizing: border-box; outline: 0px; color: rgb(102, 102, 102); position: absolute; left: 187.5px; transform: translateX(-50%); padding: 6px 7px; max-width: 100%; width: 375px; text-align: center; cursor: text; font-size: 12px; line-height: 1.5; background-color: rgb(255, 255, 255); background-image: none; border: 0px solid rgb(217, 217, 217); border-radius: 4px; transition: all 0.2s cubic-bezier(0.645, 0.045, 0.355, 1) 0s;"></tt-image>
当你看到正确的数据之后,就说明你的成功接入物联网并上传了数据。
接下来就是最重要的部分——设置是使用规则引擎来进行数据转发,将设备demo_01的数据转发到demo_02。这一步的语法很重要,虽然有官网有详细教程,但是当时还是搞了好久才完全正确。
<pre spellcheck="false" style="box-sizing: border-box; margin: 5px 0px; padding: 5px 10px; border: 0px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-variant-numeric: inherit; font-variant-east-asian: inherit; font-weight: 400; font-stretch: inherit; font-size: 16px; line-height: inherit; font-family: inherit; vertical-align: baseline; cursor: text; counter-reset: list-1 0 list-2 0 list-3 0 list-4 0 list-5 0 list-6 0 list-7 0 list-8 0 list-9 0; background-color: rgb(240, 240, 240); border-radius: 3px; white-space: pre-wrap; color: rgb(34, 34, 34); letter-spacing: normal; orphans: 2; text-align: left; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">规则查询语句:
规则查询语句:
SELECT items.IndoorTemperature.value as IndoorTemperature FROM "/sys/use-your-productkey-here/Demo_01/thing/event/property/post" WHERE items.IndoorTemperature.value > 0
</pre>
四、PC端接入
PC 端使用python模拟MQTT设备登陆阿里云订阅消息就行了,只要装好python很快就可以实现,网上也有很多代码。代码的很大一部分就是在做三元组认证,可以将这部分稍微修改一下来计算ESP32 登陆时所需的
PC端python代码如下:
<pre spellcheck="false" style="box-sizing: border-box; margin: 5px 0px; padding: 5px 10px; border: 0px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-variant-numeric: inherit; font-variant-east-asian: inherit; font-weight: 400; font-stretch: inherit; font-size: 16px; line-height: inherit; font-family: inherit; vertical-align: baseline; cursor: text; counter-reset: list-1 0 list-2 0 list-3 0 list-4 0 list-5 0 list-6 0 list-7 0 list-8 0 list-9 0; background-color: rgb(240, 240, 240); border-radius: 3px; white-space: pre-wrap; color: rgb(34, 34, 34); letter-spacing: normal; orphans: 2; text-align: left; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;"># coding=utf-8
import datetime
import time
import hmac
import hashlib
import math
try:
import paho.mqtt.client as mqtt
except ImportError:
print("MQTT client not find. Please install as follow:")
print("pip install paho-mqtt")
设置连接信息
Demo_02
ProductKey = "*********"#使用你自己的
ClientId = "2234" # 自定义clientId
DeviceName = "Demo_02"
DeviceSecret ="************************************8**"#使用你自己的
获取时间戳(当前时间毫秒值)
us = math.modf(time.time())[0]
ms = int(round(us * 1000))
timestamp = str(ms)
计算密码(签名值)
def calculation_sign(signmethod):
data = "".join(("clientId", ClientId, "deviceName", DeviceName,
"productKey", ProductKey, "timestamp", timestamp))
if "hmacsha1" == signmethod:
# ret = hmac.new(bytes(DeviceSecret),
# bytes(data), hashlib.sha1).hexdigest()
ret = hmac.new(bytes(DeviceSecret, encoding="utf-8"),
bytes(data, encoding="utf-8"),
hashlib.sha1).hexdigest()
elif "hmacmd5" == signmethod:
# ret = hmac.new(bytes(DeviceSecret, encoding="utf-8"),
# bytes(data, encoding="utf-8"), hashlib.md5).hexdigest()
ret = hmac.new(bytes(DeviceSecret, encoding="utf-8"),
bytes(data, encoding="utf-8"),
hashlib.md5).hexdigest()
else:
raise ValueError
return ret
======================================================
strBroker = ProductKey + ".iot-as-mqtt.cn-shanghai.aliyuncs.com"
port = 1883
client_id = "".join((ClientId,
"|securemode=3",
",signmethod=", "hmacsha1",
",timestamp=", timestamp,
"|"))
username = "".join((DeviceName, "&", ProductKey))
password = calculation_sign("hmacsha1")
print("="60)
print(strBroker)
print("client_id:", client_id)
print("username:", username)
print("password:", password)
print("="60)
成功连接后的操作
def on_connect(client, userdata, flags, rc):
print("OnConnetc, rc: " + str(rc))
成功发布消息的操作
def on_publish(client, msg, rc):
if rc == 0:
print("publish success, msg = " + msg)
成功订阅消息的操作
def on_subscribe(mqttc, obj, mid, granted_qos):
print("Subscribed: " + str(mid) + " " + str(granted_qos))
def on_log(mqttc, obj, level, string):
print("Log:" + string)
def on_message(mqttc, obj, msg):
curtime = datetime.datetime.now()
strcurtime = curtime.strftime("%Y-%m-%d %H:%M:%S")
print(strcurtime + ": " + msg.topic + " " + str(msg.qos) + " " + str(msg.payload))
on_exec(str(msg.payload))
def on_exec(strcmd):
print("Exec:", strcmd)
strExec = strcmd
if name == 'main':
mqttc = mqtt.Client(client_id)
mqttc.username_pw_set(username, password)
mqttc.on_message = on_message
mqttc.on_connect = on_connect
mqttc.on_publish = on_publish
mqttc.on_subscribe = on_subscribe
mqttc.on_log = on_log
mqttc.connect(strBroker, port, 120)
# mqttc.loop_start()
time.sleep(1)
temperature =27.55
mqttc.subscribe("/sys/************/Demo_02/thing/service/property/set", qos=1) # 换成自己的
#send_mseg = '{"pm_25": %s,"area":"%s","time":"%s"}' % (0, 0, datetime.datetime.now())
#send_mseg = '{"id": "1234", "version": "1.0","params": {"IndoorTemperature": %s},"method": "thing.event.property.post"}'%(temperature)
send_mseg = '{"params": {"IndoorTemperature": %s},"method": "thing.event.property.post"}' % (temperature)
print('send_mseg is : ',send_mseg)
mqttc.loop_forever()
</pre>
Python学习群:683380553,有大牛答疑,有资源共享!有想学习python编程的,或是转行,或是大学生,还有工作中想提升自己能力的,正在学习的小伙伴欢迎加入学习。
五、总结
工作之余了解了一下物联网的发展,看到有意思的东西打算学一下,刚好看到了microPython,震惊之余,决心做点小东西玩玩。
这套框架全部使用python实现,比我了解到的绝大多数物联网方案要简单太多,虽然有些开发首先,但是用来实现一些简单设计应该是不成问题的,只要你会python,这套系统可以很快构建。
当然python也是非常好学的,长期使用C语言的人根本不需要什么学习就可以上手。
网友评论