我正在使用MQTT和GPIO,我注意到该引脚保持最后状态就像内存一样,我举一个例子,这是我的脚本:
#!/usr/bin/python3
#required libraries
import sys
import ssl
import paho.mqtt.client as mqtt
import RPi.GPIO as gpio
import json
from time import sleep
try:
ledPin = 25
gpio.setmode(gpio.BCM)
gpio.setup(ledPin, gpio.OUT)
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
client.subscribe("topic/led_switch",1)
def on_message(client, userdata, msg):
json_data = msg.payload.decode('utf-8')
print("Message received: "+json_data)
parsed_json = json.loads(json_data)
if "on" in parsed_json:
gpio.output(ledPin, gpio.HIGH)
elif "off" in parsed_json:
gpio.output(ledPin, gpio.LOW)
def on_subscribe(mqttc, obj, mid, granted_qos):
print("Subscribed: "+str(mid)+" "+str(granted_qos)+"data"+str(obj))
mqttc = mqtt.Client(client_id="RaspberryPi_Sub", clean_session=True)
mqttc.on_connect = on_connect
mqttc.on_message = on_message
mqttc.on_subscribe = on_subscribe
mqttc.connect("...my_server", port=8883)
mqttc.loop_forever()
except KeyboardInterrupt:
pass
finally:
gpio.cleanup()
如果我用CTRL + C停止脚本并且led是例如HIGH,当我再次启动脚本时,LED开始为高电平,但它应该从低电平状态开始,反之如果我在低电平时停止,则重新启动低电平,任何想法?
答案 0 :(得分:0)
如果您希望客户端在重新启动时有效地记住最后一个状态,那么您应该将保留标志设置为true来发布控制消息。
这意味着代理会在订阅时将最后发布的消息发送给客户端。
这需要在发布客户端而不是订阅者中设置。