亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

MQTT和時間延遲

MQTT和時間延遲

慕妹3146593 2023-03-08 15:57:46
我有一個 python 腳本,我正在嘗試使用它來處理 paho mqtt 和時間延遲。我研究了類似的問題,這些問題討論了 paho mqtt,例如Controlling Program with MQTT and Python。我的python腳本如下:這是我的腳本: import paho.mqtt.client as mqttClient    import time    import subprocess    import os            global lastprocessed, Connected    lastprocessed = None    Connected = False   #global variable for the state of the connection        def on_connect(client, userdata, flags, rc):        if rc == 0:            print("Connected to broker")            global Connected            Connected = True                #Signal connection        else:            print("Connection failed")            def on_message(client, userdata, message):        global lastprocessed        if message.payload.decode() == "hello":            lastprocessed = time.time()            if lastprocessed and time.time() - lastprocessed < 20:            print("good")broker_address= "192.168.1.111"  #Broker addressport = 1883                         #Broker portuser = "abcde"                    #Connection usernamepassword = "12345"            #Connection passwordclient = mqttClient.Client("Python")               #create new instanceclient.username_pw_set(user, password=password)    #set username and passwordclient.on_connect= on_connect                      #attach function to callbackclient.on_message= on_message                      #attach function to callbackclient.connect(broker_address,port,60) #connectclient.subscribe("home/OpenMQTTGateway/433toMQTT") #subscribeclient.loop_forever() #then keep listening forever我上面的代碼發生的事情是,只要在有效負載中收到“hello”,它就會打印“good”,但如果在有效負載中收到任何其他內容,包括“hello”,它會繼續打印“good”。它沒有考慮 20 秒的時間。我不確定為什么?我想要實現的目標如下:當開始執行 python 腳本時,腳本應該打印“bad”。這應該停止,直到在有效負載中收到“hello”。一旦收到“hello”,“good”應該打印 20 秒,在這 20 秒內,主題中收到的任何其他消息都應該被忽略,包括“hello”。20 秒后,腳本應該繼續打印“壞”,但只打印一次,循環繼續。
查看完整描述

1 回答

?
開滿天機

TA貢獻1786條經驗 獲得超13個贊

我使用loop_start()andloop_stop()而不是loop_forever()然后使用 between start,stop我可以創建自己的循環來檢查消息和打印文本。


我使用變量state來控制代碼是在第一個hello( state = "start") 之前還是它得到hello,現在它必須檢查時間并重復文本“好” ( state = "hello") 或者它有 20 秒之后hello并且它沒有打印任何內容 (state = "other")


在內部on_message,我只hello在收到消息時才將狀態更改為hello,而舊狀態則不同hello。


import paho.mqtt.client as mqttClient

import time


# --- functions ---


def on_connect(client, userdata, flags, rc):

    #global state

    global connected


    if rc == 0:

        print("Connected to broker")

        connected = True                

    else:

        print("Connection failed")


def on_message(client, userdata, message):

    global state

    global last_processed

    

    if message.payload.decode() == "hello":

        if state != 'hello':

            state = 'hello'

            last_processed = time.time()


    # OR

    

    #if state != 'hello':

    #    if message.payload.decode() == "hello":

    #        state = 'hello'

    #        last_processed = time.time()


# --- main ---


broker_address = "192.168.1.111"  # broker address

port = 1883                       # broker port

user = "abcde"                    # connection username

password = "12345"                # connection password


# ---


client = mqttClient.Client("Python")               # create new instance

client.username_pw_set(user, password=password)    # set username and password

client.on_connect= on_connect                      # attach function to callback

client.on_message= on_message                      # attach function to callback

client.connect(broker_address, port, 60)           # connect

client.subscribe("home/OpenMQTTGateway/433toMQTT") # subscribe


# --- main loop ---


last_processed = None

connected = False      # signal connection

state = 'start' # 'start', 'hello', 'other', 'not connected'   


# ---


client.loop_start()


try:

    while True:

        if not connected:

            print('not connected')

            

        if state == 'start':

            print('bad')

            

        if state == 'hello':

            if last_processed and time.time() - last_processed < 20:

                print("good", time.time() - last_processed, end='\r') # '\r` to write it in the same line.

            else:

                print('bad')

                state = 'other'

                last_processed = None

        

        if state == 'other':

            pass

    

        time.sleep(1.0) # to slow down example

        

except KeyboardInterrupt:

    print('KeyboardInterrupt')

    

client.loop_stop()

編輯:


如果您只需要bad一次hello,那么您可以bad在循環之前先打印,然后hello在收到消息時打印,然后time.sleep(20)在打印bad和更改狀態之前打印。


import paho.mqtt.client as mqttClient

import time


# --- functions ---


def on_connect(client, userdata, flags, rc):

    #global state

    global connected


    if rc == 0:

        print("Connected to broker")

        connected = True                

    else:

        print("Connection failed")


def on_message(client, userdata, message):

    global state


    message = message.payload.decode()

    

    if state != 'hello':

        if message == 'hello':

            state = 'hello'

            print('good') # once when start `hello`

        else:

            print('msg:', message)        


# --- main ---


broker_address = "192.168.1.111"  # broker address

port = 1883                       # broker port

user = "abcde"                    # connection username

password = "12345"                # connection password


# ---


client = mqttClient.Client("Python")               # create new instance

client.username_pw_set(user, password=password)    # set username and password

client.on_connect= on_connect                      # attach function to callback

client.on_message= on_message                      # attach function to callback

client.connect(broker_address, port, 60)           # connect

client.subscribe("home/OpenMQTTGateway/433toMQTT") # subscribe


# --- main loop ---


connected = False      # signal connection

state = 'other' # 'hello'


# ---


client.loop_start()


print('bad') # once at start


try:

    while True:

        

        if state == 'hello':

            time.sleep(20)

            print('bad')  # once when end `hello`

            state = 'other'

    

        time.sleep(1.0) # to slow down example

        

except KeyboardInterrupt:

    print('KeyboardInterrupt')

    

client.loop_stop()

使用threading.Timerinstead of time.sleep()because sleep()blocks loop 會很有用,如果你想做更多的事情,它就沒那么有用了。


import paho.mqtt.client as mqttClient

import threading


# --- functions ---


def on_connect(client, userdata, flags, rc):

    #global state

    global connected


    if rc == 0:

        print("Connected to broker")

        connected = True                

    else:

        print("Connection failed")


def on_message(client, userdata, message):

    global state


    message = message.payload.decode()

    

    if state != 'hello':

        if message == 'hello':

            state = 'hello'

            print('good') # once when start `hello`

            threading.Timer(20, end_hello).start()

        else:

            print('msg:', message)

        

def end_hello():

    global state

    

    print('bad')  # once when end `hello`

    state = 'other'


# --- main ---


broker_address = "192.168.1.111"  # broker address

port = 1883                       # broker port

user = "abcde"                    # connection username

password = "12345"                # connection password


# ---


client = mqttClient.Client("Python")               # create new instance

client.username_pw_set(user, password=password)    # set username and password

client.on_connect= on_connect                      # attach function to callback

client.on_message= on_message                      # attach function to callback

client.connect(broker_address, port, 60)           # connect

client.subscribe("home/OpenMQTTGateway/433toMQTT") # subscribe


# --- main loop ---


connected = False      # signal connection

state = 'other' # 'hello'


# ---


print('bad') # once at start

client.loop_forever()

最終你仍然可以檢查循環時間


import paho.mqtt.client as mqttClient

import time


# --- functions ---


def on_connect(client, userdata, flags, rc):

    #global state

    global connected


    if rc == 0:

        print("Connected to broker")

        connected = True                

    else:

        print("Connection failed")


def on_message(client, userdata, message):

    global state

    global last_processed

    

    message = message.payload.decode()

    

    if state != 'hello':

        if message == 'hello':

            state = 'hello'

            last_processed = time.time()

            print('good') # once when start `hello`

        else:

            print('msg:', message)        


# --- main ---


broker_address = "192.168.1.111"  # broker address

port = 1883                       # broker port

user = "abcde"                    # connection username

password = "12345"                # connection password


# ---


client = mqttClient.Client("Python")               # create new instance

client.username_pw_set(user, password=password)    # set username and password

client.on_connect= on_connect                      # attach function to callback

client.on_message= on_message                      # attach function to callback

client.connect(broker_address, port, 60)           # connect

client.subscribe("home/OpenMQTTGateway/433toMQTT") # subscribe


# --- main loop ---


last_processed = None

connected = False      # signal connection

state = 'other' # 'hello'


# ---


client.loop_start()


print('bad') # once at start


try:

    while True:

        

        if state == 'hello':

            if time.time() >= last_processed + 20:

                print('bad')  # once when end `hello`

                state = 'other'

    

        time.sleep(1.0) # to slow down example

        

except KeyboardInterrupt:

    print('KeyboardInterrupt')

    

client.loop_stop()


查看完整回答
反對 回復 2023-03-08
  • 1 回答
  • 0 關注
  • 498 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號