-
Notifications
You must be signed in to change notification settings - Fork 0
/
RequestHandlers.py
96 lines (78 loc) · 3.17 KB
/
RequestHandlers.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import tornado.web
import tornado.websocket
import time
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(23, GPIO.OUT)
GPIO.setup(22, GPIO.OUT)
from RepeatEvery import RepeatEvery
from ToggleGlowbar import ToggleGlowbar
from TemperatureReader import TemperatureReader
from MessageFactory import MessageFactory
from MessageProducer import MessageProducerFactory
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.render("temperature_demo.html")
class OnHandler(tornado.web.RequestHandler):
def get(self):
GPIO.output(22, True)
self.write("On")
class OffHandler(tornado.web.RequestHandler):
def get(self):
GPIO.output(22, False)
GPIO.output(23, False)
self.write("Off")
class TemperatureSocketHandler(tornado.websocket.WebSocketHandler):
__waiters = set()
thread = set()
stepTemperature = 0
stepDuration = 0
temperatureControlOverriden = False
action = set()
state = False
lastState = False
currentTemperature = 0
def __init__(self, application, request, **kwargs):
self.thread = RepeatEvery(1, self.__send_temperatures)
tornado.websocket.WebSocketHandler.__init__(self, application, request, **kwargs)
def on_message(self, message):
messageObject = MessageFactory.get_message(message)
messageObject.processMessage(self)
messageProducerObject = MessageProducerFactory.get_message(self.action)
print(self.action)
messageProducerObject.produceMessage(self)
def open(self):
TemperatureSocketHandler.__waiters.add(self)
def on_close(self):
TemperatureSocketHandler.__waiters.remove(self)
print('Connection Closed')
if len(TemperatureSocketHandler.__waiters) == 0:
print('No more clients. Stop Thread.')
self.thread.stop()
def __send_temperatures(self):
for waiter in self.__waiters:
try:
self.currentTemperature = TemperatureReader().read_temp()
if self.currentTemperature >= self.stepTemperature:
self.state = False
if self.currentTemperature < self.stepTemperature:
self.state = True
if len(self.__waiters) == 0:
break
messageProducerObject = MessageProducerFactory.get_message('state_change')
if (self.lastState != self.state):
messageProducerObject.produceMessage(self)
if not self.temperatureControlOverriden:
self.toggleGPIO()
self.lastState = self.state
messageProducerObject = MessageProducerFactory.get_message('send_temperature')
messageProducerObject.produceMessage(self)
except AttributeError as e:
print("Error sending temp", e)
break
def toggleGPIO(self):
if self.state == True:
ToggleGlowbar().start()
else:
GPIO.output(23, False) # gas
#GPIO.output(23, self.state)