-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmeshcore_flasher.py
More file actions
executable file
·6886 lines (5946 loc) · 339 KB
/
meshcore_flasher.py
File metadata and controls
executable file
·6886 lines (5946 loc) · 339 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
#!/usr/bin/env python3
"""
Meshcore Firmware Editor and Flasher
A simple GUI tool to change BLE name and flash firmware to MeshCore devices
Copyright (c) 2024 MeshCore
Licensed under the MIT License
"""
import tkinter as tk
from tkinter import ttk, filedialog, messagebox, scrolledtext
import os
import urllib.request
import json
from datetime import datetime
import subprocess
import threading
import tempfile
import shutil
import time
import sys
import configparser
import re
import http.server
import socketserver
import socket
import asyncio
import webbrowser
from urllib.parse import urlparse
# Try to import QScintilla for advanced code editing
HAS_QSCINTILLA = False
QSCINTILLA_EDITOR = None
try:
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtCore import Qt, QTimer
from PyQt5.Qsci import QsciScintilla, QsciLexerCPP, QsciLexerProperties
from PyQt5.QtGui import QColor
import sip
HAS_QSCINTILLA = True
except ImportError:
try:
from PyQt6.QtWidgets import QApplication, QWidget
from PyQt6.QtCore import Qt, QTimer
from PyQt6.Qsci import QsciScintilla, QsciLexerCPP, QsciLexerProperties
from PyQt6.QtGui import QColor
import sip
HAS_QSCINTILLA = True
except ImportError:
HAS_QSCINTILLA = False
# GitHub repository URLs
GITHUB_API_BASE = "https://api.github.com/repos/meshcore-dev/MeshCore"
GITHUB_BRANCHES_URL = f"{GITHUB_API_BASE}/branches"
GITHUB_TAGS_URL = f"{GITHUB_API_BASE}/tags"
GITHUB_RAW_URL = "https://raw.githubusercontent.com/meshcore-dev/MeshCore/{ref}/examples/{firmware_type}/main.cpp"
MESHCORE_FIRMWARE_REPO_URL = "https://github.com/meshcore-dev/MeshCore.git"
class QScintillaWrapper:
"""Wrapper class to integrate QScintilla with Tkinter - provides ScrolledText-compatible interface"""
def __init__(self, parent_frame, language='cpp'):
self.parent_frame = parent_frame
self.language = language
self.use_qscintilla = False
self.qsci_editor = None
self.container_frame = None
if HAS_QSCINTILLA:
try:
# Create QApplication if it doesn't exist
if not QApplication.instance():
self.qapp = QApplication([])
else:
self.qapp = QApplication.instance()
# Create container frame for embedding
self.container_frame = tk.Frame(parent_frame)
# Create QScintilla editor
self.qsci_editor = QsciScintilla()
# Set up lexer based on language
if language == 'cpp':
lexer = QsciLexerCPP()
lexer.setDefaultFont(self.qsci_editor.font())
self.qsci_editor.setLexer(lexer)
elif language == 'ini' or language == 'properties':
lexer = QsciLexerProperties()
lexer.setDefaultFont(self.qsci_editor.font())
self.qsci_editor.setLexer(lexer)
# Configure editor features
self.qsci_editor.setUtf8(True)
self.qsci_editor.setAutoIndent(True)
self.qsci_editor.setIndentationGuides(True)
self.qsci_editor.setIndentationsUseTabs(False)
self.qsci_editor.setIndentationWidth(2)
self.qsci_editor.setTabWidth(2)
self.qsci_editor.setBraceMatching(QsciScintilla.BraceMatch.SloppyBraceMatch)
self.qsci_editor.setCaretLineVisible(True)
self.qsci_editor.setCaretLineBackgroundColor(QColor("#e8e8e8"))
self.qsci_editor.setMarginType(0, QsciScintilla.MarginType.NumberMargin)
self.qsci_editor.setMarginWidth(0, "0000")
self.qsci_editor.setMarginsBackgroundColor(QColor("#f0f0f0"))
self.qsci_editor.setMarginsForegroundColor(QColor("#808080"))
self.qsci_editor.setFolding(QsciScintilla.FoldStyle.PlainFoldStyle)
self.qsci_editor.setFoldMarginColors(QColor("#f0f0f0"), QColor("#f0f0f0"))
# Note: Embedding PyQt widgets in Tkinter is complex and platform-specific
# For now, we'll use a simpler approach: create the QScintilla widget
# but display it in a way that works. Full embedding requires additional setup.
# This is a placeholder - in a production environment, you might want to:
# 1. Use a library like 'pyqt5-tk' if available
# 2. Use platform-specific embedding code
# 3. Or switch the entire app to PyQt
# For now, we'll attempt basic embedding on Windows, but fall back gracefully
try:
wid = self.container_frame.winfo_id()
if sys.platform == "win32":
# Windows: Attempt embedding using SetParent
try:
import ctypes
from ctypes import wintypes
# Get QScintilla window handle
qsci_hwnd = int(self.qsci_editor.winId())
# Get Tkinter frame handle
tk_hwnd = wid
# Embed QScintilla into Tkinter frame
ctypes.windll.user32.SetParent(qsci_hwnd, tk_hwnd)
# Show the QScintilla widget
self.qsci_editor.show()
self.use_qscintilla = True
self.editor = self.qsci_editor
except Exception as embed_error:
# Embedding failed, fall back to ScrolledText
raise embed_error
else:
# For Linux/macOS, embedding is more complex
# For now, fall back to ScrolledText
# TODO: Implement proper X11/Cocoa embedding
raise Exception(f"QScintilla embedding not yet implemented for {sys.platform}")
except Exception as e:
# Embedding failed, fall back to ScrolledText
self.use_qscintilla = False
self.qsci_editor = None
self.container_frame = None
self.editor = scrolledtext.ScrolledText(parent_frame, wrap=tk.NONE, font=('Courier', 10))
except Exception as e:
# QScintilla setup failed, use ScrolledText
self.use_qscintilla = False
self.editor = scrolledtext.ScrolledText(parent_frame, wrap=tk.NONE, font=('Courier', 10))
else:
# QScintilla not available, use ScrolledText
self.editor = scrolledtext.ScrolledText(parent_frame, wrap=tk.NONE, font=('Courier', 10))
# Store callbacks for event handling
self._callbacks = {}
def grid(self, **kwargs):
"""Place the editor widget"""
if self.use_qscintilla and self.container_frame:
self.container_frame.grid(**kwargs)
# Resize QScintilla to match container
def resize_editor():
if self.container_frame and self.qsci_editor:
width = self.container_frame.winfo_width()
height = self.container_frame.winfo_height()
if width > 1 and height > 1:
self.qsci_editor.resize(width, height)
self.container_frame.after(100, resize_editor)
# Update on resize
self.container_frame.bind('<Configure>', lambda e: resize_editor())
else:
self.editor.grid(**kwargs)
def get(self, start, end):
"""Get text content - compatible with Tkinter ScrolledText interface"""
if self.use_qscintilla:
text = self.qsci_editor.text()
if start == '1.0' and end == tk.END:
return text
# Handle position-based extraction (simplified)
lines = text.split('\n')
start_line, start_col = map(int, start.split('.'))
if end == tk.END:
end_line, end_col = len(lines), len(lines[-1]) if lines else 0
else:
end_line, end_col = map(int, end.split('.'))
result_lines = lines[start_line-1:end_line]
if result_lines:
result_lines[0] = result_lines[0][start_col:]
result_lines[-1] = result_lines[-1][:end_col]
return '\n'.join(result_lines)
else:
return self.editor.get(start, end)
def delete(self, start, end):
"""Delete text"""
if self.use_qscintilla:
if start == '1.0' and end == tk.END:
self.qsci_editor.clear()
else:
# Handle range deletion (simplified - clear all for now)
self.qsci_editor.clear()
else:
self.editor.delete(start, end)
def insert(self, pos, text):
"""Insert text"""
if self.use_qscintilla:
if pos == '1.0':
self.qsci_editor.setText(text)
else:
# Handle position-based insertion (simplified - append for now)
current = self.qsci_editor.text()
self.qsci_editor.setText(current + text)
else:
self.editor.insert(pos, text)
def bind(self, event, callback):
"""Bind event - maps Tkinter events to QScintilla signals"""
if self.use_qscintilla:
# Map Tkinter events to QScintilla signals
if event == '<KeyRelease>':
self.qsci_editor.textChanged.connect(lambda: callback(None))
elif event == '<Button-1>':
self.qsci_editor.cursorPositionChanged.connect(lambda: callback(None))
self._callbacks[event] = callback
else:
self.editor.bind(event, callback)
def tag_config(self, tag, **kwargs):
"""Configure text tag - only works with ScrolledText"""
if not self.use_qscintilla:
self.editor.tag_config(tag, **kwargs)
def tag_add(self, tag, start, end):
"""Add tag to text range - only works with ScrolledText"""
if not self.use_qscintilla:
self.editor.tag_add(tag, start, end)
def tag_remove(self, tag, start, end):
"""Remove tag from text range - only works with ScrolledText"""
if not self.use_qscintilla:
self.editor.tag_remove(tag, start, end)
def mark_set(self, mark, pos):
"""Set mark position - only works with ScrolledText"""
if not self.use_qscintilla:
self.editor.mark_set(mark, pos)
def see(self, pos):
"""Scroll to position"""
if self.use_qscintilla:
# Convert Tkinter position to QScintilla line/column and scroll
try:
line, col = map(int, pos.split('.'))
self.qsci_editor.setCursorPosition(line - 1, col)
self.qsci_editor.ensureLineVisible(line - 1)
except:
pass
else:
self.editor.see(pos)
def search(self, pattern, start, end, **kwargs):
"""Search for pattern - only works with ScrolledText"""
if not self.use_qscintilla:
return self.editor.search(pattern, start, end, **kwargs)
# For QScintilla, use built-in find functionality
return None
class OTARequestHandler(http.server.SimpleHTTPRequestHandler):
"""Custom HTTP request handler for serving firmware binaries"""
def __init__(self, bin_file_path, *args, **kwargs):
self.bin_file_path = bin_file_path
super().__init__(*args, **kwargs)
def do_GET(self):
"""Handle GET requests for firmware binary"""
if self.path == '/firmware.bin' or self.path == '/update':
try:
if not os.path.exists(self.bin_file_path):
self.send_error(404, "Firmware file not found")
return
# Get file size
file_size = os.path.getsize(self.bin_file_path)
# Send headers
self.send_response(200)
self.send_header('Content-Type', 'application/octet-stream')
self.send_header('Content-Disposition', f'attachment; filename="{os.path.basename(self.bin_file_path)}"')
self.send_header('Content-Length', str(file_size))
self.send_header('Cache-Control', 'no-cache')
self.end_headers()
# Send file in chunks
with open(self.bin_file_path, 'rb') as f:
while True:
chunk = f.read(8192)
if not chunk:
break
self.wfile.write(chunk)
except Exception as e:
self.send_error(500, f"Error serving file: {str(e)}")
else:
# Return simple HTML page for root
self.send_response(200)
self.send_header('Content-Type', 'text/html')
self.end_headers()
html = f"""
<!DOCTYPE html>
<html>
<head><title>MeshCore OTA Update Server</title></head>
<body>
<h1>MeshCore OTA Update Server</h1>
<p>Firmware available at: <a href="/firmware.bin">/firmware.bin</a></p>
<p>File: {os.path.basename(self.bin_file_path)}</p>
<p>Size: {os.path.getsize(self.bin_file_path) / 1024:.2f} KB</p>
</body>
</html>
"""
self.wfile.write(html.encode())
def log_message(self, format, *args):
"""Override to suppress default logging"""
pass
class MeshCoreBLEFlasher:
def __init__(self, root):
self.root = root
self.root.title("Meshcore Firmware Editor and Flasher")
# Set window to fullscreen/maximized (cross-platform)
import sys
if sys.platform == 'win32':
# Windows
self.root.state('zoomed')
elif sys.platform == 'darwin':
# macOS
self.root.state('zoomed')
else:
# Linux - use geometry to maximize
self.root.update_idletasks()
width = self.root.winfo_screenwidth()
height = self.root.winfo_screenheight()
self.root.geometry(f"{width}x{height}+0+0")
self.root.resizable(True, True)
# State variables
# Separate file paths and content for each firmware type
self.file_paths = {
"companion_radio": None,
"simple_repeater": None,
"room_server": None,
}
self.original_contents = {
"companion_radio": None,
"simple_repeater": None,
"room_server": None,
}
# Keep for backward compatibility and current access
self.file_path = None # Will point to current firmware type's file
self.original_content = None # Will point to current firmware type's content
self.is_downloaded = False
self.project_dir = None
self.is_compiling = False
self.platformio_available = False
self.all_devices = {} # Store all devices (unfiltered)
self.available_devices = {} # Filtered devices based on firmware type
self.platformio_ini_modified = False
self.platformio_ini_loaded_path = None # Track loaded platformio.ini file path
self.selected_version = "main" # Default to main branch
self.available_versions = [] # Will be populated with branches and tags
self.firmware_type = "companion_radio" # Default to companion_radio (maps to examples/companion_radio)
# Storage settings
self.storage_root = None # User-selectable root folder
self.config_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'meshcore_config.ini')
self.load_storage_settings()
# OTA settings
self.ota_server = None
self.ota_server_thread = None
self.ota_server_port = 8080
self.ota_bin_file = None
self.ota_device_ip = None
self.last_compiled_bin = None # Store path to last compiled binary
self.ota_meshcore = None # MeshCore connection for OTA/contact-loading
self.ota_contacts_dict = {} # Map dropdown display name to public_key
self.ota_contacts_cache = {}
self._ota_ble_spin_active = False # BLE scan spinner state
self._ota_contacts_spin_active = False # Contacts load spinner state
# Single persistent event loop for all BLE/OTA async operations so that
# the MeshCore object created during Load Contacts can be safely reused
# by the OTA workflow without "Future attached to a different loop" errors.
import asyncio as _asyncio
self.ota_event_loop = _asyncio.new_event_loop()
_ota_loop_thread = threading.Thread(
target=self.ota_event_loop.run_forever,
daemon=True, name="ota-event-loop"
)
_ota_loop_thread.start() # Cache contacts per BLE device: {ble_address: (contact_list, contact_dict)}
self.ota_scanned_devices = {} # Map display name to (name, address) for scanned BLE devices
self.previous_wifi_connection = None # Store previous WiFi connection before OTA
self.ota_wifi_connected = False # Track if connected to MeshCore-OTA
self.last_ble_device = None # Store last BLE device address
self.last_target_device = None # Store last target device ID
# Theme and UI settings
self.dark_mode = False # Dark mode toggle
self.recent_files = [] # Recent files list (max 10)
self.auto_save_enabled = True # Auto-save for editors
self.auto_save_timer = None # Timer for auto-save
self.compilation_start_time = None # Track compilation time
# OTA history
self.ota_history = [] # Store OTA update history
# Serial monitor state
self.serial_monitor_process = None
self.serial_monitor_running = False
self._sm_usb_autosuspend_path = None
self._sm_usb_autosuspend_old = None
self.serial_monitor_after_id = None
self._sm_shutting_down = False
# MeshCore CLI tab state
self.cli_serial = None
self.cli_running = False
self._cli_usb_autosuspend_path = None
self._cli_usb_autosuspend_old = None
self.cli_cmd_history = []
self.cli_history_idx = -1
self.cli_quick_btn_widgets = [] # keep refs so we can destroy/rebuild
self._cli_mode_active = False # True once we see a '>' prompt
self._cli_pending_get = None # "radio" or "name" when waiting to parse response
self._cli_pending_get_buf = [] # accumulate response lines for parsing
self._cli_no_response_id = None # after() id for no-response hint timer
self.setup_ui()
self.check_platformio()
# Automatically refresh device list on startup (same approach as meshcore_ble_name_editor)
self.root.after(100, self.refresh_devices)
# Ensure window is visible
self.root.after(500, lambda: self._ensure_window_visible())
def _ensure_window_visible(self):
"""Ensure the window is visible and on top"""
try:
self.root.deiconify()
self.root.lift()
self.root.focus_force()
self.root.update()
except:
pass
def create_scrollable_frame(self, parent):
"""Create a scrollable frame with canvas and scrollbar"""
# Create canvas and scrollbar
canvas = tk.Canvas(parent, highlightthickness=0)
scrollbar = ttk.Scrollbar(parent, orient="vertical", command=canvas.yview)
scrollable_frame = ttk.Frame(canvas)
# Create window in canvas for scrollable frame
canvas_frame = canvas.create_window((0, 0), window=scrollable_frame, anchor="nw")
# Configure canvas scrolling
canvas.configure(yscrollcommand=scrollbar.set)
# Enable mousewheel scrolling (works on Windows and Mac)
def on_mousewheel(event):
canvas.yview_scroll(int(-1 * (event.delta / 120)), "units")
return "break" # Prevent event propagation
# Enable mousewheel scrolling for Linux (Button-4 and Button-5)
def on_mousewheel_linux(event):
if event.num == 4:
canvas.yview_scroll(-1, "units")
elif event.num == 5:
canvas.yview_scroll(1, "units")
return "break" # Prevent event propagation
# Function to recursively bind mousewheel to widget and all its children
def bind_mousewheel_to_children(widget):
"""Recursively bind mousewheel events to widget and all its children"""
widget.bind("<MouseWheel>", on_mousewheel)
widget.bind("<Button-4>", on_mousewheel_linux)
widget.bind("<Button-5>", on_mousewheel_linux)
for child in widget.winfo_children():
bind_mousewheel_to_children(child)
# Update scroll region when frame size changes
def configure_scroll_region(event):
canvas.configure(scrollregion=canvas.bbox("all"))
# Keep canvas width equal to scrollable frame width
canvas_width = event.width
canvas.itemconfig(canvas_frame, width=canvas_width)
# Bind mousewheel to any new children that were added
bind_mousewheel_to_children(scrollable_frame)
scrollable_frame.bind("<Configure>", configure_scroll_region)
canvas.bind("<Configure>", lambda e: canvas.itemconfig(canvas_frame, width=e.width))
# Bind mousewheel events to canvas
canvas.bind("<MouseWheel>", on_mousewheel)
canvas.bind("<Button-4>", on_mousewheel_linux)
canvas.bind("<Button-5>", on_mousewheel_linux)
# Bind mousewheel events to scrollable frame so scrolling works anywhere in the frame
scrollable_frame.bind("<MouseWheel>", on_mousewheel)
scrollable_frame.bind("<Button-4>", on_mousewheel_linux)
scrollable_frame.bind("<Button-5>", on_mousewheel_linux)
# Also bind to canvas focus for better scrolling
canvas.bind("<Enter>", lambda e: canvas.focus_set())
# Initial bind to existing children
bind_mousewheel_to_children(scrollable_frame)
# Grid canvas and scrollbar
canvas.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
scrollbar.grid(row=0, column=1, sticky=(tk.N, tk.S))
# Configure grid weights
parent.columnconfigure(0, weight=1)
parent.rowconfigure(0, weight=1)
return scrollable_frame, canvas, scrollbar
def setup_ui(self):
"""Setup the user interface"""
# Main container
main_frame = ttk.Frame(self.root, padding="10")
main_frame.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
self.root.columnconfigure(0, weight=1)
self.root.rowconfigure(0, weight=1)
# Configure for 2 columns: content on left, logs on right
main_frame.columnconfigure(0, weight=3) # Content area (expands)
main_frame.columnconfigure(1, weight=1, minsize=220) # Log area (never < 220 px)
main_frame.rowconfigure(0, weight=1)
# Left side: Content area
content_frame = ttk.Frame(main_frame)
content_frame.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S), padx=(0, 10))
content_frame.columnconfigure(0, weight=1)
content_frame.rowconfigure(1, weight=1)
# Title
title_label = ttk.Label(content_frame, text="Meshcore Firmware Editor and Flasher",
font=('Arial', 16, 'bold'))
title_label.grid(row=0, column=0, pady=(0, 10))
# Right side: Log output (shared across tabs) - vertical layout
# Create this first so it's available for logging during tab setup
log_frame = ttk.LabelFrame(main_frame, text="Log Output", padding="10")
log_frame.grid(row=0, column=1, sticky=(tk.W, tk.E, tk.N, tk.S))
log_frame.columnconfigure(0, weight=1)
log_frame.rowconfigure(0, weight=1)
# Log text widget - sized for vertical sidebar (narrower width, full height)
self.log_text = scrolledtext.ScrolledText(log_frame, height=1, width=50,
font=('Courier', 9), wrap=tk.WORD)
self.log_text.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
# Create notebook for tabs
self.notebook = ttk.Notebook(content_frame)
self.notebook.grid(row=1, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
# Create tabs
self.welcome_tab = ttk.Frame(self.notebook, padding="10")
self.firmware_tab = ttk.Frame(self.notebook, padding="10")
self.settings_tab = ttk.Frame(self.notebook, padding="10")
self.cpp_editor_tab = ttk.Frame(self.notebook, padding="10")
self.ota_tab = ttk.Frame(self.notebook, padding="10")
self.serial_monitor_tab = ttk.Frame(self.notebook, padding="10")
self.cli_tab = ttk.Frame(self.notebook, padding="10")
self.notebook.add(self.welcome_tab, text="🏠 Welcome")
self.notebook.add(self.firmware_tab, text="📦 Firmware")
self.notebook.add(self.cpp_editor_tab, text="main.cpp")
self.notebook.add(self.settings_tab, text="platformio.ini")
self.notebook.add(self.ota_tab, text="📡 OTA Update")
self.notebook.add(self.serial_monitor_tab, text="🖥️ Serial Monitor")
self.notebook.add(self.cli_tab, text="⌨️ MeshCore CLI")
# Setup welcome tab
self.setup_welcome_tab()
# Setup firmware tab
self.setup_firmware_tab()
# Setup C++ editor tab
self.setup_cpp_editor_tab()
# Setup settings tab
self.setup_settings_tab()
# Setup OTA tab
self.setup_ota_tab()
# Setup Serial Monitor tab
self.setup_serial_monitor_tab()
# Setup MeshCore CLI tab
self.setup_cli_tab()
# Auto-start serial monitor once the main loop is running
self.root.after(500, self.start_serial_monitor)
# Load OTA checkbox settings (after OTA tab is set up)
self.load_ota_checkbox_settings()
# Setup keyboard shortcuts
self.setup_keyboard_shortcuts()
# Setup auto-save timer
if self.auto_save_enabled:
self.setup_auto_save()
# Handle window close
self.root.protocol("WM_DELETE_WINDOW", self.on_closing)
def setup_welcome_tab(self):
"""Setup the Welcome tab with app information and purpose"""
# Create scrollable frame
scrollable_frame, canvas, scrollbar = self.create_scrollable_frame(self.welcome_tab)
welcome_frame = scrollable_frame
welcome_frame.columnconfigure(0, weight=1)
# Title
title_label = ttk.Label(welcome_frame, text="Meshcore Firmware Editor and Flasher",
font=('Arial', 18, 'bold'))
title_label.grid(row=0, column=0, sticky=tk.W, pady=(0, 5))
subtitle_label = ttk.Label(welcome_frame,
text="An all-in-one GUI tool for editing, compiling, flashing and managing MeshCore firmware.",
font=('Arial', 10), foreground='gray')
subtitle_label.grid(row=1, column=0, sticky=tk.W, pady=(0, 20))
# Purpose section
purpose_frame = ttk.LabelFrame(welcome_frame, text="Purpose", padding="15")
purpose_frame.grid(row=2, column=0, sticky=(tk.W, tk.E), pady=(0, 15))
purpose_frame.columnconfigure(0, weight=1)
purpose_label = ttk.Label(purpose_frame, font=('Arial', 10),
foreground='black', justify=tk.LEFT, wraplength=800,
text=(
"This application gives MeshCore enthusiasts a single, intuitive place to manage firmware — "
"from downloading source code and editing key settings, to compiling, flashing, OTA updates, "
"and direct serial CLI access.\n\n"
"All UI changes are reflected directly in the underlying source files so you always know "
"exactly what the firmware will contain."
))
purpose_label.grid(row=0, column=0, sticky=tk.W)
# Key Features section
features_frame = ttk.LabelFrame(welcome_frame, text="Key Features", padding="15")
features_frame.grid(row=3, column=0, sticky=(tk.W, tk.E), pady=(0, 15))
features_frame.columnconfigure(0, weight=1)
features_label = ttk.Label(features_frame, font=('Arial', 9),
foreground='black', justify=tk.LEFT, wraplength=800,
text=(
"📦 FIRMWARE MANAGEMENT\n"
" • Download firmware from GitHub — Companion Radio, Repeater Radio, or Room Server\n"
" • Browse and load local firmware files\n"
" • Automatic version detection and type filtering\n\n"
"🔧 BLE NAME CUSTOMISATION\n"
" • Optional custom BLE name overrides the default MeshCore-<node_name> convention\n"
" • Applied immediately to main.cpp and visible in the C++ editor\n"
" • Leave blank and click Apply to revert to the standard naming code\n"
" • ⚠ Custom names may interfere with auto-connect in some MeshCore phone apps\n\n"
"✏️ CODE EDITING\n"
" • Full-featured C++ editor for main.cpp (syntax highlighting if QScintilla installed)\n"
" • PlatformIO.ini editor — edit build settings, environments, and targets\n"
" • Find/replace (Ctrl+F), auto-backup on save, reload, reset to original\n\n"
"🔨 BUILD & FLASH\n"
" • Compile firmware using PlatformIO for your selected device\n"
" • Flash via USB — select a specific serial port or use Auto-detect\n"
" • Flash pre-built .bin files directly — no compilation needed\n"
" • Flash modes: Update Only (keeps settings) or Full Erase (wipes entire flash)\n"
" • 🔄 Refresh Ports to rescan available serial ports at any time\n\n"
"📡 OTA UPDATE\n"
" • Wireless firmware updates via the MeshCore OTA workflow\n"
" • BLE scan → load contacts → send 'start ota' → auto-connect to MeshCore-OTA WiFi\n"
" • Upload .bin via ElegantOTA in your browser; confirmation dialog waits for you\n"
" • Reconnects to your previous WiFi on completion\n\n"
"🖥️ SERIAL MONITOR\n"
" • Always-on live device output — starts automatically, auto-reconnects if unplugged\n"
" • Uses pyserial directly — no PlatformIO subprocess required\n"
" • Port sharing — pauses automatically when CLI tab takes the connection\n\n"
"⌨️ MESHCORE CLI\n"
" • Direct serial CLI — send any MeshCore command over USB serial\n"
" • Context-sensitive quick buttons for Repeater, Companion, and Room Server\n"
" • Collapsible command groups (Info, Logging, Radio, Power, Region, GPS, Manage)\n"
" • Hover tooltips on every button with full command description\n"
" • CLI mode detection — confirms when '>' prompt is active\n"
" • No-response watchdog — guides you if commands aren't getting replies\n"
" • Command history navigation with ↑/↓ arrow keys\n\n"
"🎨 USER INTERFACE\n"
" • BLE and WiFi status dots turn green when connected\n"
" • Fullscreen layout with vertical log panel (minimum width enforced)\n"
" • Device memory — remembers last BLE device, target, and serial port\n"
" • Tabs: Welcome · Firmware · main.cpp · platformio.ini · OTA Update · Serial Monitor · MeshCore CLI"
))
features_label.grid(row=0, column=0, sticky=tk.W)
# Workflow section
workflow_frame = ttk.LabelFrame(welcome_frame, text="Typical Workflows", padding="15")
workflow_frame.grid(row=4, column=0, sticky=(tk.W, tk.E), pady=(0, 15))
workflow_frame.columnconfigure(0, weight=1)
workflow_label = ttk.Label(workflow_frame, font=('Arial', 9),
foreground='black', justify=tk.LEFT, wraplength=800,
text=(
"Compile & Flash from source:\n"
" 1. 📦 Firmware tab — select type, download or browse, set optional BLE name\n"
" 2. ✏️ main.cpp tab — review or edit source code\n"
" 3. ⚙️ platformio.ini — adjust build settings if needed\n"
" 4. 🔨 Compile — build firmware (BLE name applied automatically)\n"
" 5. ⚡ Flash — select serial port, choose flash mode, and upload\n\n"
"Flash a pre-built .bin:\n"
" 1. 📦 Firmware tab — click Browse .bin, select your file\n"
" 2. ⚡ Flash .bin — select serial port and flash immediately\n\n"
"OTA Update:\n"
" 1. 📡 OTA Update tab — scan for and select your local BLE gateway device\n"
" 2. Load Contacts — fetch the device contact list, select the remote target\n"
" 3. Start OTA Update — app handles BLE, WiFi, and opens upload page in browser\n"
" 4. Upload .bin — upload in the browser, then confirm in the dialog\n\n"
"Serial CLI:\n"
" 1. ⌨️ MeshCore CLI tab — select port/baud, click Connect\n"
" 2. Enter CLI mode — usually hold BOOT on device, power on\n"
" 3. Wait for '>' — a '>' prompt confirms CLI mode is active\n"
" 4. Select device type — quick buttons update for Repeater / Companion / Room\n"
" 5. Expand a group — click any ▸ header, then click a command button\n"
" 6. Disconnect — Serial Monitor resumes automatically"
))
workflow_label.grid(row=0, column=0, sticky=tk.W)
# Requirements section
requirements_frame = ttk.LabelFrame(welcome_frame, text="Requirements", padding="15")
requirements_frame.grid(row=5, column=0, sticky=(tk.W, tk.E), pady=(0, 15))
requirements_frame.columnconfigure(0, weight=1)
requirements_label = ttk.Label(requirements_frame, font=('Arial', 9),
foreground='black', justify=tk.LEFT, wraplength=800,
text=(
"• Python 3.8 or higher\n"
"• pyserial — pip install pyserial (required for Serial Monitor and CLI)\n"
"• PlatformIO — pip install platformio (required for compile/flash)\n"
"• Git (required to download firmware from GitHub)\n"
"• meshcore — pip install meshcore (required for OTA)\n"
"• bleak — pip install bleak (required for BLE in OTA)\n"
"• Optional: tkinterweb — pip install tkinterweb (embedded browser in OTA tab)\n"
"• Optional: QScintilla / PyQt5 — pip install QScintilla PyQt5 (syntax highlighting)\n"
"• Linux OTA: NetworkManager (nmcli) for automatic WiFi management"
))
requirements_label.grid(row=0, column=0, sticky=tk.W)
# Repository section
repo_frame = ttk.LabelFrame(welcome_frame, text="Repository & License", padding="15")
repo_frame.grid(row=6, column=0, sticky=(tk.W, tk.E), pady=(0, 15))
repo_frame.columnconfigure(0, weight=1)
repo_label = ttk.Label(repo_frame, font=('Arial', 9),
foreground='black', justify=tk.LEFT, wraplength=800,
text=(
"Repository: https://github.com/basiccode12/Meshcore-Firmware-Editor-and-Flasher\n"
"License: MIT License\n\n"
"Contributions, bug reports, and feature requests are welcome via GitHub Issues."
))
repo_label.grid(row=0, column=0, sticky=tk.W)
# Getting Started section
getting_started_frame = ttk.LabelFrame(welcome_frame, text="Getting Started", padding="15")
getting_started_frame.grid(row=7, column=0, sticky=(tk.W, tk.E), pady=(0, 15))
getting_started_frame.columnconfigure(0, weight=1)
getting_started_label = ttk.Label(getting_started_frame, font=('Arial', 9),
foreground='black', justify=tk.LEFT, wraplength=800,
text=(
"Head to the 📦 Firmware tab to download or load a firmware project — that's all you need "
"to get started. All operations are logged in the panel on the right.\n\n"
"For live device output, the 🖥️ Serial Monitor starts automatically.\n\n"
"For interactive configuration, use the ⌨️ MeshCore CLI tab — connect, "
"enter CLI mode on the device, and start sending commands. Hover any quick-button for a full description."
))
getting_started_label.grid(row=0, column=0, sticky=tk.W)
def setup_firmware_tab(self):
"""Setup the firmware tab"""
# Create scrollable frame
scrollable_frame, canvas, scrollbar = self.create_scrollable_frame(self.firmware_tab)
firmware_frame = scrollable_frame
firmware_frame.columnconfigure(0, weight=1)
firmware_frame.columnconfigure(1, weight=1)
firmware_frame.rowconfigure(4, weight=1)
# Storage Settings Section (at the top)
storage_frame = ttk.LabelFrame(firmware_frame, text="📁 Storage Settings", padding="10")
storage_frame.grid(row=0, column=0, columnspan=2, sticky=(tk.W, tk.E), pady=(0, 10))
storage_frame.columnconfigure(1, weight=1)
ttk.Label(storage_frame, text="Root Folder:").grid(row=0, column=0, padx=(0, 10), sticky=tk.W)
self.storage_root_var = tk.StringVar()
if self.storage_root:
self.storage_root_var.set(self.storage_root)
else:
self.storage_root_var.set("Not set - files will be saved in current directory")
storage_path_label = ttk.Label(storage_frame, textvariable=self.storage_root_var,
font=('Courier', 9), foreground='blue', wraplength=600)
storage_path_label.grid(row=0, column=1, sticky=(tk.W, tk.E), padx=(0, 10))
ttk.Button(storage_frame, text="📂 Browse",
command=self.select_storage_root, width=15).grid(row=0, column=2, padx=(0, 5))
ttk.Button(storage_frame, text="🗑️ Clear",
command=self.clear_storage_root, width=12).grid(row=0, column=3)
info_label = ttk.Label(storage_frame,
text="Files will be organized in date-labeled folders: YYYY-MM-DD/bin/, YYYY-MM-DD/cpp/, YYYY-MM-DD/platformio/",
font=('Arial', 8), foreground='gray', wraplength=700)
info_label.grid(row=1, column=0, columnspan=4, sticky=tk.W, pady=(5, 0))
# Step 1: Get Firmware
step1_frame = ttk.LabelFrame(firmware_frame, text="1. Get Firmware", padding="10")
step1_frame.grid(row=1, column=0, columnspan=2, sticky=(tk.W, tk.E), pady=(0, 10))
step1_frame.columnconfigure(1, weight=1)
# Version selection
version_frame = ttk.Frame(step1_frame)
version_frame.grid(row=0, column=0, columnspan=2, sticky=(tk.W, tk.E), pady=(0, 10))
version_frame.columnconfigure(1, weight=1)
ttk.Label(version_frame, text="Firmware Type:").grid(row=0, column=0, padx=(0, 5), sticky=tk.W)
self.firmware_type_var = tk.StringVar()
self.firmware_type_var.set("Companion Radio")
firmware_type_combo = ttk.Combobox(version_frame, textvariable=self.firmware_type_var,
values=["Companion Radio", "Repeater Radio", "Room Server"],
state='readonly', width=18)
firmware_type_combo.grid(row=0, column=1, sticky=tk.W, padx=(0, 10))
firmware_type_combo.bind('<<ComboboxSelected>>', self._on_firmware_type_selected)
ttk.Label(version_frame, text="Version:").grid(row=0, column=2, padx=(10, 5), sticky=tk.W)
self.version_var = tk.StringVar()
self.version_var.set("main")
self.version_combo = ttk.Combobox(version_frame, textvariable=self.version_var,
values=["main"], state='readonly', width=25)
self.version_combo.grid(row=0, column=3, sticky=(tk.W, tk.E), padx=(0, 10))
self.version_combo.bind('<<ComboboxSelected>>', self._on_version_selected)
ttk.Button(version_frame, text="🔄 Refresh Versions",
command=self.refresh_versions, width=18).grid(row=0, column=4)
# Download and browse buttons
button_frame = ttk.Frame(step1_frame)
button_frame.grid(row=1, column=0, columnspan=2, sticky=(tk.W, tk.E))
ttk.Button(button_frame, text="📥 Download Selected",
command=self.download_firmware, width=18).grid(row=0, column=0, padx=(0, 5))
ttk.Button(button_frame, text="📂 Browse Local File",
command=self.browse_file, width=18).grid(row=0, column=1, padx=(0, 5))
self.file_path_var = tk.StringVar()
self.file_path_var.set("No file loaded")
ttk.Label(step1_frame, textvariable=self.file_path_var,
foreground='blue', font=('Arial', 9)).grid(row=2, column=0, columnspan=2, sticky=tk.W, pady=(5, 0))
# Load versions on startup (after firmware type is set)
self.root.after(500, self.refresh_versions)
# Step 2: BLE Name (Left Column)
step2_frame = ttk.LabelFrame(firmware_frame, text="2. Set BLE Name (Optional)", padding="10")
step2_frame.grid(row=2, column=0, sticky=(tk.W, tk.E, tk.N), padx=(0, 5), pady=(0, 10))
step2_frame.columnconfigure(1, weight=1)
ttk.Label(step2_frame, text="BLE Name:").grid(row=0, column=0, padx=(0, 10), sticky=tk.W)
self.ble_name_var = tk.StringVar()
name_entry = ttk.Entry(step2_frame, textvariable=self.ble_name_var, font=('Arial', 10))
name_entry.grid(row=0, column=1, sticky=(tk.W, tk.E))
name_entry.bind('<Return>', lambda e: self.apply_ble_name_changes())
ttk.Button(step2_frame, text="✏ Apply to main.cpp",
command=self.apply_ble_name_changes, width=20).grid(
row=0, column=2, padx=(8, 0), sticky=tk.W)
ttk.Label(step2_frame, text="Leave blank to use MeshCore's default naming: MeshCore-<node_name>",
font=('Arial', 8), foreground='gray').grid(row=1, column=0, columnspan=3, sticky=tk.W, pady=(5, 1))
ttk.Label(step2_frame, text="If set, overwrites the default — written into main.cpp and reflected in the C++ editor. Also applied automatically on compile.",
font=('Arial', 8), foreground='gray').grid(row=2, column=0, columnspan=3, sticky=tk.W, pady=(0, 2))
ttk.Label(step2_frame, text="⚠ Custom names may break auto-connect in MeshCore phone apps (apps scan for 'MeshCore-*').",
font=('Arial', 8), foreground='#b35900').grid(row=3, column=0, columnspan=3, sticky=tk.W, pady=(0, 0))
# Step 3: Device Selection (Right Column)
step3_frame = ttk.LabelFrame(firmware_frame, text="3. Select Device", padding="10")
step3_frame.grid(row=2, column=1, sticky=(tk.W, tk.E, tk.N), padx=(5, 0), pady=(0, 10))
step3_frame.columnconfigure(1, weight=1)
ttk.Label(step3_frame, text="Device:").grid(row=0, column=0, padx=(0, 10), sticky=tk.W)
self.device_var = tk.StringVar()
self.device_combo = ttk.Combobox(step3_frame, textvariable=self.device_var,
values=[], state='readonly', width=30)
self.device_combo.grid(row=0, column=1, sticky=(tk.W, tk.E))
# Step 4: Edit C++ (Optional) (Left Column)
step4_frame = ttk.LabelFrame(firmware_frame, text="4. Edit main.cpp (Optional)", padding="10")
step4_frame.grid(row=3, column=0, sticky=(tk.W, tk.E), padx=(0, 5), pady=(0, 10))
step4_frame.columnconfigure(0, weight=1)
ttk.Button(step4_frame, text="main.cpp",
command=self.go_to_cpp_editor_tab, width=30).grid(row=0, column=0)
ttk.Label(step4_frame, text="Edit source code before compiling",
font=('Arial', 8), foreground='gray').grid(row=1, column=0, pady=(5, 0))
# Step 5: Configure PlatformIO (Optional) (Right Column)
step5_frame = ttk.LabelFrame(firmware_frame, text="5. Configure PlatformIO (Optional)", padding="10")
step5_frame.grid(row=3, column=1, sticky=(tk.W, tk.E), padx=(5, 0), pady=(0, 10))
step5_frame.columnconfigure(0, weight=1)
ttk.Button(step5_frame, text="platformio.ini",
command=self.go_to_settings_tab, width=30).grid(row=0, column=0)
ttk.Label(step5_frame, text="Edit platformio.ini configuration",
font=('Arial', 8), foreground='gray').grid(row=1, column=0, pady=(5, 0))
# Step 6: Build & Flash (Full Width)
step6_frame = ttk.LabelFrame(firmware_frame, text="6. Build & Flash", padding="10")
step6_frame.grid(row=4, column=0, columnspan=2, sticky=(tk.W, tk.E), pady=(0, 10))
step6_frame.columnconfigure(0, weight=1)
# Serial port selector row
port_frame = ttk.Frame(step6_frame)
port_frame.grid(row=0, column=0, sticky=tk.W, pady=(0, 8))
ttk.Label(port_frame, text="Serial Port:").grid(row=0, column=0, padx=(0, 8), sticky=tk.W)
self.serial_port_var = tk.StringVar(value="Auto")
self.serial_port_combo = ttk.Combobox(port_frame, textvariable=self.serial_port_var,
values=["Auto"], state='readonly', width=22)
self.serial_port_combo.grid(row=0, column=1, padx=(0, 5))
ttk.Button(port_frame, text="🔄 Refresh Ports", command=self.refresh_serial_ports_combo,
width=16).grid(row=0, column=2)
ttk.Label(port_frame, text="(Auto = PlatformIO detects)",
font=('Arial', 8), foreground='gray').grid(row=0, column=3, padx=(8, 0))
# Flash mode selection
flash_mode_frame = ttk.Frame(step6_frame)
flash_mode_frame.grid(row=1, column=0, sticky=tk.W, pady=(0, 10))
ttk.Label(flash_mode_frame, text="Flash Mode:").grid(row=0, column=0, padx=(0, 10), sticky=tk.W)
self.flash_mode_var = tk.StringVar()
self.flash_mode_var.set("update") # Default to update only
ttk.Radiobutton(flash_mode_frame, text="Update Only", variable=self.flash_mode_var,
value="update", width=15).grid(row=0, column=1, padx=5)
ttk.Radiobutton(flash_mode_frame, text="Full Erase", variable=self.flash_mode_var,
value="erase", width=15).grid(row=0, column=2, padx=5)
ttk.Label(flash_mode_frame, text="(Update: faster, keeps settings)",
font=('Arial', 8), foreground='gray').grid(row=1, column=1, columnspan=2, sticky=tk.W, pady=(2, 0))
button_frame = ttk.Frame(step6_frame)
button_frame.grid(row=2, column=0)
self.compile_btn = ttk.Button(button_frame, text="🔨 Compile",
command=self.compile_firmware, width=15)
self.compile_btn.grid(row=0, column=0, padx=5)
self.flash_btn = ttk.Button(button_frame, text="⚡ Flash",
command=self.flash_firmware, width=15)
self.flash_btn.grid(row=0, column=1, padx=5)
self.ota_quick_btn = ttk.Button(button_frame, text="📡 OTA Update",
command=self.go_to_ota_tab, width=15)
self.ota_quick_btn.grid(row=0, column=2, padx=5)
# Pre-built binary flash section
prebuilt_frame = ttk.LabelFrame(step6_frame, text="Flash Pre-built .bin (no compile needed)", padding="8")
prebuilt_frame.grid(row=4, column=0, sticky=(tk.W, tk.E), pady=(12, 0))
prebuilt_frame.columnconfigure(1, weight=1)
ttk.Label(prebuilt_frame, text="Binary:").grid(row=0, column=0, padx=(0, 8), sticky=tk.W)
self.prebuilt_bin_var = tk.StringVar(value="No file selected")
ttk.Label(prebuilt_frame, textvariable=self.prebuilt_bin_var,
foreground='blue', font=('Arial', 9),
wraplength=400).grid(row=0, column=1, sticky=(tk.W, tk.E))
ttk.Button(prebuilt_frame, text="📂 Browse .bin",
command=self.browse_prebuilt_bin, width=14).grid(row=0, column=2, padx=(8, 4))
self.flash_prebuilt_btn = ttk.Button(prebuilt_frame, text="⚡ Flash .bin",
command=self.flash_prebuilt_bin, width=13)