Cameteo/cameteo-interface/mqtt2papirus.py

85 lines
2.5 KiB
Python
Executable File

#!/usr/bin/python2
# -*- coding: utf8 -*-
# Get data from MQTT broker and print them to
# Papirus ePaper display
from papirus import Papirus
from papirus import PapirusTextPos
import paho.mqtt.client as mqtt
import datetime
import decimal
# MQTT settings
mqtt_server = 'localhost'
mqtt_port= 1883
mqtt_auth= {'username':'cameteo',
'password':'CaMeteo'}
mqtt_client_id= 'mqtt2papirus'
topic="pi/papirus_zero_hat/temperature/#"
# Papirus display settings
disp_rotation = 0
font_path = '/usr/share/fonts/truetype/freefont/FreeMono.ttf'
font_path_bold = '/usr/share/fonts/truetype/freefont/FreeMonoBold.ttf'
text_size = 15
date = datetime.datetime.now().replace(microsecond=0).isoformat()
temp = "-"
unit_temp = "\u00B0C"
#Set the dispaly and position of text
text = PapirusTextPos(False, rotation=disp_rotation)
#text.Clear()
text.AddText(date, 0, 0, text_size, Id="Date", font_path=font_path_bold)
text.AddText("Connecting to MQTT...", 5, 15, text_size, Id="Temperature", font_path=font_path)
text.WriteAll()
# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
date = datetime.datetime.now().replace(microsecond=0).isoformat()
text.UpdateText("Date", date, font_path=font_path_bold)
text.UpdateText("Temperature", "Connected to MQTT !")
text.WriteAll()
# Subscribing in on_connect() means that if we lose the connection and
# reconnect then subscriptions will be renewed.
client.unsubscribe("$SYS/#")
client.subscribe(topic)
# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
global unit_temp
top=msg.topic[len(topic)-1:].strip()
print(top+" : "+str(msg.payload))
if top == "date" :
text.UpdateText("Date", msg.payload, font_path=font_path_bold)
if top == "unit" :
unit_temp = msg.payload
if top == "value" :
val = decimal.Decimal(msg.payload)
txt = "T= %.1f" % val + unit_temp.decode("utf-8")
text.UpdateText("Temperature", txt)
text.WriteAll()
########
# Main #
########
#Connect to MQTT broker and loop...
mqtt_client = mqtt.Client(mqtt_client_id, clean_session=False)
mqtt_client.username_pw_set(mqtt_auth['username'], mqtt_auth['password'])
mqtt_client.on_connect = on_connect
mqtt_client.on_message = on_message
mqtt_client.connect(mqtt_server, mqtt_port, 60)
mqtt_client.loop_forever()