物聯(lián)網(wǎng)
前言
阿里云物聯(lián)網(wǎng)平臺(tái): link
— `
pip3 install paho-mqtt
一、創(chuàng)建產(chǎn)品
然后點(diǎn)擊剛剛創(chuàng)建的產(chǎn)品,然后點(diǎn)擊功能定義,點(diǎn)擊草稿編輯,再點(diǎn)擊自定義功能定義
然后輸入你想要上傳的信息的類型定義
二、創(chuàng)建設(shè)備
設(shè)備信息是基于你剛剛定義的產(chǎn)品信息
點(diǎn)擊進(jìn)去后你點(diǎn)擊右上角的查看,可以看到三元組
將上邊的三元組放入代碼中,然后把那個(gè)標(biāo)識(shí)符改改
#!/usr/bin/python3
import aliLink,mqttd,rpi
import time,json
#線程
import threading
import time
###################################阿里云參數(shù)
# 三元素(iot后臺(tái)獲?。?ProductKey = '1'
DeviceName = '2'
DeviceSecret = "3"
# topic (iot后臺(tái)獲取)
POST = '/sys/1/2/thing/event/property/post' # 上報(bào)消息到云
POST_REPLY = '/sys/1/2/thing/event/property/post_reply'
SET = '/sys/1/2/thing/service/property/set' # 訂閱云端指令
# 消息回調(diào)(云端下發(fā)消息的回調(diào)函數(shù))
def on_message(client, userdata, msg):
#print(msg.payload)
Msg = json.loads(msg.payload)
switch = Msg['params']['PowerLed']
rpi.powerLed(switch)
print(msg.payload) # 開關(guān)值
#連接回調(diào)(與阿里云建立鏈接后的回調(diào)函數(shù))
def on_connect(client, userdata, flags, rc):
pass
# 鏈接信息
Server,ClientId,userNmae,Password = aliLink.linkiot(DeviceName,ProductKey,DeviceSecret)
# mqtt鏈接
mqtt = mqttd.MQTT(Server,ClientId,userNmae,Password)
mqtt.subscribe(SET) # 訂閱服務(wù)器下發(fā)消息topic
mqtt.begin(on_message,on_connect)
def job1():
# 信息獲取上報(bào),每10秒鐘上報(bào)一次系統(tǒng)參數(shù)
while True:
time.sleep(10)
# CPU 信息
#CPU_temp = float(rpi.getCPUtemperature()) # 溫度 ℃
#CPU_usage = float(rpi.getCPUuse()) # 占用率 %
# RAM 信息
#RAM_stats =rpi.getRAMinfo()
#RAM_total =round(int(RAM_stats[0]) /1000,1) #
#RAM_used =round(int(RAM_stats[1]) /1000,1)
#RAM_free =round(int(RAM_stats[2]) /1000,1)
# Disk 信息
#DISK_stats =rpi.getDiskSpace()
#DISK_total = float(DISK_stats[0][:-1])
#DISK_used = float(DISK_stats[1][:-1])
#DISK_perc = float(DISK_stats[3][:-1])
# 構(gòu)建與云端模型一致的消息結(jié)構(gòu)
updateMsn = {
'cpu_temperature':12,
'cpu_usage':12,
'RAM_total':12,
'RAM_used':12,
'RAM_free':12,
'DISK_total':12,
'DISK_used_space':12,
'DISK_used_percentage':12,
'PowerLed':12
}
JsonUpdataMsn = aliLink.Alink(updateMsn)
print(JsonUpdataMsn)
mqtt.push(POST,JsonUpdataMsn) # 定時(shí)向阿里云IOT推送我們構(gòu)建好的Alink協(xié)議數(shù)據(jù)
###################################
new_thread = threading.Thread(target=job1, name="T1")
# 啟動(dòng)新線程
new_thread.start()
#!/usr/bin/python3
# pip install paho-mqtt
import paho.mqtt.client
# =====初始化======
class MQTT():
def __init__(self,host,CcientID,username=None,password=None,port=1883,timeOut=60):
self.Host = host
self.Port = port
self.timeOut = timeOut
self.username =username
self.password = password
self.CcientID = CcientID
self.mqttc = paho.mqtt.client.Client(self.CcientID) #配置ID
if self.username is not None: #判斷用戶名密碼是否為空
self.mqttc.username_pw_set(self.username, self.password) #不為空則配置賬號(hào)密碼
self.mqttc.connect(self.Host, self.Port, self.timeOut) #初始化服務(wù)器 IP 端口 超時(shí)時(shí)間
# 初始化
def begin(self,message,connect):
self.mqttc.on_connect = connect
self.mqttc.on_message = message
self.mqttc.loop_start() # 后臺(tái)新進(jìn)程循環(huán)監(jiān)聽
# =====發(fā)送消息==========
def push(self,tag,date,_Qos = 0):
self.mqttc.publish(tag,date,_Qos)
#print('OK',date)
# =======訂閱tips=====
def subscribe(self,_tag):
self.mqttc.subscribe(_tag) #監(jiān)聽標(biāo)簽
import time,json,random
import hmac,hashlib
def linkiot(DeviceName,ProductKey,DeviceSecret,server = 'iot-as-mqtt.cn-shanghai.aliyuncs.com'):
serverUrl = server
ClientIdSuffix = "|securemode=3,signmethod=hmacsha256,timestamp="
# 拼合
Times = str(int(time.time())) # 獲取登錄時(shí)間戳
Server = ProductKey+'.'+serverUrl # 服務(wù)器地址
ClientId = DeviceName + ClientIdSuffix + Times +'|' # ClientId
userNmae = DeviceName + "&" + ProductKey
PasswdClear = "clientId" + DeviceName + "deviceName" + DeviceName +"productKey"+ProductKey + "timestamp" + Times # 明文密碼
# 加密
h = hmac.new(bytes(DeviceSecret,encoding= 'UTF-8'),digestmod=hashlib.sha256) # 使用密鑰
h.update(bytes(PasswdClear,encoding = 'UTF-8'))
Passwd = h.hexdigest()
return Server,ClientId,userNmae,Passwd
# 阿里Alink協(xié)議實(shí)現(xiàn)(字典傳入,json str返回)
def Alink(params):
AlinkJson = {}
AlinkJson["id"] = random.randint(0,999999)
AlinkJson["version"] = "1.0"
AlinkJson["params"] = params
AlinkJson["method"] = "thing.event.property.post"
return json.dumps(AlinkJson)
if __name__ == "__main__":
pass
# 樹莓派數(shù)據(jù)與控制
import os
# Return CPU temperature as a character string
def getCPUtemperature():
res =os.popen('vcgencmd measure_temp').readline()
return(res.replace("temp=","").replace("'C\n",""))
# Return RAM information (unit=kb) in a list
# Index 0: total RAM
# Index 1: used RAM
# Index 2: free RAM
def getRAMinfo():
p =os.popen('free')
i =0
while 1:
i =i +1
line =p.readline()
if i==2:
return(line.split()[1:4])
# Return % of CPU used by user as a character string
def getCPUuse():
data = os.popen("top -n1 | awk '/Cpu\(s\):/ {print $2}'").readline().strip()
return(data)
# Return information about disk space as a list (unit included)
# Index 0: total disk space
# Index 1: used disk space
# Index 2: remaining disk space
# Index 3: percentage of disk used
def getDiskSpace():
p =os.popen("df -h /")
i =0
while True:
i =i +1
line =p.readline()
if i==2:
return(line.split()[1:5])
def powerLed(swatch):
led = open('/sys/class/leds/led1/brightness', 'w', 1)
led.write(str(swatch))
led.close()
# LED燈狀態(tài)檢測(cè)
def getLed():
led = open('/sys/class/leds/led1/brightness', 'r', 1)
state=led.read()
led.close()
return state
if __name__ == "__main__":
# CPU informatiom
CPU_temp =getCPUtemperature()
CPU_usage =getCPUuse()
print(CPU_usage)
# RAM information
# Output is in kb, here I convert it in Mb for readability
RAM_stats =getRAMinfo()
RAM_total = round(int(RAM_stats[0]) /1000,1)
RAM_used = round(int(RAM_stats[1]) /1000,1)
RAM_free = round(int(RAM_stats[2]) /1000,1)
print(RAM_total,RAM_used,RAM_free)
# Disk information
DISK_stats =getDiskSpace()
DISK_total = DISK_stats[0][:-1]
DISK_used = DISK_stats[1][:-1]
DISK_perc = DISK_stats[3][:-1]
print(DISK_total,DISK_used,DISK_perc)
總結(jié)
提示:這里對(duì)文章進(jìn)行總結(jié):
文章來源:http://www.zghlxwxcb.cn/news/detail-517096.html
例如:以上就是今天要講的內(nèi)容,本文僅僅簡(jiǎn)單介紹了pandas的使用,而pandas提供了大量能使我們快速便捷地處理數(shù)據(jù)的函數(shù)和方法。文章來源地址http://www.zghlxwxcb.cn/news/detail-517096.html
到了這里,關(guān)于連接阿里云物聯(lián)網(wǎng)平臺(tái)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!