MQTT to Win10 Toast Notifications (Python)

Since Growl won’t get fixed , I needed a replacement. I wanted simple window notifications for events, without installing things reliant on the cloud or adding complexity to my existing setup.

Here is a solution with Python:

#!/usr/bin/python

# MQTT->Toast
# pip install win10toast paho-mqtt

# Import things
import json
import paho.mqtt.client as mqtt
from win10toast import ToastNotifier


# Host
MQTT_HOST = "1.1.1.1"
# Port
MQTT_PORT = 1883
# List of topics to subscribe to. Tuple required
MQTT_TOPICS = [("topic/1", 0), ("topic/2", 0)]
# Name of client
MQTT_CLIENT = "MQTT-Toaster"

# How long should the notification display for in seconds
TOAST_DURATION = 10

# Show log output
LOGGING = True

# -------------------------------


# Callback on server connect
def on_connect(client, userdata, flags, rc):
    if LOGGING:
        print(f"Connected to broker with status {rc}")
    client.subscribe(MQTT_TOPICS)


def on_message(client, userdata, msg):
    if LOGGING:
        print(f"Message {msg.topic} from broker.")
    toaster.show_toast(
        parse_topic(msg.topic), parse_payload(msg.payload), duration=TOAST_DURATION
    )


def parse_payload(p):
    # If payload is JSON prettify it
    try:
        return json.dumps(json.loads(p), indent=2)
    except json.JSONDecodeError:
        return p.decode("utf-8")


def parse_topic(t):
    return t.replace("/", " ").title()


# Main
toaster = ToastNotifier()
client = mqtt.Client(MQTT_CLIENT, True)
client.on_connect = on_connect
client.on_message = on_message
# Connect to broker
client.connect(MQTT_HOST, MQTT_PORT, 60)

try:
    client.loop_forever()
except KeyboardInterrupt:
    print("Goodbye")
1 Like