diff --git a/README.md b/README.md index 2fd55de..37bb86e 100644 --- a/README.md +++ b/README.md @@ -53,7 +53,7 @@ By default, the block searches for sensors on SMBus number 1 (/dev/i2c-1) howeve ### Publishing Data -The sensor data is available in json format either as an mqtt payload and/or via the built-in http server. If you include an mqtt broker container named "mqtt" in your application, the block will automatically publish to that. If you provide an address for the `MQTT_ADDRESS` service variable, it will publish to that broker instead. The default interval for publishing data is eight seconds, which you can override with the `MQTT_PUB_INTERVAL` service variable by providing a value in seconds. The default topic is set to `sensors` (which is compatible with the [connector block](https://github.com/balenablocks/connector#mqtt) ) which can be overridden by setting the `MQTT_PUB_TOPIC` service variable. +The sensor data is available in json format either as an mqtt payload and/or via the built-in http server. If you include an mqtt broker container named "mqtt" in your application, the block will automatically publish to that. If you provide an address for the `MQTT_ADDRESS` service variable, it will publish to that broker instead. If your MQTT broker is configured to require client authentication, you can specify a username and password by setting the `MQTT_USERNAME` and `MQTT_PASSWORD` variables. The default interval for publishing data is eight seconds, which you can override with the `MQTT_PUB_INTERVAL` service variable by providing a value in seconds. The default topic is set to `sensors` (which is compatible with the [connector block](https://github.com/balenablocks/connector#mqtt) ) which can be overridden by setting the `MQTT_PUB_TOPIC` service variable. If no mqtt broker is set, the http server will be available on port 7575. To force the http server to be active even with mqtt, set the `ALWAYS_USE_HTTPSERVER` service variable to True. diff --git a/sensor.py b/sensor.py index db1e8b6..e89d7c9 100644 --- a/sensor.py +++ b/sensor.py @@ -100,6 +100,8 @@ def background_web(server_socket): if __name__ == "__main__": mqtt_address = os.getenv('MQTT_ADDRESS', 'none') + mqtt_username = os.getenv('MQTT_USERNAME', '') + mqtt_password = os.getenv('MQTT_PASSWORD', '') use_httpserver = os.getenv('ALWAYS_USE_HTTPSERVER', 0) publish_interval = os.getenv('MQTT_PUB_INTERVAL', '8') publish_topic = os.getenv('MQTT_PUB_TOPIC', 'sensors') @@ -122,7 +124,11 @@ def background_web(server_socket): if mqtt_address != "none": print("Starting mqtt client, publishing to {0}:1883".format(mqtt_address)) print("Using MQTT publish interval: {0} sec(s)".format(interval)) - client = mqtt.Client() + client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION1) + + if mqtt_username != "": + client.username_pw_set(mqtt_username, mqtt_password) + try: client.connect(mqtt_address, 1883, 60) except Exception as e: