Я довольно новичок в Python и все еще учусь, поэтому, пожалуйста, будьте осторожны со мной.У меня есть скрипт на python, который подписывается на тему MQTT и получает код.
Если полезная нагрузка равна этому коду, тогда будет установлен таймер, который включит дисплей.По истечении этого времени дисплей отключится, пока полезная нагрузка снова не станет равной тому же коду, как описано ранее.
Вот мой код:
import paho.mqtt.client as mqttClient
import time
from subprocess import call
from time import sleep
def on_connect(client, userdata, flags, rc):
# print("Connected with result code "+str(rc))
client.subscribe("home/OpenMQTTGateway/433toMQTT")
#def on_message(client, userdata, msg):
# if msg.topic == 'home/OpenMQTTGateway/433toMQTT':
# print(str(msg.payload))
def on_message(client, userdata, msg):
global myGlobalMessagePayload
if msg.topic == 'home/OpenMQTTGateway/433toMQTT':
myGlobalMessagePayload = msg.payload
timeUntilDisplayOff = 240
timer = timeUntilDisplayOff
while True:
if msg.payload == '1381683':
timer = timeUntilDisplayOff
print ("Motion detected! Setting timer to " + str(timer) + " seconds.")
if timer > 0:
if timer % 10 == 0:
print ("Timer: " + str(timer) + " seconds")
timer -= 1
elif timer == 0:
call(['vcgencmd', 'display_power', '0'])
print ("Timer is 0. Display turned off. Waiting for motion...")
# display is now off. we wait for motion and turn it on
myGlobalMessagePayload == '1381683'
call(['vcgencmd', 'display_power', '1'])
timer = timeUntilDisplayOff
sleep(1)
Проблема:
Когда я запускаю свой код, я получаю сообщение об ошибке:
Traceback (most recent call last):
File "test2.py", line 26, in <module>
if msg.payload == '1381683':
NameError: name 'msg' is not defined
Также я использовал общий код, чтобы повторить процесс, то есть ближе к концу после # display is now off. we wait for motion and turn it on
, выглядит ли он правильно?или это может быть сделано лучше?
Спасибо
ОБНОВЛЕНИЕ:
Так что я отсортировал свой код благодаря @blt.Однако мой код продолжает зацикливаться, когда msg.payload соответствует '1381683'.Я получаю следующее:
Motion detected! Setting timer to 240 seconds.
Timer: 240 seconds
Motion detected! Setting timer to 240 seconds.
Timer: 240 seconds
Motion detected! Setting timer to 240 seconds.
Timer: 240 seconds
вышеупомянутое продолжает цикл ...