m0_68053386 2022-05-09 12:14 采纳率: 100%
浏览 82
已结题

有没有家人看一下Python代码的问题啊

不能同时设置为云端下发多个参数,例这两个PumpStatus= Msg['params']['PumpStatus'], WidowStatus= Msg['params']['WidowStatus'],
能不能解决为参数自动获取默认值。


run主函数
#!/usr/bin/python3

import aliLink,mqttd,rpi
import time,json
import DHT11,soil_humidity
import relay1
from threading import Thread


# 三元素(iot后台获取)
ProductKey = 'a17I2AgBkl6'
DeviceName = 'Pi_001'
DeviceSecret = "b1df76826b53c9f3897488d98d1b49b1"
# topic (iot后台获取)
POST='/sys/a17I2AgBkl6/Pi_001/thing/event/property/post'# 上报消息到云
POST_REPLY = '/sys/a17I2AgBkl6/Pi_001/thing/event/property/post_reply'
SET = '/sys/a17I2AgBkl6/Pi_001/thing/service/property/set'  # 订阅云端指令



PumpStatus= 0
Pump_Status= 0
WidowStatus = 0
Widow_Status = 0
Thread(target=relay1.close1).start()
Thread(target=relay1.close2).start()
#Thread(target=relay.close).start()
# 消息回调(云端下发消息的回调函数)
def on_message(client, userdata, msg):
    #print(msg.payload)
    topic=msg.topic
    payload=msg.payload
    if("thing/service/property/set"in topic):
        Msg = json.loads(msg.payload)
        global WidowStatus,Pump_Status,PumpStatus,WidowStatus
        PumpStatus= Msg['params']['PumpStatus']
        WidowStatus= Msg['params']['WidowStatus']
        if Widow_Status != WidowStatus:
            Widow_Status = WidowStatus
            relay1.Widowctrl(Widow_Status)
        if Pump_Status != PumpStatus:
            Pump_Status = PumpStatus
            relay1.Widowctrl(Pump_Status) 
        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)


# 信息获取上报,每10秒钟上报一次系统参数
while True:
    time.sleep(3)
    #获取指示灯状态
    power_stats=int(rpi.getLed())
    if(power_stats==0):
        power_LED = 0
    else:
        power_LED= 1

    # CPU 信息
    CPU_temp = float(rpi.getCPUtemperature())  # 温度   ℃
    CPU_usage = float(rpi.getCPUuse())   # 占用率 %
    Temperature,Humidity=DHT11.getdht11()
    Soil_Humidity=soil_humidity.setup()
    
 
    # 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_temp':CPU_temp,
        'CPU_usage':CPU_usage,
        'RAM_total':RAM_total,
        'RAM_used':RAM_used,
        'RAM_free':RAM_free,
        'DISK_total':DISK_total,
        'DISK_used_space':DISK_used,
        'DISK_used_percentage':DISK_perc,
        'PowerLed':power_LED,
        'airTemp':Temperature,
        'airHumidity':Humidity,
        'SoilStatus':Soil_Humidity,
        'PumpStatus':PumpStatus
    }
    JsonUpdataMsn = aliLink.Alink(updateMsn)
    print(JsonUpdataMsn)

    mqtt.push(POST,JsonUpdataMsn) #定时向阿里云IOT推送我们构建好的Alink协议数据
   
    
    format_time = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(time.time()))   # 格式化日期
    print("present time:",format_time)

    print("//////////////////////////////////////////////////////////")
```python

Alink函数
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
```python
MQTT函数
#!/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)   #监听标签



img

  • 写回答

3条回答 默认 最新

  • hyh123a 全栈领域新星创作者 2022-05-09 12:37
    关注

    没太理解什么意思,
    函数参数获取默认值的话,是这样吗?
    代码如下:

    def func(para1='123', para2=222):
        print(para1, para2)
    
    
    func()  # 不传参数,使用函数默认参数
    func(para1='aaa', para2=11111111)  # 传参
    

    补充
    大概理解什么意思了,加个默认值判断

    补充答案如下:
    修改第38、39行的值为

    PumpStatus= Msg['params']['PumpStatus']
    WidowStatus= Msg['params']['WidowStatus']
    

           
    if 'params' in Msg.keys():
        if 'PumpStatus' in Msg['params'].keys():
            PumpStatus = Msg['params']['PumpStatus']
        else:
            PumpStatus = None
    
        if 'WidowStatus' in Msg['params'].keys():
            WidowStatus = Msg['params']['WidowStatus']
        else:
            WidowStatus = None
    else:
        PumpStatus = None
        WidowStatus = None
    

    如有问题,及时沟通。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(2条)

报告相同问题?

问题事件

  • 系统已结题 5月17日
  • 已采纳回答 5月9日
  • 创建了问题 5月9日

悬赏问题

  • ¥15 MddBootstrapInitialize2失败
  • ¥15 LCD Flicker
  • ¥15 Spring MVC项目,访问不到相应的控制器方法
  • ¥15 esp32在micropython环境下使用ssl/tls连接mqtt服务器出现以下报错Connected on 192.168.154.223发生意外错误: 5无法连接到 MQTT 代理,如何解决?
  • ¥15 关于#genesiscsheel#的问题,如何解决?
  • ¥15 Android aidl for hal
  • ¥15 STM32CubeIDE下载程序报错
  • ¥15 微信好友如何转变为会员系统?(相关搜索:小程序)
  • ¥15 c# 直接使用c++ 类库文件
  • ¥15 一个主机电脑有两个显示器,当前有两个软件主体是网页html打包的exe程序,如何通过cmd命令bat同时打开软件一个在主屏幕显示,另外一个软件在2副屏幕上显示