-
Notifications
You must be signed in to change notification settings - Fork 4
/
controller.py
161 lines (136 loc) · 5.66 KB
/
controller.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
import asyncio
import logging
from collections import deque
from time import time
from aiohttp import web
import json
import sockjs
import interfaces
import event
from common import app, components
logger = logging.getLogger(__name__)
class Controller(interfaces.Component, interfaces.Runnable):
def __init__(self, name, sensor, actor, logic, agitator=None, targetTemp=0.0, initiallyEnabled=False):
self.name = name
self._enabled = initiallyEnabled
self._autoMode = False
self.sensor = sensor
self.actor = actor
self.agitator = agitator
self.targetTemp = targetTemp
self.logic = logic
self.timestamp_history = deque(maxlen=100)
self.power_history = deque(maxlen=100)
self.temp_history = deque(maxlen=100)
self.setpoint_history = deque(maxlen=100)
sockjs.add_endpoint(app, prefix='/controllers/%s/ws'%self.name, name='%s-ws'%self.name, handler=self.websocket_handler)
asyncio.ensure_future(self.run())
def callback(self, endpoint, data):
includeSetpoint = False
if endpoint in ['state', 'enabled']:
self.enabled = bool(data)
self.actor.updatePower(0.0)
logger.info("Setting %s ctrl enabled to %r"%(self.name, bool(data)))
elif endpoint == 'automatic':
self.actor.updatePower(0.0)
self.automatic = bool(data)
logger.info("Setting %s ctrl automatic to %r"%(self.name, bool(self._autoMode)))
elif endpoint == 'setpoint':
self.setSetpoint(float(data))
includeSetpoint = True
elif endpoint == 'power':
self.actor.updatePower(float(data))
logger.info("Setting %s ctrl power to %f"%(self.name, float(data)))
elif endpoint == 'agitating':
pwr = 100*float(data)
logger.info("Setting %s ctrl automatic to %r"%(self.name, pwr))
self.agitator.updatePower(pwr)
else:
self.logic.callback(endpoint, data)
#logger.warning("Unknown type/endpoint for Contorller %s"%endpoint)
self.broadcastDetails(includeSetpoint)
def setSetpoint(self, setpoint):
self.targetTemp = setpoint
event.notify(event.Event(source=self.name, endpoint='setpoint', data=self.targetTemp))
def broadcastDetails(self, includeSetpoint=False):
manager = sockjs.get_manager('%s-ws'%self.name, app)
details = self.getDetails()
if not includeSetpoint:
details.pop('setpoint', None)
manager.broadcast(details)
@property
def enabled(self):
return self._enabled
@enabled.setter
def enabled(self, state):
self._enabled = state
if not self._enabled:
self.actor.updatePower(0.0)
event.notify(event.Event(source=self.name, endpoint='enabled', data=self.enabled))
@property
def automatic(self):
return self._autoMode
@automatic.setter
def automatic(self, state):
self._autoMode = state
def getDetails(self):
details = {
'temperature': self.sensor.temp(),
'setpoint': self.targetTemp,
'automatic': self.automatic,
'name': self.name,
'power': self.actor.getPower(),
'agitating': self.agitator.getPower()>0 if self.agitator else None,
'enabled': self.enabled,
'wsUrl': '/controllers/%s/ws'%self.name
}
return details
async def run(self):
await asyncio.sleep(5)
while True:
output = self.actor.getPower()
if self.enabled:
if self._autoMode:
output = self.logic.calc(self.sensor.temp(), self.targetTemp)
self.actor.updatePower(output)
self.broadcastDetails()
self.timestamp_history.append(time())
self.power_history.append(output)
self.temp_history.append(self.sensor.temp())
self.setpoint_history.append(self.targetTemp)
await asyncio.sleep(10)
async def websocket_handler(self, msg, session):
if msg.type == sockjs.MSG_OPEN:
self.broadcastDetails()
if msg.type == sockjs.MSG_MESSAGE:
data = json.loads(msg.data)
for endpoint, value in data.items():
self.callback(endpoint, value)
pass
async def listControllers(request):
res=request.app.router['controllerDetail']
controllers = {name: {'url': str(request.url.with_path(str(res.url_for(name=name))))} for (name, component) in components.items() if isinstance(component, Controller)}
return web.json_response(controllers)
async def controllerDetail(request):
try:
controllerName = request.match_info['name']
details = components[controllerName].getDetails()
return web.json_response(details)
except KeyError as e:
raise web.HTTPNotFound(reason='Unknown controller %s'%str(e))
async def dataHistory(request):
try:
controllerName = request.match_info['name']
controller = components[controllerName]
data = {
'label': list(controller.timestamp_history),
'temperature': list(controller.temp_history),
'power': list(controller.power_history),
'setpoint': list(controller.setpoint_history)
}
return web.json_response(data)
except KeyError as e:
raise web.HTTPNotFound(reason='Unknown controller %s'%str(e))
app.router.add_get('/controllers', listControllers)
app.router.add_get('/controllers/{name}', controllerDetail, name='controllerDetail')
app.router.add_get('/controllers/{name}/datahistory', dataHistory, name='dataHistory')