-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
1954 lines (1500 loc) · 73.2 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
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 flet as ft
import meshtastic
import meshtastic.tcp_interface
import meshtastic.ble_interface
import sqlite3
import time
import os
import platform
from pubsub import pub
from datetime import datetime
import queue
import webbrowser
def check_android_permissions(page):
if platform.system() == "Linux" and "ANDROID_STORAGE" in os.environ:
download_path = "/storage/emulated/0/Download"
if not os.access(download_path, os.R_OK):
# Permission is not granted
show_permission_dialog(page)
def show_permission_dialog(page):
def close_dialog(e):
# Only closes the dialog
permission_dialog.open = False
page.update()
permission_dialog = ft.AlertDialog(
modal=True,
title=ft.Text("Permission Required"),
content=ft.Text(
"This app requires permission to access the Download folder to import and export files. "
"Please grant the necessary permissions in the android app permission settings."
),
actions=[
ft.TextButton("OK", on_click=close_dialog)
],
on_dismiss=lambda e: permission_dialog.close(),
)
page.dialog = permission_dialog
permission_dialog.open = True
page.update()
# Global variables for database paths
DATABASE_FILENAME = "antenna_tester.db"
CSV_FILENAME = "exported_results"
# Set the correct path for DATABASE_FILEPATH
if platform.system() == "Linux" and "ANDROID_STORAGE" in os.environ:
DATABASE_PATH = "/data/data/com.flet.meshtenna/files"
CSV_EXPORT_PATH = "/storage/emulated/0/Download"
else:
DATABASE_PATH = os.path.expanduser("~/Documents")
CSV_EXPORT_PATH = DATABASE_PATH
# Create directory if it does not exist
if not os.path.exists(DATABASE_PATH):
os.makedirs(DATABASE_PATH)
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
DATABASE_FILEPATH = os.path.join(DATABASE_PATH, DATABASE_FILENAME)
EXPORT_CSV_FILE = os.path.join(CSV_EXPORT_PATH, f"{CSV_FILENAME}_{timestamp}.csv")
#EXPORT_CSV_FILE = os.path.join("/storage/emulated/0/Download", "exported_results.csv")
# Queue for database queries
db_queue = queue.Queue()
is_db_processing = False
# Handles all database accesses of any kind
def database_manager(query, params=(), fetchone=False, fetchall=False, commit=False):
global is_db_processing
result = None
# Insert request into the queue
db_queue.put((query, params, fetchone, fetchall, commit))
# If no processing is currently running, start it
if not is_db_processing:
result = process_db_queue()
return result
def process_db_queue():
global is_db_processing
result = None
if not db_queue.empty():
is_db_processing = True
# Get next request from the queue
query, params, fetchone, fetchall, commit = db_queue.get()
# Performs the actual database operation
conn = sqlite3.connect(DATABASE_FILEPATH, check_same_thread=False)
cursor = conn.cursor()
try:
cursor.execute(query, params)
if fetchone:
result = cursor.fetchone()
if fetchall:
result = cursor.fetchall()
if commit:
conn.commit()
except Exception as e:
print(f"Database error: {e}")
result = []
finally:
cursor.close()
conn.close()
# Process the next request
is_db_processing = False
process_db_queue() # Repeat until the queue is empty
return result if result is not None else []
def initialize_database(page):
# Check if the database already exists
db_exists = os.path.exists(DATABASE_FILEPATH)
query = '''
CREATE TABLE IF NOT EXISTS results (
id INTEGER PRIMARY KEY AUTOINCREMENT,
antenna_name TEXT,
url TEXT,
notes TEXT,
location TEXT,
node_name TEXT,
node_id TEXT,
connection_type TEXT,
address TEXT,
timestamp TEXT,
rssi INTEGER,
snr REAL
)
'''
database_manager(query, commit=True)
# After the query, check again if the database now exists
if os.path.exists(DATABASE_FILEPATH) and not db_exists:
page.overlay.append(ft.SnackBar(ft.Text("Database created successfully!"), open=True))
elif db_exists:
page.overlay.append(ft.SnackBar(ft.Text("Database already exists."), open=True))
else:
page.overlay.append(ft.SnackBar(ft.Text("Failed to create the database."), open=True))
page.update()
# Global variables for storing sent message ID and test start time
sent_message_id = None
test_start_time = None
test_running = False
settings_saved = False # This variable checks if the settings have been saved
stop_sending = False
# Global variables for message and ACK count
messages_sent = 0
acks_received = 0
ack_queue = queue.Queue() # Queue for processing ACKs
def on_setting_change(e):
global settings_saved
settings_saved = False
def get_min_rssi(antenna_name=None, location=None):
query = "SELECT MIN(rssi) FROM results WHERE 1=1"
params = []
if antenna_name:
query += " AND antenna_name = ?"
params.append(antenna_name)
if location and location != "All Locations":
query += " AND location = ?"
params.append(location)
result = database_manager(query, params, fetchone=True)
return result[0] if result and result[0] is not None else -120
def get_max_rssi(antenna_name=None, location=None):
query = "SELECT MAX(rssi) FROM results WHERE 1=1"
params = []
if antenna_name:
query += " AND antenna_name = ?"
params.append(antenna_name)
if location and location != "All Locations":
query += " AND location = ?"
params.append(location)
result = database_manager(query, params, fetchone=True)
return result[0] if result and result[0] is not None else 0
def get_min_snr(location=None):
query = "SELECT MIN(snr) FROM results WHERE 1=1"
params = []
if location and location != "All Locations":
query += " AND location = ?"
params.append(location)
result = database_manager(query, params, fetchone=True)
return result[0] if result and result[0] is not None else -100
def get_max_snr(location=None):
query = "SELECT MAX(snr) FROM results WHERE 1=1"
params = []
if location and location != "All Locations":
query += " AND location = ?"
params.append(location)
result = database_manager(query, params, fetchone=True)
return result[0] if result and result[0] is not None else 100
def calculate_avg_rssi(antenna_name=None, location=None):
query = "SELECT rssi FROM results WHERE 1=1"
params = []
if antenna_name:
query += " AND antenna_name = ?"
params.append(antenna_name)
if location and location != "All Locations":
query += " AND location = ?"
params.append(location)
rssi_values = [row[0] for row in database_manager(query, params, fetchall=True)]
if not rssi_values:
#print(f"No RSSI values found for antenna {antenna_name} at location {location}")
return 0
avg_rssi = sum(rssi_values) / len(rssi_values)
#print(f"Avg RSSI for antenna {antenna_name} at location {location}: {avg_rssi}")
return avg_rssi
def calculate_avg_snr(location=None):
query = "SELECT snr FROM results WHERE location = ?"
params = [location]
snr_values = [row[0] for row in database_manager(query, params, fetchall=True)]
if not snr_values:
return 0
avg_snr = sum(snr_values) / len(snr_values)
return avg_snr
def calculate_rssi_score(antenna_name=None, location=None):
avg_rssi = calculate_avg_rssi(antenna_name=antenna_name, location=location)
min_rssi = get_min_rssi(location=location)
max_rssi = get_max_rssi(location=location)
if max_rssi == min_rssi:
return 5.0
score = (avg_rssi - min_rssi) / (max_rssi - min_rssi) * 9 + 1
return max(1.0, min(10.0, round(score, 1)))
def calculate_snr_score(location=None):
avg_snr = calculate_avg_snr(location=location)
result = database_manager("SELECT MIN(snr), MAX(snr) FROM results", fetchone=True)
global_min_snr, global_max_snr = result
if global_max_snr == global_min_snr:
return 5.0
score = (avg_snr - global_min_snr) / (global_max_snr - global_min_snr) * 9 + 1
return max(1.0, min(10.0, round(score, 1)))
expanded_row = None
expanded_row_text_elements = []
def toggle_row(additional_info_row, text_elements, page):
#print(f"Toggling row for antenna: {text_elements[0].value}")
global expanded_row, expanded_row_text_elements
# Close previous row
if expanded_row and expanded_row != additional_info_row:
expanded_row.visible = False
for text in expanded_row_text_elements:
text.weight = "normal"
expanded_row = None
# Toggle visibility of current row
is_expanded = not additional_info_row.visible
additional_info_row.visible = is_expanded
# Set the font to bold when the row is visible
for text in text_elements:
text.weight = "bold" if is_expanded else "normal"
if is_expanded:
expanded_row = additional_info_row
expanded_row_text_elements = text_elements
else:
expanded_row = None
expanded_row_text_elements = []
#print(f"Row visibility: {additional_info_row.visible}") # Sichtbarkeit überprüfen
page.update()
def main(page: ft.Page):
check_android_permissions(page)
global interface, stop_sending, connection_status_icon, connection_status_text, test_start_time, sort_column, sort_descending, min_snr, max_snr, min_rssi, max_rssi
interface = None
sort_column = "score" # Sort by "score" by default
sort_descending = True # Sort in descending order by default
# Function to update the GUI for sent messages and ACKs
def update_message_ack_display():
messages_sent_value.value = f"{messages_sent}"
acks_received_value.value = f"{acks_received}"
page.update()
try:
# Initialize the database (creates the table if necessary)
initialize_database(page)
# Execute the SQL queries to fetch MIN/MAX SNR and RSSI
result = database_manager("SELECT MIN(snr), MAX(snr) FROM results", fetchone=True)
min_snr, max_snr = result if result else (None, None)
result = database_manager("SELECT MIN(rssi), MAX(rssi) FROM results", fetchone=True)
min_rssi, max_rssi = result if result else (None, None)
except Exception as e:
print(f"Database operation error: {e}")
error_dialog = ft.AlertDialog(
modal=True,
title=ft.Text("Database Error"),
content=ft.Text(f"An error occurred while accessing the database: {str(e)}"),
actions=[],
actions_alignment=ft.MainAxisAlignment.END,
)
page.overlay.append(error_dialog)
error_dialog.open = True
page.update()
finally:
# Since no manual `conn` and `cursor` connection is used anymore, no closing is necessary.
pass
def on_connection_type_change(e):
tcp_ip_input.visible = connection_type_dropdown.value == "TCP"
ble_device_input.visible = connection_type_dropdown.value == "BLE"
page.update()
def on_visible_message_change(e):
message_text_input.visible = visible_message_checkbox.value
page.update()
def load_results(location_filter=None):
# Ensure that the database exists
if not os.path.exists(DATABASE_FILEPATH):
page.overlay.append(ft.SnackBar(ft.Text("No database connection."), open=True))
return
# Load distinct locations from the database
location_query = "SELECT DISTINCT location FROM results"
locations = ["All Locations"] + [row[0] for row in database_manager(location_query, fetchall=True)]
location_filter_dropdown.options = [ft.dropdown.Option(loc) for loc in locations]
# Set default value for location_filter
if not location_filter_dropdown.value:
location_filter_dropdown.value = "All Locations"
location_filter = location_filter_dropdown.value
rows = []
# Create the data query based on the location_filter
if location_filter == "All Locations" or location_filter is None:
query = '''SELECT id, antenna_name, location, url, notes FROM results GROUP BY antenna_name, location, url, notes'''
params = ()
else:
query = '''SELECT id, antenna_name, location, url, notes FROM results WHERE location = ? GROUP BY antenna_name, location, url, notes'''
params = (location_filter,)
# Retrieve results from the database
results = database_manager(query, params, fetchall=True)
# Calculate avg_rssi and score for each antenna, based on the selected location
for result_row in results:
avg_rssi = calculate_avg_rssi(antenna_name=result_row[1], location=location_filter)
score = calculate_rssi_score(antenna_name=result_row[1], location=location_filter)
rows.append((result_row[0], result_row[1], avg_rssi, score, result_row[3], result_row[4]))
# Sort according to the selected criterion
if sort_column == "antenna_name":
rows = sorted(rows, key=lambda x: x[1], reverse=sort_descending)
elif sort_column == "rssi":
rows = sorted(rows, key=lambda x: x[2], reverse=sort_descending)
elif sort_column == "score":
rows = sorted(rows, key=lambda x: x[3], reverse=sort_descending)
# Display results in the table
# Create table rows
results_table.rows = [
row for result_rows in rows
for row in create_antenna_row(result_rows, page)
#if row.visible # Only visible rows
]
# Update the page only if at least one row is visible
#if results_table.rows:
page.update()
def load_locations(sort_by="score"):
location_query = "SELECT DISTINCT location FROM results"
locations = [row[0] for row in database_manager(location_query, fetchall=True)]
rows = []
for location in locations:
avg_snr = calculate_avg_snr(location=location)
score = calculate_snr_score(location=location)
rows.append((location, avg_snr, score))
# Sorting based on the selected column
if sort_by == "location_name":
rows = sorted(rows, key=lambda x: x[0], reverse=sort_descending)
elif sort_by == "snr":
rows = sorted(rows, key=lambda x: x[1], reverse=sort_descending)
elif sort_by == "score":
rows = sorted(rows, key=lambda x: x[2], reverse=sort_descending)
locations_table.rows = [row for result_rows in rows for row in create_location_row(result_rows, page)]
page.update()
def open_url(url):
if platform.system() == "Windows":
webbrowser.open(url)
elif platform.system() == "Linux" and "ANDROID_STORAGE" in os.environ:
# Use an Android-specific call
page.launch_url(url)
else:
# Fallback for other platforms
webbrowser.open(url)
def create_antenna_row(row, page):
antenna_name = row[1]
location = location_filter_dropdown.value # Location from the dropdown filter
#print(f"Row data: {row}")
# Calculation of avg_rssi and score using the designated functions
avg_rssi = calculate_avg_rssi(antenna_name=antenna_name, location=location)
score = calculate_rssi_score(antenna_name=antenna_name, location=location)
avg_rssi_text = "N/A" if avg_rssi is None else str(round(avg_rssi, 2))
score_text = "N/A" if score is None else str(round(score, 2))
url = row[4] if row[4] is not None else "" # Ensure URL is present
notes = row[5] if row[5] not in [None, ""] else "No Notes"
# Text elements for the main row
text_elements = [
ft.Text(antenna_name, size=12),
ft.Text(avg_rssi_text, size=12),
ft.Text(score_text, size=12)
]
# Additional detail row (visible on click)
additional_info_row = ft.DataRow(
cells=[
ft.DataCell(
ft.TextButton(
text="Shop Link",
on_click=lambda e: open_url(url)
) if url else ft.Text("No Link")
),
ft.DataCell(ft.Text("Notes:", weight="bold", size=12)),
ft.DataCell(ft.Text(notes))
],
visible=False # Temporarily set the row to 'visible'
)
# Main antenna row
expandable_row = ft.DataRow(
cells=[
ft.DataCell(ft.Container(content=text_elements[0], alignment=ft.alignment.center)),
ft.DataCell(ft.Container(content=text_elements[1], alignment=ft.alignment.center)),
ft.DataCell(ft.Container(content=text_elements[2], alignment=ft.alignment.center))
],
on_select_changed=lambda _: toggle_row(additional_info_row, text_elements, page)
)
return [expandable_row, additional_info_row]
def create_location_row(row, page):
location_name = row[0]
avg_snr = round(row[1], 2) # The average SNR for the location
score = round(row[2], 2) # The calculated score based on avg_snr
score_text = "N/A" if score is None else str(score)
text_elements = [
ft.Text(location_name, size=12),
ft.Text(str(avg_snr), size=12),
ft.Text(score_text, size=12)
]
# SQL query to determine the antenna with the best RSSI value for this location
best_antenna = database_manager('''SELECT antenna_name, rssi FROM results WHERE location=? ORDER BY rssi DESC LIMIT 1''', (location_name,), fetchone=True)
best_antenna_text = best_antenna[0] if best_antenna else "No Antenna Found"
additional_info_row = ft.DataRow(
cells=[
ft.DataCell(ft.Text("Best antenna for this location:", weight="bold", size=12)),
ft.DataCell(ft.Text(best_antenna_text, weight="bold", size=12)),
ft.DataCell(ft.Text(""))
],
visible=False
)
expandable_row = ft.DataRow(
cells=[
ft.DataCell(ft.Container(content=text_elements[0], alignment=ft.alignment.center)), # Centered
ft.DataCell(ft.Container(content=text_elements[1], alignment=ft.alignment.center)), # Centered
ft.DataCell(ft.Container(content=text_elements[2], alignment=ft.alignment.center)) # Centered
],
on_select_changed=lambda _: toggle_row(additional_info_row, text_elements, page)
)
return [expandable_row, additional_info_row]
def start_timer():
global test_start_time
test_start_time = datetime.now()
def update_elapsed_time():
if test_start_time is not None and not stop_sending:
elapsed_time = datetime.now() - test_start_time
hours, remainder = divmod(elapsed_time.seconds, 3600)
minutes, seconds = divmod(remainder, 60)
elapsed_time_label.value = f"Elapsed Time: {hours:02}:{minutes:02}:{seconds:02}"
page.update()
def send_message(destination_node_id):
global sent_message_id, messages_sent
try:
if visible_message_checkbox.value:
sent_message = interface.sendText(
text=message_text_input.value,
destinationId=destination_node_id,
wantAck=True
)
else:
sent_message = interface.sendData(
data=b'',
destinationId=destination_node_id,
wantAck=True
)
# Direct assignment of the ID
sent_message_id = sent_message.id
messages_sent += 1 # Increment message counter
update_message_ack_display() # Update GUI for sent messages
#print(f"Sent message ID: {sent_message_id}")
except Exception as ex:
connection_status_text.value = f"Error: {str(ex)}"
connection_status_icon.color = "red"
page.update()
def save_settings(e):
global settings_saved
validate_interval(interval_input)
tcp_ip = tcp_ip_input.value if connection_type_dropdown.value == "TCP" else ""
ble_device_name = ble_device_input.value if connection_type_dropdown.value == "BLE" else ""
# Validation of the Destination Node ID
destination_node_id = destination_node_input.value.strip()
# Remove all exclamation marks and then add only one
destination_node_id = destination_node_id.lstrip("!") # Removes all leading exclamation marks
destination_node_id = "!" + destination_node_id # Adds a single exclamation mark
# Update the input field with the correct Destination Node ID
destination_node_input.value = destination_node_id
visible_message = message_text_input.value if visible_message_checkbox.value else ""
page.client_storage.set("antenna_name", antenna_name_input.value)
page.client_storage.set("url", url_input.value or "")
page.client_storage.set("notes", notes_input.value or "")
page.client_storage.set("location", location_input_dropdown.value if location_input_dropdown.value != "New Location" else new_location_input.value)
page.client_storage.set("connection_type", connection_type_dropdown.value)
page.client_storage.set("tcp_ip", tcp_ip)
page.client_storage.set("ble_device_name", ble_device_name)
page.client_storage.set("destination_node_id", destination_node_id)
page.client_storage.set("visible_message", message_text_input.value or "")
page.client_storage.set("send_visible_message", visible_message_checkbox.value)
settings_saved = True
page.overlay.append(ft.SnackBar(ft.Text("Settings saved! Make sure the BLE/TCP node is not connected to any other device before you start the test! "), open=True))
page.update()
def load_settings():
try:
# Load all locations from the database
locations = ["New Location"] + [row[0] for row in database_manager("SELECT DISTINCT location FROM results", fetchall=True)]
# Update the location dropdown with the new values
location_input_dropdown.options = [ft.dropdown.Option(loc) for loc in locations]
# Set the saved location value
location_value = page.client_storage.get("location") or ""
if location_value in locations:
location_input_dropdown.value = location_value
new_location_input.visible = False
location_input_dropdown.visible = True
cancel_location_button.visible = False
save_button.disabled = False # Enable the Save button when a valid location is loaded
else:
location_input_dropdown.value = "New Location"
new_location_input.value = location_value
new_location_input.visible = True
location_input_dropdown.visible = False
cancel_location_button.visible = True
save_button.disabled = False # Enable the Save button when a new location is entered
except Exception as e:
print(f"Error loading settings: {e}")
# Load the remaining saved settings
antenna_name_value = page.client_storage.get("antenna_name") or ""
url_value = page.client_storage.get("url") or ""
notes_value = page.client_storage.get("notes") or ""
connection_type_value = page.client_storage.get("connection_type") or "TCP"
tcp_ip_value = page.client_storage.get("tcp_ip") or ""
ble_device_name_value = page.client_storage.get("ble_device_name") or ""
destination_node_id_value = page.client_storage.get("destination_node_id") or ""
visible_message_value = page.client_storage.get("visible_message") or ""
send_visible_message_value = page.client_storage.get("send_visible_message") or False
# Set the loaded values in the corresponding fields
antenna_name_input.value = antenna_name_value
url_input.value = url_value
notes_input.value = notes_value
connection_type_dropdown.value = connection_type_value
tcp_ip_input.value = tcp_ip_value
ble_device_input.value = ble_device_name_value
destination_node_input.value = destination_node_id_value
message_text_input.value = visible_message_value
visible_message_checkbox.value = send_visible_message_value
# Visibility based on the Connection Type
tcp_ip_input.visible = connection_type_value == "TCP"
ble_device_input.visible = connection_type_value == "BLE"
message_text_input.visible = send_visible_message_value
# Enable Save button when all required fields are filled
save_button.disabled = not (
antenna_name_input.value.strip() and
location_input_dropdown.value and
connection_type_dropdown.value and
destination_node_input.value.strip()
)
# Update the page to display the changes
page.update()
def connect_to_device():
global interface
try:
connection_status_icon.color = "yellow"
connection_status_text.value = "Setting up connection..."
page.update()
connection_type = connection_type_dropdown.value
tcp_ip = tcp_ip_input.value
ble_device_name = ble_device_input.value
if connection_type == "TCP":
interface = meshtastic.tcp_interface.TCPInterface(hostname=tcp_ip)
elif connection_type == "BLE":
interface = meshtastic.ble_interface.BLEInterface(ble_device_name)
pub.subscribe(on_receive, "meshtastic.receive")
#print(f"Connected via {connection_type}")
return True
except Exception as ex:
connection_status_icon.color = "red"
connection_status_text.value = f"Connection error: {str(ex)}"
page.update()
return False
# Queue for ACK processing directly within the existing flow
def process_ack_queue():
while not ack_queue.empty():
ack_data = ack_queue.get()
# Insert into the database
try:
query = '''
INSERT INTO results (antenna_name, url, notes, location, node_name, node_id, connection_type, address, timestamp, rssi, snr)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
'''
params = (
ack_data['antenna_name'],
ack_data['url'],
ack_data['notes'],
ack_data['location'],
"Unknown Node",
ack_data['from_id'],
connection_type_dropdown.value,
tcp_ip_input.value if connection_type_dropdown.value == "TCP" else ble_device_input.value,
datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
ack_data['rssi'],
ack_data['snr']
)
database_manager(query, params, commit=True)
#print("Data inserted successfully:", ack_data)
page.overlay.append(ft.SnackBar(ft.Text(f"ACK received and logged"), open=True))
except Exception as e:
print(f"Error while inserting into database: {e}")
page.overlay.append(ft.SnackBar(ft.Text(f"Error while inserting data: {e}"), open=True))
# Update the UI after processing
page.update()
# on_receive remains unchanged, puts the data into the queue
def on_receive(packet, interface):
global acks_received
from_id = packet.get("fromId", "")
request_id = packet.get("decoded", {}).get("requestId", None)
rssi = packet.get("rxRssi", None)
snr = packet.get("rxSnr", None)
# Check if the ACK was received for the correct message
if from_id == destination_node_input.value and request_id == sent_message_id:
if request_id is not None:
acks_received += 1 # Increment ACK counter
ack_data = {
'antenna_name': antenna_name_input.value,
'url': url_input.value,
'notes': notes_input.value,
'location': location_input_dropdown.value if location_input_dropdown.value != "New Location" else new_location_input.value,
'from_id': from_id,
'rssi': rssi,
'snr': snr
}
ack_queue.put(ack_data) # Put ACK data into the queue
update_message_ack_display() # Update GUI for received ACKs
# Process the ACK data immediately upon reception
process_ack_queue()
def disable_data_buttons():
delete_antenna_button.disabled = True
delete_location_button.disabled = True
delete_database_button.disabled = True
export_csv_button.disabled = True
import_db_button.disabled = True # Import DB button disabled
export_db_button.disabled = True # Export DB button disabled
page.update()
def enable_data_buttons():
delete_antenna_button.disabled = False
delete_location_button.disabled = False
delete_database_button.disabled = False
export_csv_button.disabled = False
import_db_button.disabled = False # Import DB button enabled
export_db_button.disabled = False # Export DB button enabled
page.update()
def start_sending(e):
global stop_sending, messages_sent, acks_received, test_running
test_running = True
stop_sending = False
messages_sent = 0 # Reset message counter
acks_received = 0 # Reset ACK counter
update_message_ack_display() # Set GUI counters to 0
# Reset the display
messages_sent_value.value = "0"
acks_received_value.value = "0"
page.update()
# Disable data buttons when the test starts
disable_data_buttons()
global settings_saved
if not settings_saved:
page.overlay.append(ft.SnackBar(ft.Text("Please complete all fields and save settings before starting the test."), open=True))
page.update()
return
# Check if "New Location" is selected and not saved
if location_input_dropdown.value == "New Location" and not new_location_input.value.strip():
page.overlay.append(ft.SnackBar(ft.Text("Please complete all fields and save settings before starting the test."), open=True))
page.update()
return
# Check if all required fields are filled
if not (
antenna_name_input.value.strip() and
location_input_dropdown.value and
connection_type_dropdown.value and
destination_node_input.value.strip()
):
page.overlay.append(ft.SnackBar(ft.Text("Please complete all fields and save settings before starting the test."), open=True))
page.update()
return
destination_node_id = destination_node_input.value
countdown_label.value = ""
if interface is None:
if not connect_to_device():
return
# Get the interval from the input field
interval = int(interval_input.value) if interval_input.value.isdigit() else 30
progress_bar.visible = True
simulate_connection_setup(destination_node_id)
start_timer()
# Main test loop
while not stop_sending:
# Countdown before sending the next message
countdown(interval)
if stop_sending:
break
# Send message
send_message(destination_node_id)
# Process the ACK queue after each message
process_ack_queue()
# Update the elapsed time
update_elapsed_time()
page.update()
# Ensure all ACKs are processed
stop_sending_messages(None)
def stop_sending_messages(e):
global stop_sending, interface, test_running
test_running = False
stop_sending = True
progress_bar.visible = False
countdown_label.value = ""
test_start_time = None
elapsed_time_label.value = "Elapsed Time: 00:00:00"
if interface is not None:
try:
interface.close()
interface = None
connection_status_icon.color = "red"
connection_status_text.value = "No connection"
except Exception as ex:
page.overlay.append(ft.SnackBar(ft.Text(f"Error: {str(ex)}"), open=True))
page.overlay.append(ft.SnackBar(ft.Text("Test stopped by user."), open=True))
enable_data_buttons()
page.update()
def simulate_connection_setup(destination_node_id):
global messages_sent