-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb.py
More file actions
481 lines (442 loc) · 14.5 KB
/
db.py
File metadata and controls
481 lines (442 loc) · 14.5 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
import os
from contextlib import contextmanager
from typing import Any, Dict, Iterator, List, Optional
from dotenv import load_dotenv
from psycopg import Connection, connect
from psycopg.rows import dict_row
from psycopg.types.json import Jsonb
load_dotenv()
DATABASE_URL = os.getenv(
"DATABASE_URL",
"postgresql://bletrack:bletrack_dev_password@localhost:5433/bletrack",
)
@contextmanager
def get_db() -> Iterator[Connection]:
conn = connect(DATABASE_URL, row_factory=dict_row)
try:
yield conn
conn.commit()
except Exception:
conn.rollback()
raise
finally:
conn.close()
def check_db_health() -> bool:
try:
with get_db() as conn:
with conn.cursor() as cur:
cur.execute("SELECT 1")
row = cur.fetchone()
return bool(row)
except Exception:
return False
def ensure_app_schema() -> None:
with get_db() as conn:
with conn.cursor() as cur:
cur.execute(
"""
CREATE TABLE IF NOT EXISTS fingerprint_registry (
device_id TEXT PRIMARY KEY,
fingerprint_value TEXT NOT NULL,
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
)
"""
)
cur.execute(
"""
CREATE TABLE IF NOT EXISTS managed_devices (
id BIGSERIAL PRIMARY KEY,
display_name TEXT NOT NULL UNIQUE,
device_type TEXT NOT NULL DEFAULT 'phone',
observed_device_id TEXT NOT NULL,
fingerprint_device_id TEXT,
is_active BOOLEAN NOT NULL DEFAULT TRUE,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
)
"""
)
cur.execute(
"""
CREATE UNIQUE INDEX IF NOT EXISTS idx_managed_devices_fingerprint_device_id
ON managed_devices (fingerprint_device_id)
WHERE fingerprint_device_id IS NOT NULL
"""
)
cur.execute(
"""
CREATE INDEX IF NOT EXISTS idx_managed_devices_observed_device_id
ON managed_devices (observed_device_id)
"""
)
def upsert_managed_device(
*,
display_name: str,
observed_device_id: str,
device_type: str,
fingerprint_device_id: Optional[str],
is_active: bool,
) -> Dict[str, Any]:
with get_db() as conn:
with conn.cursor() as cur:
cur.execute(
"""
INSERT INTO managed_devices (
display_name,
observed_device_id,
device_type,
fingerprint_device_id,
is_active,
updated_at
)
VALUES (%s, %s, %s, %s, %s, NOW())
ON CONFLICT (display_name)
DO UPDATE SET
observed_device_id = EXCLUDED.observed_device_id,
device_type = EXCLUDED.device_type,
fingerprint_device_id = EXCLUDED.fingerprint_device_id,
is_active = EXCLUDED.is_active,
updated_at = NOW()
RETURNING
id,
display_name,
observed_device_id,
device_type,
fingerprint_device_id,
is_active,
created_at,
updated_at
""",
(
display_name,
observed_device_id,
device_type,
fingerprint_device_id,
is_active,
),
)
row = cur.fetchone()
return dict(row) if row else {}
def list_managed_devices(limit: int = 500) -> List[Dict[str, Any]]:
with get_db() as conn:
with conn.cursor() as cur:
cur.execute(
"""
SELECT
m.id,
m.display_name,
m.device_type,
m.observed_device_id,
m.fingerprint_device_id,
m.is_active,
m.created_at,
m.updated_at,
p.ts AS last_seen_ts,
p.room AS last_seen_room,
p.distance_m AS last_distance_m,
p.rssi AS last_rssi,
p.device_id AS last_live_device_id,
p.payload_name AS last_payload_name
FROM managed_devices m
LEFT JOIN LATERAL (
SELECT
ts,
room,
distance_m,
rssi,
device_id,
payload->>'name' AS payload_name
FROM presence_events pe
WHERE (
pe.device_id = m.observed_device_id
OR (
m.fingerprint_device_id IS NOT NULL
AND pe.device_id = m.fingerprint_device_id
)
OR (
m.fingerprint_device_id IS NOT NULL
AND split_part(m.fingerprint_device_id, ':', 1) = pe.device_id
)
)
ORDER BY pe.ts DESC
LIMIT 1
) p ON TRUE
ORDER BY m.display_name ASC
LIMIT %s
""",
(limit,),
)
rows = cur.fetchall()
return [dict(row) for row in rows]
def set_managed_device_active(
display_name: str, is_active: bool
) -> Optional[Dict[str, Any]]:
with get_db() as conn:
with conn.cursor() as cur:
cur.execute(
"""
UPDATE managed_devices
SET is_active = %s,
updated_at = NOW()
WHERE display_name = %s
RETURNING
id,
display_name,
observed_device_id,
device_type,
fingerprint_device_id,
is_active,
created_at,
updated_at
""",
(is_active, display_name),
)
row = cur.fetchone()
return dict(row) if row else None
def query_fingerprint_by_device_id(device_id: str) -> Optional[Dict[str, Any]]:
with get_db() as conn:
with conn.cursor() as cur:
cur.execute(
"""
SELECT device_id, fingerprint_value, updated_at
FROM fingerprint_registry
WHERE device_id = %s
""",
(device_id,),
)
row = cur.fetchone()
return dict(row) if row else None
def query_discovered_devices(limit: int = 500) -> List[Dict[str, Any]]:
with get_db() as conn:
with conn.cursor() as cur:
cur.execute(
"""
SELECT *
FROM (
SELECT DISTINCT ON (device_id)
device_id,
payload->>'name' AS discovered_name,
ts,
room,
distance_m,
rssi
FROM presence_events
ORDER BY device_id, ts DESC
) latest
ORDER BY ts DESC
LIMIT %s
""",
(limit,),
)
rows = cur.fetchall()
return [dict(row) for row in rows]
def upsert_fingerprint(device_id: str, fingerprint_value: str) -> None:
with get_db() as conn:
with conn.cursor() as cur:
cur.execute(
"""
INSERT INTO fingerprint_registry (device_id, fingerprint_value, updated_at)
VALUES (%s, %s, NOW())
ON CONFLICT (device_id)
DO UPDATE SET
fingerprint_value = EXCLUDED.fingerprint_value,
updated_at = NOW()
""",
(device_id, fingerprint_value),
)
def insert_presence_event(
*,
room: str,
device_id: str,
alias: Optional[str],
distance_m: Optional[float],
rssi: Optional[int],
topic: str,
payload: Dict[str, Any],
) -> None:
with get_db() as conn:
with conn.cursor() as cur:
cur.execute(
"""
INSERT INTO presence_events (
room,
device_id,
alias,
distance_m,
rssi,
topic,
payload
)
VALUES (%s, %s, %s, %s, %s, %s, %s)
""",
(room, device_id, alias, distance_m, rssi, topic, Jsonb(payload)),
)
def query_latest_presence(
*,
limit: int = 100,
room: Optional[str] = None,
device_id: Optional[str] = None,
alias: Optional[str] = None,
paired_only: bool = False,
) -> List[Dict[str, Any]]:
conditions = []
params: List[Any] = []
if room is not None:
conditions.append("room = %s")
params.append(room)
if device_id is not None:
conditions.append("device_id = %s")
params.append(device_id)
if alias is not None:
conditions.append("alias = %s")
params.append(alias)
if paired_only:
conditions.append(
"""
(
device_id IN (
SELECT observed_device_id
FROM managed_devices
WHERE is_active = TRUE
)
OR device_id IN (
SELECT fingerprint_device_id
FROM managed_devices
WHERE is_active = TRUE
AND fingerprint_device_id IS NOT NULL
)
OR
device_id IN (SELECT device_id FROM fingerprint_registry)
OR EXISTS (
SELECT 1
FROM fingerprint_registry fr
WHERE split_part(fr.device_id, ':', 1) = presence_events.device_id
)
)
"""
)
where_clause = ""
if conditions:
where_clause = "WHERE " + " AND ".join(conditions)
with get_db() as conn:
with conn.cursor() as cur:
cur.execute(
f"""
WITH latest AS (
SELECT DISTINCT ON (device_id)
ts,
room,
device_id,
alias,
distance_m,
rssi,
topic,
payload
FROM presence_events
{where_clause}
ORDER BY device_id, ts DESC
)
SELECT *
FROM latest
ORDER BY ts DESC
LIMIT %s
""",
[*params, limit],
)
rows = cur.fetchall()
return [dict(row) for row in rows]
def query_presence_history(
*,
minutes: int = 60,
limit: int = 1000,
room: Optional[str] = None,
device_id: Optional[str] = None,
alias: Optional[str] = None,
paired_only: bool = False,
) -> List[Dict[str, Any]]:
conditions = ["ts >= NOW() - (%s * INTERVAL '1 minute')"]
params: List[Any] = [minutes]
if room is not None:
conditions.append("room = %s")
params.append(room)
if device_id is not None:
conditions.append("device_id = %s")
params.append(device_id)
if alias is not None:
conditions.append("alias = %s")
params.append(alias)
if paired_only:
conditions.append(
"""
(
device_id IN (
SELECT observed_device_id
FROM managed_devices
WHERE is_active = TRUE
)
OR device_id IN (
SELECT fingerprint_device_id
FROM managed_devices
WHERE is_active = TRUE
AND fingerprint_device_id IS NOT NULL
)
OR
device_id IN (SELECT device_id FROM fingerprint_registry)
OR EXISTS (
SELECT 1
FROM fingerprint_registry fr
WHERE split_part(fr.device_id, ':', 1) = presence_events.device_id
)
)
"""
)
where_clause = "WHERE " + " AND ".join(conditions)
with get_db() as conn:
with conn.cursor() as cur:
cur.execute(
f"""
SELECT
ts,
room,
device_id,
alias,
distance_m,
rssi,
topic,
payload
FROM presence_events
{where_clause}
ORDER BY ts DESC
LIMIT %s
""",
[*params, limit],
)
rows = cur.fetchall()
return [dict(row) for row in rows]
def query_fingerprint_registry(limit: int = 200) -> List[Dict[str, Any]]:
with get_db() as conn:
with conn.cursor() as cur:
cur.execute(
"""
SELECT device_id, fingerprint_value, updated_at
FROM fingerprint_registry
ORDER BY updated_at DESC
LIMIT %s
""",
(limit,),
)
rows = cur.fetchall()
return [dict(row) for row in rows]
def ensure_retention_policy(days: int = 90) -> None:
with get_db() as conn:
with conn.cursor() as cur:
cur.execute(
"""
SELECT add_retention_policy(
'presence_events',
drop_after => make_interval(days => %s),
if_not_exists => TRUE
)
""",
(days,),
)