refactoring

This commit is contained in:
2015-06-01 17:03:23 +02:00
parent 69e8361ede
commit 777e225d0b
2 changed files with 119 additions and 96 deletions

View File

@ -1,77 +1,107 @@
import sys
from time import strftime, gmtime
from twisted.internet import reactor from twisted.internet import reactor
from twisted.web.server import Site from twisted.web.server import Site
from twisted.web.resource import Resource from twisted.web.resource import Resource
from twisted.web.static import File from twisted.web.static import File
import paho.mqtt.client as mqtt #import paho.mqtt.client as mqtt
import json #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'
class HelloWorld(MyResource):
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 isLeaf = True
def render_GET(self, request): def render_GET(self, request):
return "Hello world!" return "Hello world!"
class Switch(Resource): class SwitchCommand(MyResource):
isLeaf = True isLeaf = True
def render_GET(self, request): def render_GET(self, request):
target = request.args['target'][0] res = "ERR"
switchState = request.args['state'][0] try:
send_message(target, switchState) target = request.args['target'][0]
return "OK" switchState = request.args['state'][0]
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 isLeaf = False
def __init__(self, target):
self.target = target
def render_GET(self, request): def render_GET(self, request):
t = {'kitchen':0, 'oven':1, 'laundry':2} state = "ERR"
return state[t[self.target]] 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 = mqtt.Client()
mqttClient.on_message = on_message #mqttClient.on_message = on_message
mqttClient.connect("mqttbroker", 1883, 60) #mqttClient.connect("mqttbroker", 1883, 60)
mqttClient.subscribe("IoT/Status/RelayBox") #mqttClient.subscribe("IoT/Status/RelayBox")
mqttClient.loop_start() #mqttClient.loop_start()
root = Resource() root = Resource()
root.putChild("", File("index.html")) root.putChild("", File("index.html"))
root.putChild("Hello", HelloWorld()) root.putChild("Hello", HelloWorld())
root.putChild("switch", Switch()) root.putChild("switchCommand", SwitchCommand())
root.putChild("oven", Status("oven")) root.putChild("switchStatus", SwitchStatus())
root.putChild("kitchen", Status("kitchen"))
root.putChild("laundry", Status("laundry"))
factory = Site(root, logPath='/tmp/laundryServer.log') factory = Site(root, logPath='laundryServer.log')
reactor.listenTCP(8080, factory) reactor.listenTCP(8080, factory)
reactor.run() reactor.run()

View File

@ -7,62 +7,53 @@
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script> <script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<script> <script>
$("document").ready(function() { $("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(); $("#target").hide();
$("#button").click(function() { $("#button").click(function() {
var $v = "nix"; var v = ($("#flip-checkbox-1").is(":checked")) ? 1 : 0;
if ($("#flip-checkbox-1").is(":checked")) { var w = switchMapping[$("#target").text()]['index'];
$v = "on";
} else {
$v = "off";
}
var $w = $("#target").text();
$.ajax({ $.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() { $(".switchlink").click(function() {
var $v = $(this).attr("id"); var v = $(this).attr("id");
var $w = $("span:first", this).text(); var w = $("span:first", this).text();
$("#dialogTitle").text($w); $("#dialogTitle").text(w);
$("#target").text($v); $("#target").text(v);
}); });
(function worker1() { function updateState() {
$.ajax({ for (var key in switchMapping) {
url: 'http://172.16.2.15:8080/kitchen', $.ajax({
success: function(data) { async:false,
$('#stateKueche').text(data); url: 'http://' + serverAddress + '/switchStatus?target=' + switchMapping[key]['index'],
}, success: function(data) {
complete: function() { $('#state' + key).text(data);
// Schedule the next request when the current one's complete }
setTimeout(worker1, 1000); });
} }
}); setTimeout(updateState, 1000);
})(); }
(function worker2() { updateState();
$.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);
}
});
})();
}); });
</script> </script>
<style> <style>
@ -77,10 +68,12 @@
<h1>RelayBox</h1> <h1>RelayBox</h1>
</div> </div>
<div data-role="main" class="ui-content"> <div data-role="main" class="ui-content">
<ul data-role="listview" data-inset="true" data-count-theme="b"> <ul id="switchlist" data-role="listview" data-inset="true" data-count-theme="b">
<li><a class="switchlink" id="kitchen" href="#dialog?switch=kitchen"><span>K&uuml;che Rest</span> <span id="stateKueche" class="ui-li-count">on</span></a></li> <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=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&uuml;che</span> <span id="stateWaschkueche" class="ui-li-count">off</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&uuml;che</span> <span id="stateWaschkueche" class="ui-li-count">off</span></a></li>
-->
</ul> </ul>
</div> </div>
</div> </div>