-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
executable file
·261 lines (216 loc) · 6.97 KB
/
main.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
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
#!/usr/bin/env python
import os
import subprocess
import logging
logging.basicConfig(filename='run/lightware.log', level=logging.INFO, format='%(asctime)s %(message)s', datefmt='%d.%m.%Y %H:%M:%S ')
from flask_cors import CORS, cross_origin
from flask_debugtoolbar import DebugToolbarExtension
from flask import Flask, jsonify, request, make_response, render_template
application = Flask(__name__)
application.debug = False
cors = CORS(application, resources={r"/api/*": {"origins": "*"}})
application.config['SECRET_KEY'] = 'j1h9syenwksu2nHanzPakq63sdfhshdfHjH45dfGFDjd'
toolbar = DebugToolbarExtension(application)
_version = '1.0.0'
LIGHTWARE_BASE_PATH = '/sys/class/gpio'
LIGHTWARE_EXPORT_PATH = LIGHTWARE_BASE_PATH + '/export'
LIGHTWARE_UNEXPORT_PATH = LIGHTWARE_BASE_PATH + '/unexport'
LIGHTWARE_GPIO_PATH = LIGHTWARE_BASE_PATH + '/gpio{0}'
LIGHTWARE_GPIO_DIRECTION_PATH = LIGHTWARE_GPIO_PATH + '/direction'
LIGHTWARE_GPIO_EDGE_PATH = LIGHTWARE_GPIO_PATH + '/edge'
LIGHTWARE_GPIO_VALUE_PATH = LIGHTWARE_GPIO_PATH + '/value'
LIGHTWARE_GPIO_ACTIVE_LOW_PATH = LIGHTWARE_GPIO_PATH + '/active_low'
LIGHTWARE_GPIO_VALUE_LOW = '0'
LIGHTWARE_GPIO_VALUE_HIGH = '1'
class LightWare:
def __init__(self, num, direction='out', read_only=False):
self._number = num
self._direction = direction
self._read_only = read_only
if not self._read_only:
if not self._check_pin_export():
with open(LIGHTWARE_EXPORT_PATH, 'w') as _f_ex:
_f_ex.write('{0}'.format(self._number))
with open(self._lightware_gpio_direction_path(), 'w') as f:
f.write(direction)
f.close()
try:
self._f_value = open(self._lightware_gpio_value_path(), 'r+')
except FileNotFoundError:
self._f_value = 0
def _lightware_gpio_direction_path(self):
return LIGHTWARE_GPIO_DIRECTION_PATH.format(self._number)
def _lightware_gpio_value_path(self):
return LIGHTWARE_GPIO_VALUE_PATH.format(self._number)
def _check_pin_export(self):
gpio_path = LIGHTWARE_GPIO_PATH.format(self._number)
return os.path.isdir(gpio_path)
def on(self):
self._f_value.write(LIGHTWARE_GPIO_VALUE_HIGH)
self._f_value.seek(0)
self._f_value.close()
def off(self):
self._f_value.write(LIGHTWARE_GPIO_VALUE_LOW)
self._f_value.seek(0)
self._f_value.close()
def read(self):
val = self._f_value.read()
self._f_value.seek(0)
self._f_value.close()
return int(val)
switches_state = {
"switches": {
"5": {
"id": 5,
"name": "Main light",
"state": False,
"color": "purple",
"active": True
},
"6": {
"id": 6,
"name": "Channel 6",
"state": False,
"color": "red",
"active": False
},
"13": {
"id": 13,
"name": "Main light",
"state": False,
"color": "green",
"active": True
},
"19": {
"id": 19,
"name": "LED Strip",
"state": False,
"color": "yellow",
"active": True
},
"26": {
"id": 26,
"name": "Channel 26",
"state": False,
"color": "orange",
"active": False
},
"12": {
"id": 12,
"name": "Channel 12",
"state": False,
"color": "violet",
"active": False
},
"16": {
"id": 16,
"name": "Channel 16",
"state": False,
"color": "pink",
"active": False
},
"20": {
"id": 20,
"name": "Channel 20",
"state": False,
"color": "brown",
"active": False
}
},
"api": {
"version": _version,
"status": "up",
"errors": None
}
}
dimmer_state = {
"dimmer": {
"1": {
"id": 1,
"name": "Door",
"value": 0,
"active": True
},
"2": {
"id": 2,
"name": "Sofa",
"value": 0,
"active": True
},
"3": {
"id": 3,
"name": "Work zone",
"value": 0,
"active": True
}
},
"api": {
"version": _version,
"status": "up",
"errors": None
}
}
@application.route("/", methods=["GET"])
def index():
return render_template('index.html')
@application.route("/api")
def api():
return jsonify({"api": {"version": "1.0.0"}})
@application.route("/api/channel/status", methods=["GET"])
def get_channel_status():
return jsonify(switches_state)
@application.route("/api/channel/set/state", methods=["POST"])
@cross_origin()
def set_state():
if not request.is_json:
return jsonify({"msg": "Missing JSON in request"}), 400
_params = request.get_json()
_channel = _params.get("channel", None)
_state = _params.get("state", None)
ret = {"channel": _channel, "state": _state}
switches_state['switches']['{}'.format(_channel)]['state'] = _state
if _state:
LightWare(_channel).on()
else:
LightWare(_channel).off()
return jsonify(ret), 200
@application.route("/api/channel/<int:channel>/<int:state>}", methods=["POST", "GET"])
@cross_origin()
def set_channel_state(channel, state):
if state == 1:
LightWare(channel).on()
else:
LightWare(channel).off()
return jsonify('ok'), 200
@application.route("/api/dimmer/status", methods=["GET"])
def get_dimmer_status():
return jsonify(dimmer_state)
@application.route("/api/dimmer/set/state", methods=["POST"])
def set_dimmer_state():
if not request.is_json:
return jsonify({"msg": "Missing JSON in request"}), 400
_params = request.get_json()
_dimmer = _params.get("dimmer", None)
_value = _params.get("value", None)
if _value is None:
return jsonify({"msg": "Missing value"}), 400
if _value < 0 or _value > 100:
return jsonify({"msg": "Out of range"}), 400
ret = {"dimmer": _dimmer, "value": _value}
dimmer_state['dimmer']['{}'.format(_dimmer)]['value'] = _value
_value = 100 - _value
try:
subprocess.call(['dimmer.py', str(_dimmer), str(_value)], cwd='/home/projects/lightware')
logging.info('set dimmer #{0} value to {1} %'.format(_dimmer, _value))
return jsonify(ret), 200
except Exception as e:
logging.warning('Error: ' + str(e))
return make_response(jsonify({"msg": "Server error"}), 500)
@application.errorhandler(404)
def not_found(error):
return make_response(jsonify({"msg": "Resource not found"}), 404)
@application.errorhandler(405)
def handle_bad_request(error):
return make_response(jsonify({"msg": "Method not allowed"}), 405)
if __name__ == "__main__":
application.run(host='0.0.0.0')