从MQTTX订阅的消息中对比无效

问题描述 投票:0回答:1

我收到的错误是比较不起作用。

def switch_on_off(topic, message):
    print("Received message on topic: {}, message: {}".format(topic, message))
    message_str = message.decode()  # Convert bytes to string
    if message_str == 'on':
        print("Turning on the relay")
        relay_pin.value(0)  # Turn on the relay
    elif message_str == 'off':
        print("Turning off the relay")
        relay_pin.value(1)  # Turn off the relay
    else:
        print("Invalid message:", message_str)



def ai_posture(topic, message):
    
    print("Received message on topic: {}, message: {}".format(topic, message))
    message_str = message.decode()  # Convert bytes to string
    if message_str == 'Bad posture detected!':
        print("buzzer beeping")
        oled.text("Bad Posture Detected!", 0, 40)
        oled.show()
        buzzer_pin.value(1)
    elif message_str == 'Good posture detected!':
        print("buzzer off")
        buzzer_pin.value(0)
    else:
        print("Invalid message:", message_str)

我随机收到能够获得正确的消息并让灯关闭和打开。即使订阅的消息是一样的。我收到以下消息:

Invalid message: on
on
Invalid message: on
off
on
off
on 
python mqtt
1个回答
0
投票

您在一条消息中收到多个更新。

def switch_on_off(topic, message):
    print("Received message on topic: {}, message: {}".format(topic, message))
    message_str = message.decode()  # Convert bytes to string
    for operation in message_str.split():
        if operation == 'on':
            print("Turning on the relay")
            relay_pin.value(0)  # Turn on the relay
        elif operation == 'off':
            print("Turning off the relay")
            relay_pin.value(1)  # Turn off the relay
        else:
            print("Invalid message:", operation)

请注意,您可以只保存最后一个命令并只执行该命令,而不是多次调整继电器:

def switch_on_off(topic, message):
    print("Received message on topic: {}, message: {}".format(topic, message))
    message_str = message.decode()  # Convert bytes to string
    operation = message_str.split()[-1]
    if operation == 'on':
        print("Turning on the relay")
        relay_pin.value(0)  # Turn on the relay
    elif operation == 'off':
        print("Turning off the relay")
        relay_pin.value(1)  # Turn off the relay
    else:
        print("Invalid message:", message_str)
© www.soinside.com 2019 - 2024. All rights reserved.