forked from SCWhite/MeshBridge
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp_noteboard.py
More file actions
4932 lines (4278 loc) · 206 KB
/
app_noteboard.py
File metadata and controls
4932 lines (4278 loc) · 206 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
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import eventlet
eventlet.monkey_patch()
import time
import sys
import os
import glob
import sqlite3
import uuid
import re
import subprocess
import logging
import random
from datetime import datetime, timedelta
from flask import Flask, render_template, request, redirect, url_for, jsonify, make_response, session, send_file
from flask_socketio import SocketIO, emit
from meshtastic.serial_interface import SerialInterface
from pubsub import pub
import config
from config import SEND_INTERVAL_SECOND, BOARD_MESSAGE_CHANNELS
print(f"[系統] 使用多頻道設定: {[ch['name'] for ch in BOARD_MESSAGE_CHANNELS]}")
# 所有設定中的頻道名稱(用於驗證)
CONFIGURED_CHANNEL_NAMES = [ch['name'] for ch in BOARD_MESSAGE_CHANNELS]
NOTEBOARD_MBTILES_FOLDER = getattr(config, 'NOTEBOARD_MBTILES_FOLDER', './maps')
NOTEBOARD_MBTILES_LAYER_MODE = getattr(config, 'NOTEBOARD_MBTILES_LAYER_MODE', 'auto')
APP_VERSION = "v0.7.1"
APP_PROJECT_NAME = "meshBridge/meshNoteboard"
NOTEBOARD_SERVICE_NAME = getattr(
config,
'NOTEBOARD_SERVICE_NAME',
getattr(config, 'BOARD_SERVICE_NAME', 'Mesh資訊站')
)
EPAPER_CONNECT_NOTE = getattr(config, 'EPAPER_CONNECT_NOTE', '即可檢視更多訊息。')
REAUTH_ON_CHANNEL_SWITCH = getattr(config, 'REAUTH_ON_CHANNEL_SWITCH', False)
UPDATE_LORA_DEVICE_TIME_FROM_LOCAL = getattr(config, 'UPDATE_LORA_DEVICE_TIME_FROM_LOCAL', False)
ACK_TIMEOUT_SECONDS = 60
ACK_DELAY_SECONDS = max(10, SEND_INTERVAL_SECOND // 2)
ACK_JITTER = True
# 自動重送機制參數
_auto_resend_node_raw = getattr(config, 'AUTO_RESEND_NODE', 0)
try:
AUTO_RESEND_NODE = int(_auto_resend_node_raw)
except (ValueError, TypeError):
AUTO_RESEND_NODE = 0
AUTO_RESEND_BACKOFF_SECOND = 100
# 55秒退避基數
# AUTO_RESEND_MAX_MINUTE=30 => 8 次
# AUTO_RESEND_MAX_MINUTE=60 => 11 次
# AUTO_RESEND_MAX_MINUTE=120 => 16 次
# 100秒退避基數
# AUTO_RESEND_MAX_MINUTE=30 => 6 次
# AUTO_RESEND_MAX_MINUTE=60 => 9 次
# AUTO_RESEND_MAX_MINUTE=120 => 13 次
# 150秒退避基數
# AUTO_RESEND_MAX_MINUTE=30 => 5 次
# AUTO_RESEND_MAX_MINUTE=60 => 7 次
# AUTO_RESEND_MAX_MINUTE=120 => 10 次
if AUTO_RESEND_NODE > 0:
AUTO_RESEND_MIN_MINUTE = float(getattr(config, 'AUTO_RESEND_MIN_MINUTE', 6))
AUTO_RESEND_MAX_MINUTE = float(getattr(config, 'AUTO_RESEND_MAX_MINUTE', 720))
print(f"[自動重送] 功能已啟用: 需要 {AUTO_RESEND_NODE} 個節點 ACK, 時間範圍 {AUTO_RESEND_MIN_MINUTE}~{AUTO_RESEND_MAX_MINUTE} 分鐘, 退避基數 {AUTO_RESEND_BACKOFF_SECOND}s")
else:
AUTO_RESEND_MIN_MINUTE = 0
AUTO_RESEND_MAX_MINUTE = 0
print(f"[自動重送] 功能未啟用 (AUTO_RESEND_NODE={AUTO_RESEND_NODE})")
from app import get_power_status
from app_noteboard_epaper import update_epaper_display, start_epaper_periodic_refresh, clear_epaper_display, get_current_photo_path
# 抑制 Meshtastic 的 protobuf 解析錯誤日誌(這些是暫時性錯誤,不影響功能)
logging.getLogger('meshtastic.mesh_interface').setLevel(logging.CRITICAL)
logging.getLogger('meshtastic.stream_interface').setLevel(logging.CRITICAL)
# Monkey patch Meshtastic 的錯誤處理,抑制 protobuf 解析錯誤
def patch_meshtastic_error_handling():
"""修補 Meshtastic 庫的錯誤處理,抑制暫時性的 protobuf 解析錯誤"""
try:
from meshtastic import mesh_interface
import io
import contextlib
original_handleFromRadio = mesh_interface.MeshInterface._handleFromRadio
def patched_handleFromRadio(self, fromRadioBytes):
# 使用 context manager 來抑制 stderr 輸出
stderr_suppressor = io.StringIO()
try:
with contextlib.redirect_stderr(stderr_suppressor):
return original_handleFromRadio(self, fromRadioBytes)
except Exception as e:
error_msg = str(e)
# 只抑制 protobuf 解析錯誤,其他錯誤仍然拋出
if "Error parsing message" in error_msg or "DecodeError" in error_msg:
# 靜默忽略這些暫時性錯誤(包括 traceback)
pass
else:
# 其他錯誤仍然拋出,並顯示 stderr
stderr_content = stderr_suppressor.getvalue()
if stderr_content:
sys.stderr.write(stderr_content)
raise
mesh_interface.MeshInterface._handleFromRadio = patched_handleFromRadio
print("[系統] 已修補 Meshtastic protobuf 錯誤處理")
except Exception as e:
print(f"[系統] 修補 Meshtastic 錯誤處理失敗 (可忽略): {e}")
# 在導入 SerialInterface 之後立即執行修補
patch_meshtastic_error_handling()
try:
from config import UID_SOURCE
except ImportError:
UID_SOURCE = "mac"
# 控制是否印出完整 LoRa 封包資訊
IS_PRINT_LORA_PACKAGE = False
# 驗證頻道設定
FORBIDDEN_CHANNEL_NAMES = ["MeshTW", "Emergency!","SignalTest"]
for _ch_cfg in BOARD_MESSAGE_CHANNELS:
_ch_name = _ch_cfg.get('name', '')
if not _ch_name or _ch_name.strip() == "":
raise ValueError("頻道名稱不得為空")
if _ch_name in FORBIDDEN_CHANNEL_NAMES:
raise ValueError(f"頻道名稱 '{_ch_name}' 不得為: {', '.join(FORBIDDEN_CHANNEL_NAMES)}")
app = Flask(__name__,
template_folder='templates/app_noteboard',
static_folder='static/app_noteboard')
app.config['SECRET_KEY'] = 'meshbridge_secret'
app.config['SESSION_COOKIE_SAMESITE'] = 'Lax'
app.config['SESSION_COOKIE_SECURE'] = False
app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(days=365)
socketio = SocketIO(app, cors_allowed_origins="*", async_mode='eventlet')
interface = None
current_dev_path = None
lora_connected = False
channel_validated = False
active_channels = [] # 連線後實際可用的頻道清單 (從 BOARD_MESSAGE_CHANNELS 中篩選出設備上存在的頻道)
pending_ack = {}
FLAG_DEVICE_WAITING_ACK = False
send_interval = max(SEND_INTERVAL_SECOND, 30)
deviceLastPosition = {'lat': 0.0, 'lng': 0.0}
isDeviceProvideLocation = False
DB_PATH = 'noteboard.db'
MAX_NOTES = 200
user_last_locations = {}
# MAC 模式的伺服器端 session 儲存(不支援 cookie 的客戶端使用)
# 格式:{mac_address: {'admin_channels': [...], 'verified_channels': [...], 'selected_board': '...'}}
mac_sessions = {}
def _get_mac_address_for_request():
"""取得當前請求的 MAC address(僅 MAC 模式有效)"""
if UID_SOURCE != "mac":
return None
client_ip = request.remote_addr
return mac_from_ip(client_ip)
def get_session_value(key, default=None):
"""取得 session 值(自動判斷 MAC 模式或 Flask session)"""
if UID_SOURCE == "mac":
mac_address = _get_mac_address_for_request()
if mac_address:
return mac_sessions.get(mac_address, {}).get(key, default)
return session.get(key, default)
def set_session_value(key, value):
"""設定 session 值(自動判斷 MAC 模式或 Flask session)"""
if UID_SOURCE == "mac":
mac_address = _get_mac_address_for_request()
if mac_address:
if mac_address not in mac_sessions:
mac_sessions[mac_address] = {}
mac_sessions[mac_address][key] = value
return
# Flask session 模式
session[key] = value
session.permanent = True
session.modified = True
COLOR_PALETTE = [
'hsl(0, 70%, 85%)', # 0: Red
'hsl(30, 70%, 85%)', # 1: Orange
'hsl(60, 70%, 85%)', # 2: Yellow
'hsl(90, 70%, 85%)', # 3: Light Green
'hsl(120, 70%, 85%)', # 4: Green
'hsl(150, 70%, 85%)', # 5: Teal
'hsl(180, 70%, 85%)', # 6: Cyan
'hsl(210, 70%, 85%)', # 7: Light Blue
'hsl(240, 70%, 85%)', # 8: Blue
'hsl(270, 70%, 85%)', # 9: Purple
'hsl(300, 70%, 85%)', # 10: Magenta
'hsl(330, 70%, 85%)', # 11: Pink
'hsl(0, 0%, 85%)', # 12: Light Gray
'hsl(0, 0%, 75%)', # 13: Gray
'hsl(45, 80%, 85%)', # 14: Gold
'hsl(0, 0%, 100%)' # 15: White
]
def _build_epaper_default_profile():
"""從 config.EPAPER_DISPLAY_MODE 解析預設的 layout 與 canvas"""
display_mode = getattr(config, 'EPAPER_DISPLAY_MODE', 'standard_qr,w7')
device_id = getattr(config, 'EPAPER_MODULE_ID', '')
from app_noteboard_epaper import DEVICE_COLOR_MODE_MAPPING
color_mode = DEVICE_COLOR_MODE_MAPPING.get(device_id, {}).get('color_mode', 'mono')
layout, canvas = 'standard_qr', 'w7'
if ',' in display_mode:
parts = display_mode.split(',', 1)
layout = parts[0].strip()
canvas = parts[1].strip()
return {'color_mode': color_mode, 'layout': layout, 'canvas': canvas}
EPAPER_DEFAULT_PROFILE = _build_epaper_default_profile()
EPAPER_SUPPORTED_OPTIONS = {
'color_mode': {'mono', 'full_color', 'dual_rb'},
'layout': {'standard_qr', 'photo_qr'},
'canvas': {'w7', 'p7'}
}
EPAPER_CANVAS_SPECS = {
'w7': {
'width': 800,
'height': 480,
'orientation': 'landscape',
'max_notes': 3
},
'p7': {
'width': 480,
'height': 800,
'orientation': 'portrait',
'max_notes': 3
}
}
def init_database():
"""初始化 SQLite 資料庫"""
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS notes (
note_id TEXT PRIMARY KEY,
reply_lora_msg_id TEXT,
board_id TEXT NOT NULL,
body TEXT NOT NULL,
bg_color TEXT,
status TEXT NOT NULL,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL,
author_key TEXT NOT NULL,
rev INTEGER NOT NULL DEFAULT 1,
deleted INTEGER NOT NULL DEFAULT 0,
resent_count INTEGER NOT NULL DEFAULT 0,
is_need_update_lora INTEGER NOT NULL DEFAULT 0,
lora_msg_id TEXT,
is_temp_parent_note INTEGER NOT NULL DEFAULT 0,
is_pined_note INTEGER NOT NULL DEFAULT 0,
resent_priority INTEGER NOT NULL DEFAULT 0,
grid_mode TEXT NOT NULL DEFAULT '',
grid_x INTEGER NOT NULL DEFAULT 0,
grid_y INTEGER NOT NULL DEFAULT 0,
lora_node_id TEXT,
transmit_st_at INTEGER,
FOREIGN KEY (reply_lora_msg_id) REFERENCES notes(note_id)
)
''')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_board_id ON notes(board_id)')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_created_at ON notes(created_at DESC)')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_deleted ON notes(deleted)')
cursor.execute('''
CREATE TABLE IF NOT EXISTS ack_records (
ack_id TEXT PRIMARY KEY,
note_id TEXT NOT NULL,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL,
lora_node_id TEXT NOT NULL,
hop_limit INTEGER,
hop_start INTEGER,
FOREIGN KEY (note_id) REFERENCES notes(note_id)
)
''')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_ack_note_id ON ack_records(note_id)')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_ack_created_at ON ack_records(created_at DESC)')
conn.commit()
conn.close()
print("資料庫初始化完成")
def migrate_database():
"""檢查並執行資料庫遷移"""
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
try:
cursor.execute("PRAGMA table_info(notes)")
columns = [column[1] for column in cursor.fetchall()]
if 'lora_node_id' not in columns:
print("[資料庫遷移] 偵測到 notes 表缺少 lora_node_id 欄位,開始遷移...")
cursor.execute('ALTER TABLE notes ADD COLUMN lora_node_id TEXT')
conn.commit()
print("[資料庫遷移] 已成功新增 lora_node_id 欄位")
cursor.execute("PRAGMA table_info(ack_records)")
ack_columns = [column[1] for column in cursor.fetchall()]
if 'hop_limit' not in ack_columns:
print("[資料庫遷移] 偵測到 ack_records 表缺少 hop_limit 欄位,開始遷移...")
cursor.execute('ALTER TABLE ack_records ADD COLUMN hop_limit INTEGER')
conn.commit()
print("[資料庫遷移] 已成功新增 hop_limit 欄位")
if 'hop_start' not in ack_columns:
print("[資料庫遷移] 偵測到 ack_records 表缺少 hop_start 欄位,開始遷移...")
cursor.execute('ALTER TABLE ack_records ADD COLUMN hop_start INTEGER')
conn.commit()
print("[資料庫遷移] 已成功新增 hop_start 欄位")
if 'transmit_st_at' not in columns:
print("[資料庫遷移] 偵測到 notes 表缺少 transmit_st_at 欄位,開始遷移...")
cursor.execute('ALTER TABLE notes ADD COLUMN transmit_st_at INTEGER')
conn.commit()
print("[資料庫遷移] 已成功新增 transmit_st_at 欄位")
except Exception as e:
print(f"[資料庫遷移] 遷移失敗: {e}")
finally:
conn.close()
def get_time():
return time.strftime("%H:%M", time.localtime())
def format_note_time(timestamp_ms):
"""
格式化便利貼時間顯示
今天|1天前|2天前..n天前 (YYYY/MM/DD HH:MM)
HH 為 24小時制
"""
local_time = time.localtime(timestamp_ms / 1000)
# 計算日期差異
note_date = datetime.fromtimestamp(timestamp_ms / 1000).date()
today = datetime.now().date()
days_diff = (today - note_date).days
# 格式化日期時間 (24小時制)
formatted_datetime = time.strftime("%Y/%m/%d %H:%M", local_time)
# 根據天數差異顯示相對時間
if days_diff == 0:
relative_time = "今天"
elif days_diff == 1:
relative_time = "昨天"
else:
relative_time = f"{days_diff}天前"
return f"{relative_time} ({formatted_datetime})"
def generate_note_id():
"""生成唯一的 note_id"""
return str(uuid.uuid4())
def generate_user_uuid():
"""生成用戶 UUID (8字元)"""
alphabet = 'abcdefghijklmnopqrstuvwxyz0123456789'
import random
return ''.join(random.choice(alphabet) for _ in range(8))
MAC_RE = re.compile(r"lladdr\s+([0-9a-f:]{17})", re.I)
SHEET_DELETE_RE = re.compile(r'^\{([a-z0-9]{6}):delete\}$')
SHEET_TITLE_RE = re.compile(r'^\{([a-z0-9]{6}):title\}([\s\S]*)$')
TABLE_CELL_RE = re.compile(r'^\{([a-z0-9]{6}):((?:[A-Z][1-9]\d{0,2})|title)\}([\s\S]*)$', re.DOTALL)
def _is_table_format_note(body):
"""判斷 note body 是否為 table 資料格式(TABLE_CELL_RE 或 SHEET_DELETE_RE)"""
return bool(TABLE_CELL_RE.match(body)) or bool(SHEET_DELETE_RE.match(body))
def auto_archive_old_notes(cursor, board_id, ch_max_notes):
"""自動封存超過 max_notes 的舊留言
規則:
- 只計算『沒有 table 指令』且『非置頂』的 notes 數量
- 只封存『沒有 table 指令』且『非置頂』的最舊 notes
- table 指令的 note 和置頂的 note 完全不受此機制影響
"""
timestamp = int(time.time() * 1000)
# 計算非 table 指令、非置頂、未刪除的 notes 數量
# 使用 NOT 排除 table 格式的 body(匹配 {xxxxxx:...} 開頭)
cursor.execute('''
SELECT COUNT(*) FROM notes
WHERE board_id = ? AND deleted = 0 AND is_pined_note = 0
AND body NOT GLOB '{[a-z0-9][a-z0-9][a-z0-9][a-z0-9][a-z0-9][a-z0-9]:*'
''', (board_id,))
count = cursor.fetchone()[0]
if count > ch_max_notes:
overflow = count - ch_max_notes
cursor.execute('''
UPDATE notes
SET deleted = 1, updated_at = ?
WHERE note_id IN (
SELECT note_id FROM notes
WHERE board_id = ? AND deleted = 0 AND is_pined_note = 0
AND body NOT GLOB '{[a-z0-9][a-z0-9][a-z0-9][a-z0-9][a-z0-9][a-z0-9]:*'
ORDER BY created_at ASC
LIMIT ?
)
''', (timestamp, board_id, overflow))
archived_count = cursor.rowcount
if archived_count > 0:
print(f"[自動封存] board_id={board_id}: 封存了 {archived_count} 筆舊留言 (非table指令, 非置頂)")
def sheet_id_exists_in_db(sheet_id):
"""檢查 sheet_id 是否已存在於資料庫的任何 note body 中(包含 deleted 及所有指令類型)"""
try:
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
pattern = '{' + sheet_id + ':%'
cursor.execute('SELECT COUNT(*) FROM notes WHERE body LIKE ?', (pattern,))
count = cursor.fetchone()[0]
conn.close()
return count > 0
except Exception as e:
print(f"檢查 sheet_id 是否存在失敗: {e}")
return False
def generate_unique_sheet_id():
"""產生不重複的 6 字元 sheet_id"""
import random
chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
for _ in range(100):
sheet_id = ''.join(random.choice(chars) for _ in range(6))
if not sheet_id_exists_in_db(sheet_id):
return sheet_id
raise Exception("無法產生唯一的 sheet_id(已嘗試 100 次)")
def mac_from_ip(ip: str, iface: str = "wlan0") -> str | None:
"""從 IP 取得 MAC address (移除冒號)"""
try:
out = subprocess.run(
["ip", "neigh", "show", "dev", iface, ip],
capture_output=True, text=True, check=False
).stdout
m = MAC_RE.search(out)
if m:
mac_with_colons = m.group(1).lower()
return mac_with_colons.replace(':', '')
return None
except Exception as e:
print(f"Error getting MAC from IP {ip}: {e}")
return None
def get_current_wifi_ssid():
"""
參考 setup_wifi.sh:
1) 由 wlan0 MAC 推導 TARGET_SSID (MeshBridge_XXXX)
2) 讀取 MeshBridge-Hotspot 目前設定的 SSID
3) 優先回傳目前設定值,失敗時回傳 TARGET_SSID,再失敗回傳預設值
"""
default_ssid = "MeshBridge_8944"
target_ssid = default_ssid
try:
with open('/sys/class/net/wlan0/address', 'r', encoding='utf-8') as fp:
raw_mac = fp.read().strip()
sanitized = raw_mac.replace(':', '').upper()
if len(sanitized) >= 4:
suffix = sanitized[-4:]
target_ssid = f"MeshBridge_{suffix}"
except Exception as e:
print(f"[WiFi] 讀取 wlan0 MAC 失敗,使用預設 SSID: {e}")
try:
result = subprocess.run(
["nmcli", "-g", "802-11-wireless.ssid", "connection", "show", "MeshBridge-Hotspot"],
capture_output=True,
text=True,
timeout=5,
check=False
)
current_ssid = result.stdout.strip()
if result.returncode == 0 and current_ssid:
return current_ssid
except Exception as e:
print(f"[WiFi] 讀取 MeshBridge-Hotspot SSID 失敗,改用 TARGET_SSID: {e}")
return target_ssid
def get_or_create_user_uuid():
"""從 session/cookie 取得或建立用戶 UUID"""
if 'user_uuid' not in session:
session['user_uuid'] = generate_user_uuid()
session.permanent = True
return session['user_uuid']
def generate_bg_color(author_key):
"""根據 author_key 生成背景顏色"""
hash_val = 0
for char in author_key:
hash_val = ord(char) + ((hash_val << 5) - hash_val)
h = abs(hash_val) % 360
return f"hsl({h}, 70%, 85%)"
def get_color_from_palette(color_index):
"""從調色盤取得顏色 (0-15)"""
try:
index = int(color_index)
if 0 <= index < len(COLOR_PALETTE):
return COLOR_PALETTE[index]
except (ValueError, TypeError):
pass
return COLOR_PALETTE[0]
def note_exists(note_id):
"""檢查 note_id 是否存在"""
try:
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
cursor.execute('SELECT COUNT(*) FROM notes WHERE note_id = ?', (note_id,))
count = cursor.fetchone()[0]
conn.close()
return count > 0
except Exception as e:
print(f"檢查 note 是否存在失敗: {e}")
return False
def lora_msg_id_exists(lora_msg_id):
"""檢查 lora_msg_id 是否存在"""
try:
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
cursor.execute('SELECT COUNT(*) FROM notes WHERE lora_msg_id = ?', (lora_msg_id,))
count = cursor.fetchone()[0]
conn.close()
return count > 0
except Exception as e:
print(f"檢查 lora_msg_id 是否存在失敗: {e}")
return False
def get_note_id_by_lora_msg_id(lora_msg_id):
"""透過 lora_msg_id 取得 note_id"""
try:
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
cursor.execute('SELECT note_id FROM notes WHERE lora_msg_id = ?', (lora_msg_id,))
row = cursor.fetchone()
conn.close()
return row[0] if row else None
except Exception as e:
print(f"透過 lora_msg_id 取得 note_id 失敗: {e}")
return None
def save_or_update_ack_record(note_id, lora_node_id, hop_limit=None, hop_start=None):
"""儲存或更新 ACK 記錄"""
try:
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
timestamp = int(time.time() * 1000)
cursor.execute('''
SELECT ack_id FROM ack_records
WHERE note_id = ? AND lora_node_id = ?
''', (note_id, lora_node_id))
existing_record = cursor.fetchone()
if existing_record:
cursor.execute('''
UPDATE ack_records
SET updated_at = ?, hop_limit = ?, hop_start = ?
WHERE note_id = ? AND lora_node_id = ?
''', (timestamp, hop_limit, hop_start, note_id, lora_node_id))
conn.commit()
conn.close()
print(f" -> 已更新 ACK 記錄 (note_id={note_id}, lora_node_id={lora_node_id}, hop_limit={hop_limit}, hop_start={hop_start})")
return True
else:
ack_id = str(uuid.uuid4())
cursor.execute('''
INSERT INTO ack_records (ack_id, note_id, created_at, updated_at, lora_node_id, hop_limit, hop_start)
VALUES (?, ?, ?, ?, ?, ?, ?)
''', (ack_id, note_id, timestamp, timestamp, lora_node_id, hop_limit, hop_start))
conn.commit()
conn.close()
print(f" -> 已新建 USER ACK 記錄 (ack_id={ack_id}, note_id={note_id}, lora_node_id={lora_node_id}, hop_limit={hop_limit}, hop_start={hop_start})")
return True
except Exception as e:
print(f"儲存或更新 USER ACK 記錄失敗: {e}")
return False
def update_note_color(lora_msg_id, author_key, color_index, need_lora_update=False):
"""透過 lora_msg_id 更新 note 的背景顏色,需驗證 author_key"""
try:
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
bg_color = get_color_from_palette(color_index)
timestamp = int(time.time() * 1000)
if need_lora_update:
cursor.execute('''
UPDATE notes
SET bg_color = ?, updated_at = ?, rev = rev + 1, is_need_update_lora = 1
WHERE lora_msg_id = ? AND author_key = ?
''', (bg_color, timestamp, lora_msg_id, author_key))
else:
cursor.execute('''
UPDATE notes
SET bg_color = ?, updated_at = ?, rev = rev + 1
WHERE lora_msg_id = ? AND author_key = ?
''', (bg_color, timestamp, lora_msg_id, author_key))
affected_rows = cursor.rowcount
conn.commit()
conn.close()
return affected_rows > 0
except Exception as e:
print(f"更新 note 顏色失敗: {e}")
return False
def update_note_color_by_note_id(note_id, author_key, color_index, need_lora_update=False):
"""透過 note_id 更新 note 的背景顏色,需驗證 author_key"""
try:
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
bg_color = get_color_from_palette(color_index)
timestamp = int(time.time() * 1000)
if need_lora_update:
cursor.execute('''
UPDATE notes
SET bg_color = ?, updated_at = ?, rev = rev + 1, is_need_update_lora = 1
WHERE note_id = ? AND author_key = ?
''', (bg_color, timestamp, note_id, author_key))
else:
cursor.execute('''
UPDATE notes
SET bg_color = ?, updated_at = ?, rev = rev + 1
WHERE note_id = ? AND author_key = ?
''', (bg_color, timestamp, note_id, author_key))
affected_rows = cursor.rowcount
conn.commit()
conn.close()
return affected_rows > 0
except Exception as e:
print(f"更新 note 顏色失敗: {e}")
return False
def update_note_author(lora_msg_id, author_key):
"""更新 note 的 author_key"""
try:
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
timestamp = int(time.time() * 1000)
cursor.execute('''
UPDATE notes
SET author_key = ?, updated_at = ?, rev = rev + 1
WHERE lora_msg_id = ?
''', (author_key, timestamp, lora_msg_id))
affected_rows = cursor.rowcount
conn.commit()
conn.close()
return affected_rows > 0
except Exception as e:
print(f"更新 note author_key 失敗: {e}")
return False
def archive_note(note_id, author_key, need_lora_update=False):
"""將 note 標記為已刪除 (deleted=1),需驗證 author_key"""
try:
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
timestamp = int(time.time() * 1000)
if need_lora_update:
cursor.execute('''
UPDATE notes
SET deleted = 1, is_pined_note = 0, updated_at = ?, is_need_update_lora = 1
WHERE note_id = ? AND author_key = ?
''', (timestamp, note_id, author_key))
else:
cursor.execute('''
UPDATE notes
SET deleted = 1, is_pined_note = 0, updated_at = ?
WHERE note_id = ? AND author_key = ?
''', (timestamp, note_id, author_key))
affected_rows = cursor.rowcount
conn.commit()
conn.close()
return affected_rows > 0
except Exception as e:
print(f"封存 note 失敗: {e}")
return False
def archive_note_by_lora_msg_id(lora_msg_id, author_key):
"""透過 lora_msg_id 將 note 標記為已刪除 (deleted=1),需驗證 author_key"""
try:
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
timestamp = int(time.time() * 1000)
cursor.execute('''
UPDATE notes
SET deleted = 1, is_pined_note = 0, updated_at = ?
WHERE lora_msg_id = ? AND author_key = ?
''', (timestamp, lora_msg_id, author_key))
affected_rows = cursor.rowcount
conn.commit()
conn.close()
return affected_rows > 0
except Exception as e:
print(f"封存 note 失敗: {e}")
return False
def mark_sheet_notes_deleted(board_id, sheet_id, exclude_note_id=None):
"""將指定 sheetId 的所有 notes 標記為 deleted(排除指定的 note_id)"""
try:
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
timestamp = int(time.time() * 1000)
pattern = '{' + sheet_id + ':%'
if exclude_note_id:
cursor.execute('''
UPDATE notes
SET deleted = 1, updated_at = ?
WHERE board_id = ? AND body LIKE ? AND note_id != ? AND deleted = 0
''', (timestamp, board_id, pattern, exclude_note_id))
else:
cursor.execute('''
UPDATE notes
SET deleted = 1, updated_at = ?
WHERE board_id = ? AND body LIKE ? AND deleted = 0
''', (timestamp, board_id, pattern))
affected_rows = cursor.rowcount
conn.commit()
conn.close()
print(f"[刪除工作表] 已將 {affected_rows} 筆 sheetId={sheet_id} 的 notes 標記為 deleted (board_id={board_id})")
return affected_rows
except Exception as e:
print(f"刪除工作表 notes 失敗: {e}")
return 0
def pin_note_by_lora_msg_id(lora_msg_id, author_key):
"""透過 lora_msg_id 將 note 標記為置頂 (is_pined_note=1),需驗證 author_key 和 lora_msg_id 存在"""
try:
conn = sqlite3.connect(DB_PATH)
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
timestamp = int(time.time() * 1000)
cursor.execute('''
SELECT board_id, reply_lora_msg_id, is_temp_parent_note, deleted
FROM notes
WHERE lora_msg_id = ? AND author_key = ?
''', (lora_msg_id, author_key))
result = cursor.fetchone()
if not result:
conn.close()
return False
board_id = result['board_id']
reply_lora_msg_id = result['reply_lora_msg_id']
is_temp_parent_note = result['is_temp_parent_note']
deleted = result['deleted']
if reply_lora_msg_id is not None and reply_lora_msg_id != '':
print(f" -> 無法置頂回覆訊息")
conn.close()
return False
if is_temp_parent_note == 1:
print(f" -> 無法置頂臨時父訊息")
conn.close()
return False
if deleted == 1:
print(f" -> 無法置頂已封存的訊息")
conn.close()
return False
cursor.execute('''
UPDATE notes
SET is_pined_note = 0, updated_at = ?
WHERE board_id = ? AND is_pined_note = 1
''', (timestamp, board_id))
cursor.execute('''
UPDATE notes
SET is_pined_note = 1, updated_at = ?
WHERE lora_msg_id = ? AND author_key = ?
''', (timestamp, lora_msg_id, author_key))
affected_rows = cursor.rowcount
conn.commit()
conn.close()
return affected_rows > 0
except Exception as e:
print(f"置頂 note 失敗: {e}")
return False
def save_lora_note(lora_msg_id, board_id, body, bg_color='', author_key='', reply_lora_msg_id=None, lora_node_id=''):
"""儲存 LoRa 接收的 note"""
try:
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
timestamp = int(time.time() * 1000)
status = 'LoRa received'
note_id = generate_note_id()
cursor.execute('''
INSERT INTO notes (note_id, reply_lora_msg_id, board_id, body, bg_color, status,
created_at, updated_at, author_key, rev, deleted, lora_msg_id, lora_node_id)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 1, 0, ?, ?)
''', (note_id, reply_lora_msg_id, board_id, body, bg_color, status, timestamp, timestamp, author_key, lora_msg_id, lora_node_id))
ch_cfg = get_channel_config(board_id)
ch_max_notes = ch_cfg.get('max_notes', MAX_NOTES)
auto_archive_old_notes(cursor, board_id, ch_max_notes)
conn.commit()
conn.close()
return True
except Exception as e:
print(f"儲存 LoRa note 失敗: {e}")
return False
def get_oldest_lan_only_note(board_id):
"""取得最舊的 LAN only 狀態的 note"""
try:
conn = sqlite3.connect(DB_PATH)
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
cursor.execute('''
SELECT note_id, body, bg_color, author_key, created_at, reply_lora_msg_id
FROM notes
WHERE board_id = ? AND (status = 'LAN only' OR status = 'Sending') AND deleted = 0
ORDER BY created_at ASC
LIMIT 1
''', (board_id,))
row = cursor.fetchone()
conn.close()
if row:
return {
'note_id': row['note_id'],
'body': row['body'],
'bg_color': row['bg_color'],
'author_key': row['author_key'],
'created_at': row['created_at'],
'reply_lora_msg_id': row['reply_lora_msg_id']
}
return None
except Exception as e:
print(f"取得最舊 LAN only note 失敗: {e}")
return None
def get_note_need_update_lora(board_id):
"""取得一個需要更新到 LoRa 的 note (is_need_update_lora=1)"""
try:
conn = sqlite3.connect(DB_PATH)
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
cursor.execute('''
SELECT note_id, body, bg_color, author_key, deleted, lora_msg_id
FROM notes
WHERE board_id = ? AND is_need_update_lora = 1
ORDER BY updated_at ASC
LIMIT 1
''', (board_id,))
row = cursor.fetchone()
if row:
note_data = {
'note_id': row['note_id'],
'body': row['body'],
'bg_color': row['bg_color'],
'author_key': row['author_key'],
'deleted': row['deleted'],
'lora_msg_id': row['lora_msg_id']
}
timestamp = int(time.time() * 1000)
cursor.execute('''
UPDATE notes
SET is_need_update_lora = 0, updated_at = ?
WHERE note_id = ?
''', (timestamp, row['note_id']))
conn.commit()
conn.close()
return note_data
conn.close()
return None
except Exception as e:
print(f"取得需要更新的 note 失敗: {e}")
return None
def update_note_status(note_id, status):
"""更新 note 的 status"""
try:
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
timestamp = int(time.time() * 1000)
cursor.execute('''
UPDATE notes
SET status = ?, updated_at = ?
WHERE note_id = ?
''', (status, timestamp, note_id))
affected_rows = cursor.rowcount
conn.commit()
conn.close()
return affected_rows > 0
except Exception as e:
print(f"更新 note status 失敗: {e}")
return False
def update_note_lora_msg_id(note_id, lora_msg_id):
"""更新 note 的 lora_msg_id"""
try:
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
timestamp = int(time.time() * 1000)
cursor.execute('''
UPDATE notes
SET lora_msg_id = ?, updated_at = ?
WHERE note_id = ?
''', (lora_msg_id, timestamp, note_id))
affected_rows = cursor.rowcount
conn.commit()
conn.close()
return affected_rows > 0
except Exception as e:
print(f"更新 note lora_msg_id 失敗: {e}")
return False
def update_note_transmit_st_at(note_id):
"""記錄 note 開始傳輸的時間"""
try:
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
timestamp = int(time.time() * 1000)
cursor.execute('''
UPDATE notes
SET transmit_st_at = ?
WHERE note_id = ?
''', (timestamp, note_id))
affected_rows = cursor.rowcount
conn.commit()
conn.close()
return affected_rows > 0
except Exception as e:
print(f"更新 note transmit_st_at 失敗: {e}")
return False
def get_notes_from_db(board_id, include_deleted=False):
"""從資料庫取得 notes"""
try:
conn = sqlite3.connect(DB_PATH)
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
ch_cfg = get_channel_config(board_id)
max_notes = ch_cfg.get('max_notes', 200)
max_archived = ch_cfg.get('max_archived_notes', 200)
# 分開查詢:非 table 指令的 notes 與 table 指令的 notes
# table 指令的 body 匹配 {xxxxxx:...} 格式
table_glob = '{[a-z0-9][a-z0-9][a-z0-9][a-z0-9][a-z0-9][a-z0-9]:*'