时间从mqtt有效负载打开/关闭屏幕

时间:2019-01-29 11:32:48

标签: python timer counter mqtt python-multithreading

我是python的新手,仍然在学习,所以请对我保持温柔。我已经获得了订阅MQTT主题并接收代码的python脚本。

如果有效载荷等于该代码,则它将设置计时器,该计时器将打开显示屏。时间过后,显示器将关闭,直到有效载荷再次等于之前所述的相同代码为止。

这是我的代码:

 startTipLabel.text = "longer text what you want"
 startTipLabel.numberOfLines = 0
 startTipLabel.lineBreakMode = NSLineBreakMode.ByWordWrapping

问题:

运行代码时,出现错误消息:

    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 之后接近尾声,它看起来正确吗?还是可以做得更好?

谢谢

更新:

因此,我感谢@blt对我的代码进行了排序。但是,当msg.payload匹配“ 1381683”时,我的代码将继续循环播放。我得到以下信息:

# display is now off. we wait for motion and turn it on

以上内容不断循环播放...

1 个答案:

答案 0 :(得分:0)

缩进在python中很重要。

您需要将以下代码块缩进一级:

timeUntilDisplayOff = 1800

timer = timeUntilDisplayOff

while True:

否则,本节后面的代码将在范围内没有msg变量(因此会出现错误)。

所以on_message函数的前半部分是:

def on_message(client, userdata, msg):
    global myGlobalMessagePayload
    if msg.topic == 'home/OpenMQTTGateway/433toMQTT':
        myGlobalMessagePayload = msg.payload

    timeUntilDisplayOff = 1800

    timer = timeUntilDisplayOff

    while True:

        if msg.payload == '1381683':
                timer = timeUntilDisplayOff
                print ("Motion detected! Setting timer to " + str(timer) + " seconds.")