-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
478 lines (366 loc) · 12.8 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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
import re
import ntptime
import network
import gc
import urequests
from machine import ADC, Pin, SoftI2C, Timer
import json
import ssd1306
from time import localtime, mktime, gmtime, sleep, ticks_ms, ticks_diff
from models import ClockodoTask
from render_helpers import TextFormatting, TextScrolling
# APPLICATION STATE
class State:
error: str | None = None
triggered_request = None
selected_task_index = None
active_task = None
active_entry_id = None
timer_started_at: int | None = None
@classmethod
def change_for_clock_start(cls, active_task, entry_id, timer_started_at):
cls.active_task = active_task
cls.active_entry_id = entry_id
cls.timer_started_at = timer_started_at
@classmethod
def change_for_clock_stop(cls):
cls.active_task = None
cls.active_entry_id = None
cls.timer_started_at = None
@classmethod
def change_for_knob_turn(cls, index_value):
cls.selected_task_index = index_value
@classmethod
def change_for_button_push(cls):
if cls.error is not None:
if cls.error == Error.API_REQUEST:
cls.error = None
return
if cls.active_task:
cls.triggered_request = ClockodoRequest.stop_clock
else:
cls.triggered_request = ClockodoRequest.start_clock
class Error:
GENERAL = "GENERAL"
WIFI_CONNECTION = "WIFI_CONNECTION"
CONFIG_READ = "CONFIG_READ"
CONFIG_PARSE = "CONFIG_PARSE"
CONFIG_API = "CONFIG_API"
CONFIG_WIFI = "CONFIG_WIFI"
CONFIG_SERVICE_ID = "CONFIG_SERVICE_ID"
API_REQUEST = "API_REQUEST"
# CONFIG
class Config:
class File:
FILENAME = "config.json"
@classmethod
def read_and_parse(cls):
try:
with open(cls.FILENAME) as file:
return json.load(file)
except OSError:
State.error = Error.CONFIG_READ
except json.JSONDecodeError:
State.error = Error.CONFIG_PARSE
return {}
class Wifi:
essid = None
password = None
api_key = None
api_user = None
wifi = Wifi
tasks = []
@classmethod
def validate(cls):
if not cls.wifi.essid or not cls.wifi.password:
State.error = Error.CONFIG_WIFI
elif not cls.api_key or not cls.api_user:
State.error = Error.CONFIG_API
elif not cls.service_id:
State.error = Error.CONFIG_SERVICE_ID
@classmethod
def load(cls):
config_dict = cls.File.read_and_parse()
cls.api_key = config_dict.get("api_key")
cls.api_user = config_dict.get("api_user")
cls.service_id = config_dict.get("service_id")
cls.wifi.essid = config_dict.get("wifi_essid")
cls.wifi.password = config_dict.get("wifi_password")
cls.tasks = []
config_tasks = config_dict.get("tasks", [])
for task_data in config_tasks:
task = ClockodoTask.from_dict(task_data)
if task is not None:
cls.tasks.append(task)
cls.validate()
# WIFI
class Wifi:
CONNECTION_TIMEOUT = 10000
station_interface = network.WLAN(network.STA_IF)
access_point_interface = network.WLAN(network.AP_IF)
last_connect_at = None
essid = None
password = None
@classmethod
def wait_for_connection(cls):
while not cls.station_interface.isconnected():
diff = ticks_diff(ticks_ms(), cls.last_connect_at)
if diff < cls.CONNECTION_TIMEOUT:
continue
else:
break
if not cls.station_interface.isconnected():
raise
@classmethod
def connect(cls):
if cls.station_interface.isconnected():
return
if not cls.essid or not cls.password:
return
cls.station_interface.active(True)
cls.access_point_interface.active(False)
cls.last_connect_at = ticks_ms()
try:
cls.station_interface.connect(cls.essid, cls.password)
cls.wait_for_connection()
except:
State.error = Error.WIFI_CONNECTION
# PERIPHERALS
class Knob:
MAX_ATTN_VALUE = 4095
GPIO_PIN = 36
scale = MAX_ATTN_VALUE
poti = ADC(Pin(GPIO_PIN))
poti.atten(ADC.ATTN_11DB)
previous_value = 0
@classmethod
def scale_value(cls, value):
return round((cls.scale / 4095) * value)
@classmethod
def value(cls):
read_value = cls.poti.read()
result = cls.scale_value(read_value)
return result
@classmethod
def handle_turn(cls):
current_value = cls.value()
if current_value != cls.previous_value:
cls.previous_value = current_value
State.change_for_knob_turn(current_value)
class Button:
GPIO_PIN = 15
pin = Pin(GPIO_PIN, Pin.IN, Pin.PULL_UP)
previous_value = 1
@classmethod
def handle_push(cls):
current_value = cls.pin.value()
if current_value == 0 and cls.previous_value == 1:
cls.previous_value = 0
State.change_for_button_push()
elif current_value == 1:
cls.previous_value = 1
class Display:
SCL_PIN = 22
SDA_PIN = 21
WIDTH = 128
HEIGHT = 64
CHAR_WIDTH = 8
LINE_HEIGHT = 10
CHARS_PER_LINE = round(WIDTH / CHAR_WIDTH)
scl = Pin(SCL_PIN)
sda = Pin(SDA_PIN)
i2c = SoftI2C(scl=scl, sda=sda)
oled = ssd1306.SSD1306_I2C(WIDTH, HEIGHT, i2c)
scroll_timer = Timer(0).init(
period=500, mode=Timer.PERIODIC, callback=lambda _: TextScrolling.scroll()
)
@classmethod
def wrapped_text(cls, text, start_line=0, max_line=None):
text_segments = TextFormatting.split_for_wrapping(text, cls.CHARS_PER_LINE)
for i, segment in enumerate(text_segments):
position = (start_line + i) * cls.LINE_HEIGHT
if max_line is None or position <= max_line * cls.LINE_HEIGHT:
cls.oled.text(segment, 0, position)
else:
break
@classmethod
def centered_text(cls, text, line):
margin_left = 0
text_length = len(text)
if text_length < cls.CHARS_PER_LINE:
margin_left = round((cls.WIDTH - text_length * cls.CHAR_WIDTH) / 2)
cls.oled.text(text, margin_left, line * cls.LINE_HEIGHT)
@classmethod
def text(cls, text, line):
cls.oled.text(text, 0, line * cls.LINE_HEIGHT)
@classmethod
def render_error(cls, error):
text_for_error = {
Error.GENERAL: "Error!",
Error.WIFI_CONNECTION: "WIFI connection error!",
Error.API_REQUEST: "API request failed!",
Error.CONFIG_READ: "Config read error!",
Error.CONFIG_PARSE: "Config parse error!",
Error.CONFIG_WIFI: "Please configure WIFI credentials!",
Error.CONFIG_API: "Please configure API credentials!",
Error.CONFIG_SERVICE_ID: "Please configure a service ID!",
}
text = text_for_error[error]
if len(text) < cls.CHARS_PER_LINE:
cls.centered_text(text, 3)
else:
cls.wrapped_text(text, 2)
@classmethod
def render(cls):
cls.oled.fill(0)
if State.error is not None:
cls.render_error(State.error)
elif State.triggered_request is not None:
cls.centered_text("...", 2)
elif State.active_task is not None and State.timer_started_at is not None:
now = mktime(gmtime())
seconds_elapsed = now - State.timer_started_at
timer_text = TextFormatting.format_time(seconds_elapsed)
task_name = State.active_task.name
text, is_scrolling = TextScrolling.maybe_scroll(
task_name, cls.CHARS_PER_LINE
)
if is_scrolling:
cls.text(text, 0)
else:
cls.centered_text(text, 0)
cls.centered_text("Timer", 3)
cls.centered_text(timer_text, 5)
elif State.selected_task_index is not None:
selected_task_index = State.selected_task_index
cls.centered_text("Select Task", 0)
if len(Config.tasks) == 0:
cls.wrapped_text("No tasks configured", 3)
else:
task_name = Config.tasks[selected_task_index].name
underline_width = len(task_name) * cls.CHAR_WIDTH
cls.oled.hline(0, 38, underline_width, 2)
for i, task in enumerate(Config.tasks):
if i < selected_task_index - 1:
continue
task_name = task.name
if i == selected_task_index:
task_name, _ = TextScrolling.maybe_scroll(
task_name, cls.CHARS_PER_LINE
)
line = 3 + (i - selected_task_index)
cls.text(task_name, line)
else:
cls.centered_text("clocko:ctrl", 2)
cls.oled.show()
# API INTERACTION
class ClockodoClient:
BASE_URL = "https://my.clockodo.com/api/v2"
@staticmethod
def headers():
return {
"X-Clockodo-External-Application": "clocko:ctrl;[email protected]",
"X-ClockodoApiUser": Config.api_user,
"X-ClockodoApiKey": Config.api_key,
}
@classmethod
def endpoint(cls, name):
return f"{cls.BASE_URL}/{name}"
@classmethod
def start_clock(cls, task):
data = {
"customers_id": task.customer_id,
"projects_id": task.project_id,
"services_id": Config.service_id,
}
return urequests.post(cls.endpoint("clock"), headers=cls.headers(), json=data)
@classmethod
def stop_clock(cls, entry_id):
return urequests.delete(
cls.endpoint(f"clock/{entry_id}"), headers=cls.headers()
)
@classmethod
def get_clock(cls):
return urequests.get(cls.endpoint("clock"), headers=cls.headers())
class ClockodoRequest:
@staticmethod
def send(request, on_success):
try:
response = request()
if response.status_code == 200:
on_success(response)
else:
raise
except:
State.error = Error.API_REQUEST
finally:
State.triggered_request = None
@classmethod
def start_clock(cls):
active_task = Config.tasks[State.selected_task_index]
def request():
return ClockodoClient.start_clock(active_task)
def on_success(response):
entry_id = response.json()["running"]["id"]
now = mktime(gmtime())
State.change_for_clock_start(active_task, entry_id, now)
cls.send(request, on_success)
@classmethod
def stop_clock(cls):
def request():
return ClockodoClient.stop_clock(State.active_entry_id)
def on_success(_):
State.change_for_clock_stop()
cls.send(request, on_success)
@classmethod
def restore_timer(cls):
def request():
return ClockodoClient.get_clock()
def on_success(response):
running_entry = response.json()["running"]
if not running_entry:
return
active_entry_id = running_entry["id"]
active_task = None
for task in Config.tasks:
if (
task.project_id == running_entry["projects_id"]
and task.customer_id == running_entry["customers_id"]
):
active_task = task
break
start_time_str = running_entry["time_since"]
datetime_regexp ="(\d\d\d\d)-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)"
result = re.search(datetime_regexp , start_time_str)
timer_started_at = None
if result:
try:
t = tuple([int(result.group(i)) if i < 7 else 0 for i in range(1, 10)])
timer_started_at = mktime(t)
except:
pass
if active_entry_id and active_task and timer_started_at:
State.change_for_clock_start(active_task, active_entry_id, timer_started_at)
cls.send(request, on_success)
# MAIN
def init():
gc.enable()
Display.render()
Config.load()
Knob.scale = len(Config.tasks) - 1
Wifi.essid = Config.wifi.essid
Wifi.password = Config.wifi.password
Wifi.connect()
ntptime.settime()
State.triggered_request = ClockodoRequest.restore_timer
def main():
init()
while True:
Knob.handle_turn()
Button.handle_push()
Display.render()
if State.triggered_request is not None:
State.triggered_request()
gc.collect()
sleep(0.1)
main()