arun
arun

Reputation: 21

MQTT message counter on receive

I tried searching topics related to my question, as I think, it's a quite common to ask. I wanted to count the number of time the message received on "on_message". The global or local count variable won't work, how to keep count on the received messages?

Here is my snippet of code, where my count won't work as it will reset every time.

def

def on_message(client, userdata, message):
    ts_data = str(message.payload.decode("utf-8"))
    count=count+1
    print(count)

if __name__ == '__main__':
    client = mqtt.Client()
    client.on_message=on_message

could you help?

Thanks Kind Regards Arun

Upvotes: 0

Views: 982

Answers (1)

hardillb
hardillb

Reputation: 59608

I'm not sure what you mean by the following:

The global or local count variable won't work,

The following should work just fine:

count = 0

def on_message(client, userdata, message):
    global count
    ts_data = str(message.payload.decode("utf-8"))
    count=count+1
    print(count)

if __name__ == '__main__':
    client = mqtt.Client()
    client.on_message=on_message

Upvotes: 2

Related Questions