I'm trying to update some code someone else wrote that I've been providing a docker file for, as well as trying to keep up-to-date,since they no longer support it. In the paho docs, for v2, you need to add "mqtt.CallbackAPIVersion.VERSION1" as per this page.
In this SO question, I kind of had an idea, but I'm not a python expert and not sure exactly where to add the callback method.
The code I'm trying to update that calls the pahoo.mqtt.client is
#===========================================================================
#
# Broker connection
#
#===========================================================================
from . import config
import paho.mqtt.client as mqtt
#===========================================================================
class Client( mqtt.Client ):
"""Logging client
"""
def __init__( self, log=None ):
mqtt.Client.__init__(mqtt.CallbackAPIVersion.VERSION1, self )
self._logger = log
# Restore callbacks overwritten by stupid mqtt library
self.on_log = Client.on_log
def on_log( self, userData, level, buf ):
if self._logger:
self._logger.log( level, buf )
#===========================================================================
def connect( configDir, log, client=None ):
cfg = config.parse( configDir )
if client is None:
client = Client( log )
if cfg.user:
client.username_pw_set( cfg.user, cfg.password )
if cfg.ca_certs:
client.tls_set( cfg.ca_certs, cfg.certFile, cfg.keyFile )
log.info( "Connecting to broker at %s:%d" % ( cfg.host, cfg.port ) )
client.connect( cfg.host, cfg.port, cfg.keepAlive )
return client
#===========================================================================
Am I correct in thinking that to make this work with client v2, i need to do this?
class Client( mqtt.Client ):
"""Logging client
"""
def __init__( self, log=None ):
mqtt.Client.__init__(mqtt.CallbackAPIVersion.VERSION1, self )
self._logger = log
# Restore callbacks overwritten by stupid mqtt library
self.on_log = Client.on_log
def on_log( self, userData, level, buf ):
if self._logger:
self._logger.log( level, buf )
I tried asking chatgpt but got the following unhelpful code:
class Client(mqtt.Client):
"""Logging client"""
def __init__(self, log=None):
super().__init__(protocol=mqtt.MQTTv31, transport="tcp", clean_session=True, userdata=None,
protocol_version=mqtt.PROTOCOL_V31, callback=None)
self._logger = log
def on_log(self, userData, level, buf):
if self._logger:
self._logger.log(level, buf)
I also asked it to "rewrite it using version 2 of the library", and it came up with this:
class Client(mqtt.Client):
"""Logging client"""
def __init__(self, log=None):
super().__init__(protocol=mqtt.MQTTv5) # Specify MQTT version 5
self._logger = log
def on_log(self, userdata, level, buf):
if self._logger:
self._logger.log(level, buf)
which might be correct, but I'm not sure.