79 lines
1.9 KiB
Python
79 lines
1.9 KiB
Python
from twisted.internet import reactor
|
|
from twisted.web.server import Site
|
|
from twisted.web.resource import Resource
|
|
from twisted.web.static import File
|
|
|
|
import paho.mqtt.client as mqtt
|
|
import json
|
|
|
|
|
|
|
|
state = ['x', 'x', 'x', 'x', 'x', 'x', 'x', 'x']
|
|
|
|
|
|
def on_message(client, userdata, msg):
|
|
j = json.loads(msg.payload)
|
|
ss = j['data']['switchStates']
|
|
for s in ss:
|
|
if s['feedbackState'] == 0:
|
|
state[s['index']] = 'aus'
|
|
elif s['state'] == 1:
|
|
state[s['index']] = 'an'
|
|
else:
|
|
state[s['index']] = 'unbekannt'
|
|
|
|
|
|
def send_message(target, switchState):
|
|
t = {'kitchen':0, 'oven':1, 'laundry':2}
|
|
# command = "switch %s %s" % [target, switchState]
|
|
command = "switch " + str(t[target]) + " " + str(switchState)
|
|
mqttClient.publish('IoT/Command/RelayBox', command)
|
|
|
|
class HelloWorld(Resource):
|
|
isLeaf = True
|
|
|
|
def render_GET(self, request):
|
|
return "Hello world!"
|
|
|
|
|
|
class Switch(Resource):
|
|
isLeaf = True
|
|
|
|
def render_GET(self, request):
|
|
target = request.args['target'][0]
|
|
switchState = request.args['state'][0]
|
|
send_message(target, switchState)
|
|
return "OK"
|
|
|
|
|
|
class Status(Resource):
|
|
isLeaf = False
|
|
|
|
def __init__(self, target):
|
|
self.target = target
|
|
|
|
def render_GET(self, request):
|
|
t = {'kitchen':0, 'oven':1, 'laundry':2}
|
|
return state[t[self.target]]
|
|
|
|
|
|
mqttClient = mqtt.Client()
|
|
mqttClient.on_message = on_message
|
|
mqttClient.connect("mqttbroker", 1883, 60)
|
|
mqttClient.subscribe("IoT/Status/RelayBox")
|
|
mqttClient.loop_start()
|
|
|
|
root = Resource()
|
|
root.putChild("", File("index.html"))
|
|
root.putChild("Hello", HelloWorld())
|
|
root.putChild("switch", Switch())
|
|
root.putChild("oven", Status("oven"))
|
|
root.putChild("kitchen", Status("kitchen"))
|
|
root.putChild("laundry", Status("laundry"))
|
|
|
|
factory = Site(root, logPath='/tmp/laundryServer.log')
|
|
|
|
reactor.listenTCP(8080, factory)
|
|
reactor.run()
|
|
|