亚洲视频二区_亚洲欧洲日本天天堂在线观看_日韩一区二区在线观看_中文字幕不卡一区

公告:魔扣目錄網為廣大站長提供免費收錄網站服務,提交前請做好本站友鏈:【 網站目錄:http://www.430618.com 】, 免友鏈快審服務(50元/站),

點擊這里在線咨詢客服
新站提交
  • 網站:51998
  • 待審:31
  • 小程序:12
  • 文章:1030137
  • 會員:747

一、基本結構

先看架構圖

用python + 阿里云搭建物聯系統,可將單片機上的數據傳輸到PC端

 

框架.png

二、設備端接入

物聯網終端是用的ESP32,是一款自帶藍牙和Wifi的單片機。利用它可以直接接入互聯網,無需其他模塊。當然你可以將現在流行的NB-Iot模塊來聯網,不過需要自己寫一下驅動程序。我買的模塊是支持microPython開發的,在淘寶上可以搜索到,用起來很方便。有時間我會補上這一塊的初步教程。

用python + 阿里云搭建物聯系統,可將單片機上的數據傳輸到PC端

 

ESP32模塊.jpg

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 上的代碼如下:

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,"n","Broker:",strBroker,"n","User Name:",user_name,"n","Password:",user_password,"n")


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()

有幾點需要說明:1.代碼中的wifi.connect()函數需要自己編寫,網上能搜到類似的,也可以打賞私信我所要源碼。2.阿里云物聯網平臺的接入需要進行三元組認證,會根據一定的規則生成登錄名和密碼,這個網上信息還是比較全面的。3.向阿里云物聯網平臺發布消息的格式一定要按照代碼中所寫,網上很多代碼,但是對這一塊的描述都不清楚。

  1. Micropython使用的umqtt.simple庫,一定要設置keepalive時間,否則無法連接。這一點我是摸索了好久,最終通過查看庫的源碼才發現的問題。

三、云端設置

在云端建立一個高級產品,并創建兩個設備,以供ESP32 和PC連接。

用python + 阿里云搭建物聯系統,可將單片機上的數據傳輸到PC端

 

device.JPG

需要在產品中定義一下功能。

用python + 阿里云搭建物聯系統,可將單片機上的數據傳輸到PC端

 

device_define.JPG

云端和設備端都建立好了之后,可以查看設備運行狀態看到數據上傳

用python + 阿里云搭建物聯系統,可將單片機上的數據傳輸到PC端

 

云端數據查看.JPG

這是查看數據記錄得到的結果

用python + 阿里云搭建物聯系統,可將單片機上的數據傳輸到PC端

 

云端數據記錄.JPG

當你看到正確的數據之后,就說明你的成功接入物聯網并上傳了數據。接下來就是最重要的部分——設置是使用規則引擎來進行數據轉發,將設備demo_01的數據轉發到demo_02。這一步的語法很重要,雖然有官網有詳細教程,但是當時還是搞了好久才完全正確。規則查詢語句:

SELECT items.IndoorTemperature.value as IndoorTemperature FROM "/sys/use-your-productkey-here/Demo_01/thing/event/property/post" WHERE items.IndoorTemperature.value > 0

四、PC端接入

PC 端使用python模擬MQTT設備登陸阿里云訂閱消息就行了,只要裝好python很快就可以實現,網上也有很多代碼。代碼的很大一部分就是在做三元組認證,可以將這部分稍微修改一下來計算ESP32 登陸時所需的PC端python代碼如下:

# 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()

五、總結

工作之余了解了一下物聯網的發展,看到有意思的東西打算學一下,剛好看到了microPython,震驚之余,決心做點小東西玩玩。

這套框架全部使用python實現,比我了解到的絕大多數物聯網方案要簡單太多,雖然有些開發首先,但是用來實現一些簡單設計應該是不成問題的,只要你會python,這套系統可以很快構建。當然python也是非常好學的,長期使用C語言的人根本不需要什么學習就可以上手。

分享到:
標簽:阿里
用戶無頭像

網友整理

注冊時間:

網站:5 個   小程序:0 個  文章:12 篇

  • 51998

    網站

  • 12

    小程序

  • 1030137

    文章

  • 747

    會員

趕快注冊賬號,推廣您的網站吧!
最新入駐小程序

數獨大挑戰2018-06-03

數獨一種數學游戲,玩家需要根據9

答題星2018-06-03

您可以通過答題星輕松地創建試卷

全階人生考試2018-06-03

各種考試題,題庫,初中,高中,大學四六

運動步數有氧達人2018-06-03

記錄運動步數,積累氧氣值。還可偷

每日養生app2018-06-03

每日養生,天天健康

體育訓練成績評定2018-06-03

通用課目體育訓練成績評定