物联网
前言
阿里云物联网平台: link
— `
pip3 install paho-mqtt
一、创建产品
然后点击刚刚创建的产品,然后点击功能定义,点击草稿编辑,再点击自定义功能定义
然后输入你想要上传的信息的类型定义
二、创建设备
设备信息是基于你刚刚定义的产品信息
点击进去后你点击右上角的查看,可以看到三元组
将上边的三元组放入代码中,然后把那个标识符改改
#!/usr/bin/python3
import aliLink,mqttd,rpi
import time,json
#线程
import threading
import time
###################################阿里云参数
# 三元素(iot后台获取)
ProductKey = '1'
DeviceName = '2'
DeviceSecret = "3"
# topic (iot后台获取)
POST = '/sys/1/2/thing/event/property/post' # 上报消息到云
POST_REPLY = '/sys/1/2/thing/event/property/post_reply'
SET = '/sys/1/2/thing/service/property/set' # 订阅云端指令
# 消息回调(云端下发消息的回调函数)
def on_message(client, userdata, msg):
#print(msg.payload)
Msg = json.loads(msg.payload)
switch = Msg['params']['PowerLed']
rpi.powerLed(switch)
print(msg.payload) # 开关值
#连接回调(与阿里云建立链接后的回调函数)
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) # 订阅服务器下发消息topic
mqtt.begin(on_message,on_connect)
def job1():
# 信息获取上报,每10秒钟上报一次系统参数
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])
# 构建与云端模型一致的消息结构
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) # 定时向阿里云IOT推送我们构建好的Alink协议数据
###################################
new_thread = threading.Thread(target=job1, name="T1")
# 启动新线程
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) #不为空则配置账号密码
self.mqttc.connect(self.Host, self.Port, self.timeOut) #初始化服务器 IP 端口 超时时间
# 初始化
def begin(self,message,connect):
self.mqttc.on_connect = connect
self.mqttc.on_message = message
self.mqttc.loop_start() # 后台新进程循环监听
# =====发送消息==========
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) #监听标签
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())) # 获取登录时间戳
Server = ProductKey+'.'+serverUrl # 服务器地址
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协议实现(字典传入,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
# 树莓派数据与控制
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灯状态检测
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)
总结
提示:这里对文章进行总结:
文章来源:https://www.toymoban.com/news/detail-517096.html
例如:以上就是今天要讲的内容,本文仅仅简单介绍了pandas的使用,而pandas提供了大量能使我们快速便捷地处理数据的函数和方法。文章来源地址https://www.toymoban.com/news/detail-517096.html
到了这里,关于连接阿里云物联网平台的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!