refactoring
This commit is contained in:
110
LaundryServer.py
110
LaundryServer.py
@ -1,77 +1,107 @@
|
||||
import sys
|
||||
from time import strftime, gmtime
|
||||
|
||||
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
|
||||
#import paho.mqtt.client as mqtt
|
||||
#import json
|
||||
|
||||
logfile = 'laundry.log'
|
||||
|
||||
loadedSwitchStates = ['x0', 'x1', 'x2', 'x3', 'x4', 'x5', 'x6', 'x7']
|
||||
|
||||
|
||||
#def on_message(client, userdata, msg):
|
||||
# j = json.loads(msg.payload)
|
||||
# ss = j['data']['switchStates']
|
||||
# for s in ss:
|
||||
# if s['feedbackState'] == 0:
|
||||
# loadedSwitchStates[s['index']] = 'aus'
|
||||
# elif s['state'] == 1:
|
||||
# loadedSwitchStates[s['index']] = 'an'
|
||||
# else:
|
||||
# loadedSwitchStates[s['index']] = 'unbekannt'
|
||||
|
||||
|
||||
|
||||
state = ['x', 'x', 'x', 'x', 'x', 'x', 'x', 'x']
|
||||
class MyResource(Resource):
|
||||
def log(self, m):
|
||||
t = strftime("%d %b %Y %H:%M:%S", gmtime())
|
||||
with open(logfile, 'a') as f:
|
||||
f.write("%s %s\n" % (t, m))
|
||||
|
||||
def send_message(self, target, switchState):
|
||||
try:
|
||||
t = int(target)
|
||||
s = int(switchState)
|
||||
if s not in [0, 1]:
|
||||
raise ValueError('illegal switchState ' + switchState)
|
||||
if t < 0 or t >= len(loadedSwitchStates):
|
||||
raise ValueError('illegal target ' + target)
|
||||
command = "switch %d %d" % (t, s)
|
||||
#mqttClient.publish('IoT/Command/RelayBox', command)
|
||||
self.log(command)
|
||||
except ValueError, e:
|
||||
self.log("ValueError in send_message: " + str(e))
|
||||
|
||||
|
||||
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):
|
||||
class HelloWorld(MyResource):
|
||||
isLeaf = True
|
||||
|
||||
def render_GET(self, request):
|
||||
return "Hello world!"
|
||||
|
||||
|
||||
class Switch(Resource):
|
||||
class SwitchCommand(MyResource):
|
||||
isLeaf = True
|
||||
|
||||
def render_GET(self, request):
|
||||
res = "ERR"
|
||||
try:
|
||||
target = request.args['target'][0]
|
||||
switchState = request.args['state'][0]
|
||||
send_message(target, switchState)
|
||||
return "OK"
|
||||
self.send_message(target, switchState)
|
||||
res = "OK"
|
||||
except KeyError, e:
|
||||
self.log("KeyError in SwitchCommand, render_GET: " + str(e))
|
||||
return res
|
||||
|
||||
|
||||
class Status(Resource):
|
||||
class SwitchStatus(MyResource):
|
||||
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]]
|
||||
state = "ERR"
|
||||
try:
|
||||
target = request.args['target'][0]
|
||||
t = int(target)
|
||||
state = loadedSwitchStates[t]
|
||||
except ValueError, e:
|
||||
self.log("ValueError in SwitchStatus, render_GET: " + str(e))
|
||||
except KeyError, e:
|
||||
self.log("KeyError in SwitchStatus, render_GET: " + str(e))
|
||||
except IndexError, e:
|
||||
self.log("KeyError in SwitchStatus, render_GET: " + str(e))
|
||||
return state
|
||||
|
||||
|
||||
mqttClient = mqtt.Client()
|
||||
mqttClient.on_message = on_message
|
||||
mqttClient.connect("mqttbroker", 1883, 60)
|
||||
mqttClient.subscribe("IoT/Status/RelayBox")
|
||||
mqttClient.loop_start()
|
||||
#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"))
|
||||
root.putChild("switchCommand", SwitchCommand())
|
||||
root.putChild("switchStatus", SwitchStatus())
|
||||
|
||||
factory = Site(root, logPath='/tmp/laundryServer.log')
|
||||
factory = Site(root, logPath='laundryServer.log')
|
||||
|
||||
reactor.listenTCP(8080, factory)
|
||||
reactor.run()
|
||||
|
87
index.html
87
index.html
@ -7,62 +7,53 @@
|
||||
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
|
||||
<script>
|
||||
$("document").ready(function() {
|
||||
var serverAddress = '127.0.0.1:8080';
|
||||
var switchMapping = {
|
||||
'kitchen': { 'index': 0, 'label': 'Kueche' },
|
||||
'oven': { 'index': 1, 'label': 'Herd' },
|
||||
'laundry': { 'index': 2, 'label': 'Waschkueche' },
|
||||
};
|
||||
var firstListItem = $("li:first", "#switchlist");
|
||||
for (var key in switchMapping) {
|
||||
var newListItem = firstListItem.clone()
|
||||
var href = newListItem.children('a')
|
||||
href.attr('id', 'switch' + key);
|
||||
href.attr('href', '#dialog?switch=' + switchMapping[key]['index'])
|
||||
var span = newListItem.find("#statusEmpty0");
|
||||
span.attr('id', 'state' + key);
|
||||
span = newListItem.find("#labelEmpty0");
|
||||
span.attr('id', 'label' + key);
|
||||
span.text(switchMapping[key]['label']);
|
||||
newListItem.appendTo("#switchlist");
|
||||
}
|
||||
firstListItem.hide();
|
||||
$("#target").hide();
|
||||
$("#button").click(function() {
|
||||
var $v = "nix";
|
||||
if ($("#flip-checkbox-1").is(":checked")) {
|
||||
$v = "on";
|
||||
} else {
|
||||
$v = "off";
|
||||
}
|
||||
var $w = $("#target").text();
|
||||
var v = ($("#flip-checkbox-1").is(":checked")) ? 1 : 0;
|
||||
var w = switchMapping[$("#target").text()]['index'];
|
||||
$.ajax({
|
||||
url: 'http://172.16.2.15:8080/switch?target=' + $w + '&state=' + $v
|
||||
url: 'http://' + serverAddress + '/switchCommand?target=' + w + '&state=' + v
|
||||
});
|
||||
// $("#bla").text($v + $w);
|
||||
});
|
||||
$(".switchlink").click(function() {
|
||||
var $v = $(this).attr("id");
|
||||
var $w = $("span:first", this).text();
|
||||
$("#dialogTitle").text($w);
|
||||
$("#target").text($v);
|
||||
var v = $(this).attr("id");
|
||||
var w = $("span:first", this).text();
|
||||
$("#dialogTitle").text(w);
|
||||
$("#target").text(v);
|
||||
});
|
||||
(function worker1() {
|
||||
function updateState() {
|
||||
for (var key in switchMapping) {
|
||||
$.ajax({
|
||||
url: 'http://172.16.2.15:8080/kitchen',
|
||||
async:false,
|
||||
url: 'http://' + serverAddress + '/switchStatus?target=' + switchMapping[key]['index'],
|
||||
success: function(data) {
|
||||
$('#stateKueche').text(data);
|
||||
},
|
||||
complete: function() {
|
||||
// Schedule the next request when the current one's complete
|
||||
setTimeout(worker1, 1000);
|
||||
$('#state' + key).text(data);
|
||||
}
|
||||
});
|
||||
})();
|
||||
(function worker2() {
|
||||
$.ajax({
|
||||
url: 'http://172.16.2.15:8080/oven',
|
||||
success: function(data) {
|
||||
$('#stateHerd').text(data);
|
||||
},
|
||||
complete: function() {
|
||||
// Schedule the next request when the current one's complete
|
||||
setTimeout(worker2, 1000);
|
||||
}
|
||||
});
|
||||
})();
|
||||
(function worker3() {
|
||||
$.ajax({
|
||||
url: 'http://172.16.2.15:8080/laundry',
|
||||
success: function(data) {
|
||||
$('#stateWaschkueche').text(data);
|
||||
},
|
||||
complete: function() {
|
||||
// Schedule the next request when the current one's complete
|
||||
setTimeout(worker3, 1000);
|
||||
setTimeout(updateState, 1000);
|
||||
}
|
||||
});
|
||||
})();
|
||||
updateState();
|
||||
});
|
||||
</script>
|
||||
<style>
|
||||
@ -77,10 +68,12 @@
|
||||
<h1>RelayBox</h1>
|
||||
</div>
|
||||
<div data-role="main" class="ui-content">
|
||||
<ul data-role="listview" data-inset="true" data-count-theme="b">
|
||||
<li><a class="switchlink" id="kitchen" href="#dialog?switch=kitchen"><span>Küche Rest</span> <span id="stateKueche" class="ui-li-count">on</span></a></li>
|
||||
<li><a class="switchlink" id="oven" href="#dialog?switch=oven"><span>Herd</span> <span id="stateHerd" class="ui-li-count">on</span></a></li>
|
||||
<li><a class="switchlink" id="laundry" href="#dialog?switch=laundry"><span>Waschküche</span> <span id="stateWaschkueche" class="ui-li-count">off</span></a></li>
|
||||
<ul id="switchlist" data-role="listview" data-inset="true" data-count-theme="b">
|
||||
<li><a class="switchlink" id="itemEmpty0" href="#dialog?switch=0"><span id="labelEmpty0">Vorlage</span> <span id="statusEmpty0" class="ui-li-count">on</span></a></li>
|
||||
<!--
|
||||
<li><a class="switchlink" id="oven" href="#dialog?switch=1"><span>Herd</span> <span id="stateHerd" class="ui-li-count">on</span></a></li>
|
||||
<li><a class="switchlink" id="laundry" href="#dialog?switch=2"><span>Waschküche</span> <span id="stateWaschkueche" class="ui-li-count">off</span></a></li>
|
||||
-->
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
|
Reference in New Issue
Block a user