-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunction.py
More file actions
561 lines (464 loc) · 15.2 KB
/
Copy pathfunction.py
File metadata and controls
561 lines (464 loc) · 15.2 KB
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
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
from machine import Pin, I2C, RTC, PWM, ADC, Timer, SPI
import ssd1306
import utime as time
from urequests import request
import ujson
import network
import ntptime
I2C_SDA = 22
I2C_SCL = 20
OLED_W, OLED_H = 128, 32
rtc = RTC()
i2c = I2C(0, sda=Pin(I2C_SDA), scl=Pin(I2C_SCL))
oled = ssd1306.SSD1306_I2C(OLED_W, OLED_H, i2c)
piezo = None
BTN_A_PIN = 33
BTN_B_PIN = 15
BTN_C_PIN = 32
DEBOUNCE_MS = 200
SPI_SCK = 5
SPI_MOSI = 19
SPI_MISO = 21
SPI_CS = 13
SPI_READ = 1 << 7
SPI_MB = 1 << 6
btn_a = Pin(BTN_A_PIN, Pin.IN, Pin.PULL_UP)
btn_b = Pin(BTN_B_PIN, Pin.IN, Pin.PULL_UP)
btn_c = Pin(BTN_C_PIN, Pin.IN, Pin.PULL_UP)
cs_adxl = Pin(SPI_CS, Pin.OUT, value=1)
spi = SPI(1, baudrate=5_000_000, polarity=1, phase=1,
sck=Pin(SPI_SCK), mosi=Pin(SPI_MOSI), miso=Pin(SPI_MISO))
last_display_func = None
last_display_args = []
screen_is_on = True
clock_timer = None
alarm_timer = None
alarm_time = None
alarm_ringing = False
last_press_time = 0
_display_count = 0
alarm_toggle_timer = None
alarm_beep_on = False
BEEP_FREQ_HZ = 2000
BEEP_DUTY = 512
BEEP_PERIOD_MS = 500
SSID = "Columbia University"
TIMEZONE_OFFSET = -4
ntp_servers = ["pool.ntp.org", "time.google.com", "time.nist.gov"]
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
WEATHER_API_KEY = 'c011d734fbd24a7f6fb3d04eb159b00d'
# IP_ADDR = '192.168.1.251'
def connect_wifi(max_retries=20):
"""Connect to Wi-Fi and show status on OLED."""
oled.fill(0)
oled.text("Connecting WiFi...", 0, 0)
oled.show()
print("🔌 Connecting to Wi-Fi...")
wlan.connect(SSID)
retry = 0
while not wlan.isconnected() and retry < max_retries:
oled.text("." * (retry % 10 + 1), 0, 12)
oled.show()
time.sleep(0.5)
retry += 1
oled.fill(0)
if wlan.isconnected():
ip = wlan.ifconfig()[0]
oled.text("WiFi OK", 0, 0)
oled.text(ip, 0, 12)
oled.show()
print("✅ Connected:", wlan.ifconfig())
return True
else:
oled.text("WiFi Fail", 0, 0)
oled.show()
print("❌ Failed to connect to Wi-Fi.")
return False
def sync_time(max_retries=5):
"""Sync time from NTP and show progress."""
for server_host in ntp_servers:
ntptime.host = server_host
for attempt in range(max_retries):
try:
oled.fill(0)
oled.text("Sync time...", 0, 0)
oled.text(server_host[:14], 0, 12)
oled.show()
print(f"🌐 Syncing time with {server_host} (attempt {attempt+1})...")
ntptime.settime()
print(f"✅ Time synchronized with {server_host}")
# Apply timezone
tm = list(rtc.datetime())
tm[4] = (tm[4] + TIMEZONE_OFFSET) % 24
rtc.datetime(tuple(tm))
print(f"🕒 Local time adjusted (UTC{TIMEZONE_OFFSET:+d})")
oled.fill(0)
oled.text("Time Sync OK", 0, 0)
oled.show()
time.sleep(1)
return True
except Exception as e:
print(f"⚠️ Failed to sync with {server_host}: {e}")
time.sleep(1)
oled.fill(0)
oled.text("Time Sync Fail", 0, 0)
oled.show()
print("❌ All NTP sync attempts failed.")
return False
def screen_on():
global screen_is_on
screen_is_on = True
oled.poweron()
oled.init_display()
time.sleep_ms(100)
print("[OLED] Power ON")
try:
if last_display_func:
print("[OLED] Restoring previous display...")
last_display_func(*last_display_args)
else:
print("[OLED] No previous display to restore.")
except Exception as e:
print("[ERROR] Failed to restore display:", e)
def screen_off():
global screen_is_on
screen_is_on = False
oled.poweroff()
stop_clock_timer()
print("[OLED] Power OFF")
def display_time():
global last_display_func, last_display_args, clock_timer, _display_count, alarm_time
last_display_func = display_time
last_display_args = []
def update_time(t=None):
global _display_count
y, m, d, wd, h, mi, s, sub = rtc.datetime()
oled.fill(0)
oled.text(f"{y:04d}-{m:02d}-{d:02d}", 0, 0)
oled.text(f"{h:02d}:{mi:02d}:{s:02d}", 0, 12)
if alarm_time and not alarm_ringing:
ah, ami, asec = alarm_time
alarm_for = "TDY" if (h, mi, s) < (ah, ami, asec) else "TMW"
oled.text(f"ALRM: {ah:02d}:{ami:02d} ({alarm_for})", 0, 24)
oled.show()
_display_count += 1
if _display_count % 5 == 0:
print(f"[OLED] {y:04d}-{m:02d}-{d:02d} {h:02d}:{mi:02d}:{s:02d}")
update_time()
stop_clock_timer()
clock_timer = Timer(0)
clock_timer.init(period=1000, mode=Timer.PERIODIC, callback=update_time)
print("[CLOCK] Time auto-update started.")
def stop_clock_timer():
"""Stop periodic screen updates."""
global clock_timer
if clock_timer:
clock_timer.deinit()
clock_timer = None
print("[CLOCK] Clock auto-update stopped.")
def display_message(msg: str):
"""Display a message on OLED, auto-wrap text across lines."""
global last_display_func, last_display_args
last_display_func = display_message
last_display_args = [msg]
stop_clock_timer()
oled.fill(0)
max_chars_per_line = 16
lines = []
while msg:
lines.append(msg[:max_chars_per_line])
msg = msg[max_chars_per_line:]
for i, line in enumerate(lines[:4]):
oled.text(line, 0, i * 12)
oled.show()
print(f"[OLED] Displayed message: {msg}")
def _adxl_read(addr, nbytes=1):
cs_adxl(0)
cmd = SPI_READ | (addr & 0x3F)
if nbytes > 1: cmd |= SPI_MB
spi.write(bytearray([cmd]))
buf = bytearray(nbytes)
spi.readinto(buf)
cs_adxl(1)
return buf if nbytes > 1 else buf[0]
def adxl_read_xyz():
d = _adxl_read(0x32, 6)
x = (d[1] << 8) | d[0]; y = (d[3] << 8) | d[2]; z = (d[5] << 8) | d[4]
if x > 32767: x -= 65536
if y > 32767: y -= 65536
if z > 32767: z -= 65536
return x, y, z
def classify_HAR(label=None):
"""Predict human activity."""
import sys
try:
import uselect as select
except ImportError:
select = None # the hardware sensor does not fit for uselect
global last_display_func, last_display_args
last_display_func = classify_HAR
last_display_args = []
stop_clock_timer()
if label is None:
oled.fill(0)
oled.text('Collecting acc data...', 0, 0)
oled.show()
readings = []
for i in range(128):
acc_reading = adxl_read_xyz()
readings.append(acc_reading)
time.sleep(0.05)
acc_x = [round(r[0], 3) for r in readings]
acc_y = [round(r[1], 3) for r in readings]
acc_z = [round(r[2], 3) for r in readings]
ACTIVITIES = ["WALKING",
"WALKING_UPSTAIRS",
"WALKING_DOWNSTAIRS",
"SITTING",
"STANDING",
"LAYING"]
payload = {
"Device": "ESP32",
"Attached Location": "Waist",
"Candidate Activities": ACTIVITIES,
"acc_x": acc_x,
"acc_y": acc_y,
"acc_z": acc_z
}
# transfer the payload data to LLM on the laptop
try:
print(ujson.dumps(payload))
except Exception as k:
display_message("JSON Dump Fail") # display the error message on OLED
print("The JSON Fails", k)
# Waiting for data from LLM
oled.fill(0)
oled.text("Sent to host, waiting for response..", 0, 0)
oled.show()
pred = None
time_out = 30_000 # 30 seconds maximum
start = time.tick_ms()
# uselect as select, uselect is non-blocking
if select:
poll = select.POLLIN
poll.register(sys.stdin, poll)
while time.tick_diff(time.tick_ms(), 0) < time_out:
dt = poll.poll(300) # wait for 300 per cycle to see whether receives data or not
if dt:
line = sys.stdin.readline().strip()
if line:
pred = line
break
else: # this is for blocking
try:
line = sys.stdin.readline().strip()
pred = line
except Exception:
pred = None
if not pred:
pred = "N/A"
else:
pred = str(label)
# Now we got the data and we display the data on the OLED light
oled.fill(0)
oled.text("Predict..", 0, 0)
oled.text(pred[:15], 0, 12)
oled.show()
print(f"[LLM PRED] {pred}")
time.sleep(5)
display_time()
return pred
def set_alarm(hour, minute):
global alarm_time
second = 0
alarm_time = (hour, minute, second)
y, m, d, wd, h, mi, s, sub = rtc.datetime()
alarm_for = "Today" if (h, mi, s) < (hour, minute, second) else "Tomorrow"
oled.fill(0)
oled.text("Alarm set for:", 0, 0)
oled.text(f"{hour:02d}:{minute:02d}:00", 0, 12)
oled.text(f"({alarm_for})", 0, 24)
oled.show()
print(f"[ALARM] Set for {hour:02d}:{minute:02d}:00 ({alarm_for})")
def check_alarm():
"""Check RTC time vs alarm_time every second."""
global alarm_ringing
if not alarm_time or alarm_ringing:
return
y, m, d, wd, h, mi, s, sub = rtc.datetime()
if (h, mi, s) == alarm_time:
trigger_alarm()
def trigger_alarm():
"""Start alarm sound and flashing OLED."""
global screen_is_on, alarm_ringing, alarm_toggle_timer, alarm_beep_on, piezo
if alarm_ringing:
return
if not screen_is_on:
screen_on()
alarm_ringing = True
alarm_beep_on = False
if piezo is None:
piezo = PWM(Pin(25))
else:
piezo.deinit()
piezo = PWM(Pin(25))
flash_state = [False]
def toggle_alarm_line(t=None):
global alarm_beep_on, piezo
if not alarm_ringing:
piezo.deinit()
display_time()
return
alarm_beep_on = not alarm_beep_on
if alarm_beep_on:
piezo.init(freq=BEEP_FREQ_HZ, duty=BEEP_DUTY)
else:
piezo.deinit()
y, m, d, wd, h, mi, s, sub = rtc.datetime()
oled.fill(0)
oled.text(f"{y:04d}-{m:02d}-{d:02d}", 0, 0)
oled.text(f"{h:02d}:{mi:02d}:{s:02d}", 0, 12)
if flash_state[0]:
oled.text("ALRM! PRESS BTNS", 0, 24)
flash_state[0] = not flash_state[0]
oled.show()
alarm_toggle_timer = Timer(2)
alarm_toggle_timer.init(period=BEEP_PERIOD_MS, mode=Timer.PERIODIC, callback=toggle_alarm_line)
def stop_alarm():
"""Stop the alarm and revert to time display."""
global alarm_ringing, alarm_toggle_timer, piezo, alarm_time
if alarm_ringing:
alarm_ringing = False
if alarm_toggle_timer:
alarm_toggle_timer.deinit()
alarm_toggle_timer = None
try:
piezo.deinit()
except:
pass
alarm_time = None
print("[ALARM] Stopped.")
display_time()
def button_handler(pin):
"""Stop alarm on any button press (with debounce)."""
global last_press_time
now = time.ticks_ms()
if time.ticks_diff(now, last_press_time) < DEBOUNCE_MS:
return # debounce
last_press_time = now
if alarm_ringing:
stop_alarm()
btn_a.irq(trigger=Pin.IRQ_FALLING, handler=button_handler)
btn_b.irq(trigger=Pin.IRQ_FALLING, handler=button_handler)
btn_c.irq(trigger=Pin.IRQ_FALLING, handler=button_handler)
def display_location():
global last_display_func, last_display_args
last_display_func = display_location
last_display_args = []
stop_clock_timer()
try:
geo_query = f'http://ip-api.com/json/'
response = request('GET', geo_query)
if response.status_code == 200:
data = ujson.loads(response.text)
lat = data.get('lat', 0.0)
lon = data.get('lon', 0.0)
oled.fill(0)
oled.text("Location:", 0, 0)
oled.text("Lat: {:.4f}".format(lat), 0, 12)
oled.text("Lon: {:.4f}".format(lon), 0, 24)
oled.show()
print(f"[OLED] Location: {lat}, {lon}")
else:
display_message(f"Error: {response.status_code}")
response.close()
except Exception as e:
display_message("Failed to get location")
print("[ERROR] display_location:", e)
def display_weather():
global last_display_func, last_display_args
last_display_func = display_weather
last_display_args = []
stop_clock_timer()
try:
geo_query = f'http://ip-api.com/json/'
response = request('GET', geo_query)
if response.status_code != 200:
display_message("Loc Error")
response.close()
return
loc_data = ujson.loads(response.text)
lat = loc_data.get('lat', 0.0)
lon = loc_data.get('lon', 0.0)
response.close()
weather_query = (
f'https://api.openweathermap.org/data/2.5/weather'
f'?lat={lat}&lon={lon}&appid={WEATHER_API_KEY}'
)
response = request('GET', weather_query)
if response.status_code != 200:
display_message("Weather Err")
response.close()
return
weather_data = ujson.loads(response.text)
response.close()
weather_desc = weather_data['weather'][0]['description']
temp_min = int((weather_data['main']['temp_min'] - 273.15) * 10) / 10
temp_max = int((weather_data['main']['temp_max'] - 273.15) * 10) / 10
humid = weather_data['main']['humidity']
oled.fill(0)
oled.text("Weather:", 0, 0)
oled.text(weather_desc, 0, 12)
oled.text(f'Temp:{temp_min}~{temp_max}', 0, 24)
# oled.text(f'Humid:{humid}%', 0, 36)
oled.show()
print(f"[OLED] Weather: {weather_desc}, Temp: {temp_min}-{temp_max}, Humid: {humid}%")
except Exception as e:
display_message("Weather Fail")
print("[ERROR] display_weather:", e)
def execute_command(cmd: dict):
name = cmd.get("name")
args = cmd.get("args", [])
functions = {
"screen_on": screen_on,
"screen_off": screen_off,
"display_time": display_time,
"display_message": display_message,
"set_alarm": set_alarm,
"stop_alarm": stop_alarm,
"display_location": display_location,
"display_weather": display_weather,
"classify_HAR": classify_HAR
}
func = functions.get(name)
if func:
data = func(*args)
if data is None:
return f"Executed {name} with args {args}"
else:
return f"DATA:{data}"
else:
return f"Unknown command: {name}"
def start_background_tasks():
"""Initialize any continuous tasks."""
global alarm_timer, piezo
screen_on()
wifi_ok = connect_wifi()
if wifi_ok:
time_ok = sync_time()
else:
time_ok = False
if wifi_ok and time_ok:
display_message("Ready")
elif wifi_ok:
display_message("No Time Sync")
else:
display_message("No WiFi")
display_time()
if piezo:
piezo.deinit()
piezo = None
alarm_timer = Timer(1)
alarm_timer.init(period=1000, mode=Timer.PERIODIC, callback=lambda t: check_alarm())
print("[INIT] WiFi, time sync, display, and alarm checker running.")