Bladeren bron

Add an option to enable MQTT-over-TLS

William Hughes 8 jaren geleden
bovenliggende
commit
c6fdee7819
2 gewijzigde bestanden met toevoegingen van 25 en 1 verwijderingen
  1. 13 1
      config.ini.dist
  2. 12 0
      miflora-mqtt-daemon.py

+ 13 - 1
config.ini.dist

@@ -30,7 +30,7 @@
 # The hostname or IP address of the MQTT broker to connect to (Default: localhost)
 #hostname = localhost
 
-# The TCP port the MQTT broker is listening on. SSL/TLS currently not implemented (Default: 1883)
+# The TCP port the MQTT broker is listening on (Default: 1883)
 #port = 1883
 
 # Maximum period in seconds between ping messages to the broker. (Default: 60)
@@ -48,6 +48,18 @@
 #username = user
 #password = pwd123
 
+# Enable TLS/SSL on the connection
+#tls = false
+
+# Path to CA Certificate file to verify host
+#tls_ca_cert =
+
+# Path to TLS client auth key file
+#tls_keyfile =
+
+# Path to TLS client auth certificate file
+#tls_certfile =
+
 [Sensors]
 
 # Add your Mi Flora sensors here. Each sensor consists of a name and a Ethernet MAC address.

+ 12 - 0
miflora-mqtt-daemon.py

@@ -1,5 +1,6 @@
 #!/usr/bin/env python3
 
+import ssl
 import sys
 import re
 import json
@@ -149,6 +150,17 @@ if reporting_mode in ['mqtt-json', 'mqtt-homie', 'mqtt-smarthome']:
     elif reporting_mode == 'mqtt-smarthome':
         mqtt_client.will_set('{}/connected'.format(base_topic), payload='0', retain=True)
 
+    if config['MQTT'].get('tls', False):
+        # According to the docs, setting PROTOCOL_SSLv23 "Selects the highest protocol version
+        # that both the client and server support. Despite the name, this option can select
+        # “TLS” protocols as well as “SSL”" - so this seems like a resonable default
+        mqtt_client.tls_set(
+            ca_certs=config['MQTT'].get('tls_ca_cert', None),
+            keyfile=config['MQTT'].get('tls_keyfile', None),
+            certfile=config['MQTT'].get('tls_certfile', None),
+            tls_version=ssl.PROTOCOL_SSLv23
+        )
+
     if config['MQTT'].get('username'):
         mqtt_client.username_pw_set(config['MQTT'].get('username'), config['MQTT'].get('password', None))
     try: