简体   繁体   English

使用 MQTT 回调时如何避免使用全局变量

[英]How do I avoid global variables when using MQTT callbacks

I am incrementing a global variable in my on_receive callback, to track how many messages have been received.我在我的 on_receive 回调中递增一个全局变量,以跟踪收到了多少消息。 I need to know this count for testing purposes.为了测试目的,我需要知道这个计数。

Since global variables are generally considered a code smell, is there a way to avoid using global variables in this situation?由于全局变量通常被认为是一种代码味道,有没有办法避免在这种情况下使用全局变量?

Here is my callback:这是我的回调:

def on_message_callback_v3( message_client, userdata, message ):
  global global_message_received_count
  with my_mutex:
    global_message_received_count += 1
    msg = str( message.payload.decode( "utf-8" ) )
    print( f"▼▼ ON MESSAGE ▼▼" )
    print( f"  Message received for client: {message_client}" )
    print( f"  Message user data: {userdata}" )
    print( f"  Message topic: {message.topic}" )
    print( f"  Message body: {msg}" )

When all messages have been published, I compare global_message_received_count to the published_count (incremented elsewhere), to determine if all messages have been received.发布所有消息后,我将global_message_received_countpublished_count (在其他地方增加)进行比较,以确定是否已收到所有消息。 Since the signature of the callback is enforced by Paho, I cannot pass in or return variables.由于回调的签名是由 Paho 强制执行的,因此我无法传入或返回变量。

I would like to avoid replying on the global global_message_received_count .我想避免回复全局global_message_received_count

My solution would be to use a class / object that handles receiving messages.我的解决方案是使用 class / object 来处理接收消息。 That way, the count can be a property of the handler object (code simplified):这样,计数可以是处理程序 object 的属性(代码简化):

class MessageReceivedHandler:
    count = 0
      
    def on_message_callback(self, message_client, userdata, message):
        self.count += 1
        print(message)

You can then create an instance of the handler: handler = MessageReceivedHandler() and pass handler.on_message_callback as the callback.然后您可以创建处理程序的实例: handler = MessageReceivedHandler()并将handler.on_message_callback作为回调传递。 The handler.count variable can then be accessed to check the amount of received messages.然后可以访问handler.count变量来检查接收到的消息数量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM