unhb-mqtt/unhb-mqtt.py

142 lines
5.3 KiB
Python
Raw Permalink Normal View History

2018-12-10 17:17:32 +01:00
#!/usr/bin/python
import paho.mqtt.client as mqtt
import json
import time
import pyqrcode
2019-08-18 16:23:01 +02:00
import subprocess
2018-12-10 17:17:32 +01:00
from PIL import Image, ImageDraw, ImageFont
import cups
from matrix_client.client import MatrixClient
2019-08-18 16:23:01 +02:00
from unhb_mqtt_config import *
2018-12-10 17:17:32 +01:00
2018-12-10 17:57:15 +01:00
# Druckerinitialisierung
2018-12-10 17:17:32 +01:00
conn = cups.Connection()
printers = conn.getPrinters()
2018-12-10 17:57:15 +01:00
# formatiert uns hex in der notation 0x0000
2018-12-10 17:17:32 +01:00
def padhexa(s):
return '0x' + s[2:].zfill(4)
2018-12-10 17:57:15 +01:00
def create_qrcode(newcode, hexid):
2018-12-10 17:17:32 +01:00
qrobj = pyqrcode.create(newcode)
2018-12-10 17:31:42 +01:00
with open('qr.png', 'wb') as f:
2018-12-10 17:17:32 +01:00
qrobj.png(f, scale=10)
bg = Image.open('bg.png')
2018-12-10 17:31:42 +01:00
img = Image.open('qr.png')
2018-12-10 17:17:32 +01:00
width, height = img.size
logo_size = 140
logo = Image.open('unhb.png')
xmin = ymin = int((width / 2) - (logo_size / 2))
xmax = ymax = int((width / 2) + (logo_size / 2))
logo = logo.resize((xmax - xmin, ymax - ymin))
img.paste(logo, (xmin, ymin, xmax, ymax))
fnt = ImageFont.truetype('font.ttf', 28)
d = ImageDraw.Draw(img)
d.text((width / 2 - 55, height - 40), hexid, font=fnt)
bg.paste(img, (205, 0, 615, 410))
outimage = "./qrcodes/" + hexid + ".png"
bg.save(outimage)
2018-12-10 17:57:15 +01:00
print("qrcode erfolgreich generiert: " + newcode)
2018-12-10 17:31:42 +01:00
# druckername hardcoded!
conn.printFile("gk420d", outimage, "Labelausdruck", {})
2018-12-10 17:17:32 +01:00
def get_lastkey():
with open("/home/pi/lastkey.txt", "r") as lastkeyinfile:
last_int = int(lastkeyinfile.read().rstrip(), 16)
return lastkey
space_obj = json.loads(space_json)
2019-08-18 16:23:01 +02:00
with open("spaceapi.json", "w") as write_file:
json.dump(space_obj, write_file, sort_keys=True)
print(json.dumps(space_obj, sort_keys=True, indent=4))
2018-12-10 17:17:32 +01:00
# 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))
# Subscribing in on_connect() means that if we lose the connection and
# reconnect then subscriptions will be renewed.
client.subscribe("/UHB/#")
def spaceapi():
print("funktion spaceapi go!")
json.dumps(space_json)
print(y["api"])
write_file = open("spaceapi.json", "w")
json.dump(space_json, write_file)
print("file written")
# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
# print(msg.topic+" "+str(msg.payload))
print("Received message '" + str(msg.payload) + "' on topic '" + msg.topic + "' with QoS " + str(msg.qos))
2019-08-18 16:23:01 +02:00
print("current Status of space: " + str(space_obj["state"]["open"]))
2018-12-11 12:50:59 +01:00
if msg.topic == '/UHB/status/public':
2019-08-18 16:23:01 +02:00
if (msg.payload == "0" and not space_obj["state"]["open"]):
2018-12-10 17:17:32 +01:00
# space_obj["state"] = {u'open': True,u'lastchange': time.time()}
space_obj["state"]["open"] = True
space_obj["state"]["lastchange"] = time.time()
print(json.dumps(space_obj, sort_keys=True, indent=4))
with open("spaceapi.json", "w") as write_file:
json.dump(space_obj, write_file, sort_keys=True)
matrix_room.send_state_event("m.room.avatar", matrix_open_json)
2019-08-18 16:23:01 +02:00
matrix_room.send_text("Der Space ist jetzt offen.")
elif (msg.payload == "1" and space_obj["state"]["open"] ):
2018-12-10 17:17:32 +01:00
# space_obj["state"] = {b'open': False,u'lastchange': time.time()}
space_obj["state"]["open"] = False
space_obj["state"]["lastchange"] = time.time()
with open("spaceapi.json", "w") as write_file:
json.dump(space_obj, write_file, sort_keys=True)
print(json.dumps(space_obj, sort_keys=True, indent=4))
matrix_room.send_state_event("m.room.avatar", matrix_closed_json)
2019-08-18 16:23:01 +02:00
matrix_room.send_text("Der Space ist jetzt geschlossen.")
p = subprocess.Popen('/home/amdash/fritzPower/allOff.sh')
p.wait()
2018-12-10 17:17:32 +01:00
if msg.topic == '/UHB/label/create':
new_keys = int(msg.payload)
print("anzahl neu zu generierender label: " + str(new_keys))
2020-06-20 21:17:02 +02:00
with open("/home/pi/unhb-mqtt/lastkey.txt", "r") as infile:
2018-12-10 17:17:32 +01:00
last_label_key = int(infile.read().rstrip(), 16)
print("bisher generierte labels: " + str(last_label_key))
print("letzte gedruckte label id: " + padhexa(hex(last_label_key)))
nextkey = last_label_key + 1
print("naechste freie label id: " + padhexa(hex(nextkey)))
for i in range(nextkey, nextkey + new_keys):
hexkey = padhexa(hex(i))
urldings = "https://inv.unhb.de/" + hexkey
create_qrcode(urldings, hexkey)
2020-06-20 21:17:02 +02:00
with open("/home/pi/unhb-mqtt/lastkey.txt", "w") as outfile:
2018-12-10 17:17:32 +01:00
outfile.write(hexkey)
# Prepare MQTT client
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect("localhost", 1883, 60)
# Prepare Matrix Client
matrix_client = MatrixClient(matrix_server)
matrix_client.login_with_password_no_sync(matrix_bot_user, matrix_bot_passwd)
matrix_room = matrix_client.join_room(matrix_roomid)
matrix_room.send_state_event("m.room.avatar", matrix_unk_json)
2019-08-18 16:23:01 +02:00
matrix_room.send_text("Ich wurde neu gestartet... kein Plan ob der Raum gerade offen oder geschlossen ist.")
2018-12-10 17:17:32 +01:00
# Blocking call that processes network traffic, dispatches callbacks and
# handles reconnecting.
# Other loop*() functions are available that give a threaded interface and a
# manual interface.
client.loop_forever()