mqtt wrapper: add tls handling

Signed-off-by: Thomas Klaehn <thomas.klaehn@u-blox.com>
This commit is contained in:
Thomas Klaehn 2018-02-10 11:36:10 +01:00 committed by tkl
parent 31b6294088
commit 2ce37d3a00
2 changed files with 18 additions and 12 deletions

View File

@ -10,7 +10,7 @@ import paho.mqtt.client as mqtt_client
class Mqtt(object): class Mqtt(object):
''' Wrapper class for mqtt communication ''' ''' Wrapper class for mqtt communication '''
def __init__(self, hostname, port=1883, keepalive=60, qos=2, retain=True, subscribe=[]): def __init__(self, hostname, port=1883, ca_certs=None, certfile=None, keyfile=None, keepalive=60, qos=2, retain=True, subscribe=[]):
''' Constructor ''' Constructor
@param hostname: The hostname of the mqtt broker @param hostname: The hostname of the mqtt broker
@param port: The port number used for mqtt transport @param port: The port number used for mqtt transport
@ -21,6 +21,9 @@ class Mqtt(object):
''' '''
self.hostname = hostname self.hostname = hostname
self.port = port self.port = port
self.ca_certs = ca_certs
self.certfile = certfile
self.keyfile = keyfile
self.keepalive = keepalive self.keepalive = keepalive
self.client = mqtt_client.Client() self.client = mqtt_client.Client()
self.client.on_connect = self.__on_connect self.client.on_connect = self.__on_connect
@ -34,17 +37,20 @@ class Mqtt(object):
def connect(self): def connect(self):
''' Connect to mqtt broker ''' ''' Connect to mqtt broker '''
ret = False
if not self.is_connected: if not self.is_connected:
res = self.client.connect(self.hostname, self.port, \ res = None
self.keepalive) try:
if res != mqtt_client.MQTT_ERR_SUCCESS: self.client.tls_set(self.ca_certs, self.certfile, self.keyfile)
return False res = self.client.connect(self.hostname, self.port, self.keepalive)
if res == mqtt_client.MQTT_ERR_SUCCESS:
res = self.client.loop_start() res = self.client.loop_start()
if res == mqtt_client.MQTT_ERR_INVAL: if res != mqtt_client.MQTT_ERR_INVAL:
return False ret = True
self.is_connected = True self.is_connected = True
return True except ValueError:
return False pass
return ret
def disconnect(self): def disconnect(self):
''' Disconnect from mqtt broker ''' ''' Disconnect from mqtt broker '''

View File

@ -9,5 +9,5 @@ type 'python setup.py install' to install the distribution.
''' '''
from distutils.core import setup from distutils.core import setup
setup(name='mqtt', version='1.0.0', author='Thomas Klaehn', setup(name='mqtt', version='1.1.0', author='Thomas Klaehn',
author_email='tkl@blackfinn.de', packages=['mqtt']) author_email='tkl@blackfinn.de', packages=['mqtt'])