-
Notifications
You must be signed in to change notification settings - Fork 20
add MQTT handler example #45
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 5 commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
a6baf60
add MQTT handler example
vladak e35bf21
reorder imports per pylint
vladak 99587f0
use black
vladak 31cb610
add copyright/lincense headers
vladak 722fef9
make the handler a bit more resilient
vladak 068c585
fold MQTTHandler to logging_mqtt_handler.py
vladak da73359
apply black
vladak File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
# SPDX-FileCopyrightText: 2022 vladak | ||
# SPDX-License-Identifier: Unlicense | ||
""" | ||
Demonstrate how to use a single logger to emit log records to | ||
both console and MQTT broker, in this case Adafruit IO. | ||
""" | ||
|
||
import json | ||
import socket | ||
import ssl | ||
|
||
import adafruit_minimqtt.adafruit_minimqtt as MQTT | ||
from mqtt_handler import MQTTHandler | ||
|
||
import adafruit_logging as logging | ||
|
||
logger = logging.getLogger(__name__) | ||
|
||
broker = "io.adafruit.com" | ||
port = 8883 | ||
username = "Adafruit_IO_username" | ||
password = "Adafruit_IO_key" | ||
feedname = "Adafruit_feed_name" | ||
mqtt_topic = f"{username}/feeds/{feedname}" | ||
mqtt_client = MQTT.MQTT( | ||
broker=broker, | ||
port=port, | ||
username=username, | ||
password=password, | ||
socket_pool=socket, | ||
ssl_context=ssl.create_default_context(), | ||
) | ||
mqtt_client.connect() | ||
mqtt_handler = MQTTHandler(mqtt_client, mqtt_topic) | ||
print("adding MQTT handler") | ||
logger.addHandler(mqtt_handler) | ||
|
||
stream_handler = logging.StreamHandler() | ||
print("adding Stream handler") | ||
logger.addHandler(stream_handler) | ||
|
||
data = "foo bar" | ||
print("logging begins !") | ||
# This should emit both to the console as well as to the MQTT broker. | ||
logger.warning(json.dumps(data)) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
# SPDX-FileCopyrightText: 2022 vladak | ||
# SPDX-License-Identifier: Unlicense | ||
""" | ||
MQTT logging handler - log records will be published as MQTT messages | ||
""" | ||
|
||
import adafruit_minimqtt.adafruit_minimqtt as MQTT | ||
|
||
# adafruit_logging defines log levels dynamically. | ||
# pylint: disable=no-name-in-module | ||
from adafruit_logging import NOTSET, Handler, LogRecord | ||
|
||
|
||
class MQTTHandler(Handler): | ||
""" | ||
Log handler that emits log records as MQTT PUBLISH messages. | ||
""" | ||
|
||
def __init__(self, mqtt_client: MQTT.MQTT, topic: str) -> None: | ||
""" | ||
Assumes that the MQTT client object is already connected. | ||
""" | ||
super().__init__() | ||
|
||
self._mqtt_client = mqtt_client | ||
self._topic = topic | ||
|
||
# To make it work also in CPython. | ||
self.level = NOTSET | ||
|
||
def emit(self, record: LogRecord) -> None: | ||
""" | ||
Publish message from the LogRecord to the MQTT broker, if connected. | ||
""" | ||
try: | ||
if self._mqtt_client.is_connected(): | ||
self._mqtt_client.publish(self._topic, record.msg) | ||
except MQTT.MMQTTException: | ||
pass | ||
|
||
# To make this work also in CPython's logging. | ||
def handle(self, record: LogRecord) -> None: | ||
""" | ||
Handle the log record. Here, it means just emit. | ||
""" | ||
self.emit(record) |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.