mqtt-to-flipdot/mqtt-to-flipdot.py

115 lines
3.7 KiB
Python

#!/usr/bin/env python3
import time
import paho.mqtt.client as mqtt
from FlipdotSender import FlipdotSender
import time
from hangman import Hangman
global mode
mode="standby"
global gametimeout
gametimeout=0
def on_connect(client, userdata, flags, rc):
print("Connected with result code " + str(rc))
client.subscribe("raum2/flipdot/#")
#client.subscribe("raum2/flipdot/text")
#client.subscribe("raum2/flipdot/scroll")
#client.subscribe("raum2/flipdot/image")
def on_message(client, userdata, msg):
print(msg.topic + " " + str(msg.payload.decode("utf-8")))
global mode
global gametimeout
if mode=="standby":
gametimeout=0
if msg.topic == "raum2/flipdot/scroll/set":
payload = msg.payload.decode("utf-8")
if len(payload)>0 and (payload[0]).isdigit():
speed = int(payload[0])
text = payload[1:]
else:
speed = 3
text = payload
flipdot.send_marquee(text, speed)
if msg.topic == "raum2/flipdot/text/set":
payload = msg.payload.decode("utf-8")
if len(payload)>0 and payload[0]=='~':
payload=payload[1:] #remove first char
flipdot.send_text(payload,25) #send_text with animation
flipdot.send_text(payload) #without animation
if msg.topic == "raum2/flipdot/textFull/set":
payload = msg.payload.decode("utf-8")
if len(payload)>0 and payload[0]=='~':
payload=payload[1:]
flipdot.send_textFull(payload,50)
flipdot.send_textFull(payload)
if msg.topic == "raum2/flipdot/image/set":
payload = msg.payload.decode("utf-8")
print(payload)
flipdot.send_bytes(payload)
if msg.topic == "raum2/flipdot/hangman/set":
payload = msg.payload.decode("utf-8")
if payload=="#start":
hangman.setup()
gametimeout=int(round(time.time() * 1000))
client.publish("raum2/flipdot/hangman","started")
mode="hangman"
elif (mode=="hangman") and (len(payload)>0): #try entered character
gametimeout=int(round(time.time() * 1000))
trychar=payload[-1]
gamestatus=hangman.step(trychar)
client.publish("raum2/flipdot/hangman","char="+trychar.upper())
if gamestatus!=1: #game has ended
mode="standby"
if gamestatus==2: #gameover
client.publish("raum2/flipdot/hangman","gameover")
elif gamestatus==3: #won
client.publish("raum2/flipdot/hangman","won")
elif gamestatus==0: #ended in another way
client.publish("raum2/flipdot/hangman","ended")
if payload=="#stop":
mode="standby"
client.publish("raum2/flipdot/hangman","ended")
flipdot = FlipdotSender("::1", 2323)
hangman= Hangman("::1", 2323,flipdot)
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect("raum.ctdo.de", 1883, 60)
client.loop_start()
while True:
millis = int(round(time.time() * 1000))
if gametimeout!=0:
if millis-120000 > gametimeout: #timeout
print("Game Timeout")
mode="standby"
gametimeout=0
time.sleep(2)