-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdrone_gui.py
More file actions
5027 lines (4260 loc) · 209 KB
/
drone_gui.py
File metadata and controls
5027 lines (4260 loc) · 209 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
"""
Tello Drone Control System - GUI Version
A comprehensive graphical interface for controlling DJI Tello drones
"""
import tkinter as tk
from tkinter import ttk, messagebox, scrolledtext
import threading
import time
try:
import cv2
CV2_AVAILABLE = True
except ImportError:
cv2 = None
CV2_AVAILABLE = False
from PIL import Image, ImageTk
import numpy as np
from tello_drone_agent import TelloDroneAgent
import queue
import sys
# Voice command support
try:
import speech_recognition as sr
VOICE_AVAILABLE = True
except ImportError:
sr = None
VOICE_AVAILABLE = False
# Text-to-speech support
try:
import pyttsx3
TTS_AVAILABLE = True
except ImportError:
pyttsx3 = None
TTS_AVAILABLE = False
# Audio playback support
try:
import simpleaudio as sa
SIMPLEAUDIO_AVAILABLE = True
except ImportError:
sa = None
SIMPLEAUDIO_AVAILABLE = False
# Real-time audio support (from advanced agent)
try:
import pyaudio
import websockets
import asyncio
REALTIME_AUDIO_AVAILABLE = True
except ImportError:
pyaudio = None
websockets = None
asyncio = None
REALTIME_AUDIO_AVAILABLE = False
# Removed gTTS support - using simple TTS only
# Azure OpenAI support
try:
from openai import AzureOpenAI
AZURE_OPENAI_AVAILABLE = True
except ImportError:
AzureOpenAI = None
AZURE_OPENAI_AVAILABLE = False
print("⚠️ Azure OpenAI unavailable: openai package not installed")
# JSON is part of standard library
import json
import base64
import io
import os
import logging.handlers
from datetime import datetime, timedelta
from enum import Enum
from pathlib import Path
from typing import Dict, Any, Optional
# ===== ENHANCED LOGGING SYSTEM =====
class LogLevel(Enum):
"""Log level categories for structured logging."""
EVENT = "EVENT" # Normal system events (connection, takeoff, etc.)
WARNING = "WARNING" # Non-critical issues that should be noted
FAILURE = "FAILURE" # Critical failures and errors
DEBUG = "DEBUG" # Debug information for troubleshooting
SYSTEM = "SYSTEM" # System state changes and configuration
class DailyLogger:
"""Enhanced logging system with daily log files for system improvement feedback."""
def __init__(self, log_directory="logs", max_days=30):
"""
Initialize the daily logging system.
Args:
log_directory: Directory to store log files
max_days: Number of days to retain log files
"""
self.log_directory = Path(log_directory)
self.log_directory.mkdir(exist_ok=True)
self.max_days = max_days
self.current_date = None
self.current_file_handler = None
self.logger = self._setup_logger()
self._cleanup_old_logs()
def _setup_logger(self):
"""Setup the main logger with daily rotation."""
logger = logging.getLogger('drone_system')
logger.setLevel(logging.DEBUG)
# Remove any existing handlers
for handler in logger.handlers[:]:
logger.removeHandler(handler)
# Console handler for immediate feedback (optional)
console_handler = logging.StreamHandler()
console_formatter = logging.Formatter(
'%(asctime)s [%(levelname)s] %(message)s',
datefmt='%H:%M:%S'
)
console_handler.setFormatter(console_formatter)
console_handler.setLevel(logging.WARNING) # Only warnings and above to console
logger.addHandler(console_handler)
return logger
def _get_daily_log_filename(self, date=None):
"""Generate filename for daily log."""
if date is None:
date = datetime.now()
return self.log_directory / f"drone_system_{date.strftime('%Y-%m-%d')}.log"
def _ensure_daily_handler(self):
"""Ensure we have a file handler for today's date."""
today = datetime.now().date()
if self.current_date != today:
# Remove old file handler
if self.current_file_handler:
self.logger.removeHandler(self.current_file_handler)
self.current_file_handler.close()
# Create new file handler for today
log_filename = self._get_daily_log_filename()
self.current_file_handler = logging.FileHandler(log_filename, encoding='utf-8')
# Detailed formatter for file logs
file_formatter = logging.Formatter(
'%(asctime)s | %(levelname)-7s | %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
self.current_file_handler.setFormatter(file_formatter)
self.logger.addHandler(self.current_file_handler)
self.current_date = today
# Log the daily file creation
if not log_filename.exists() or log_filename.stat().st_size == 0:
self._log_structured(LogLevel.SYSTEM, "LOGGER", "Daily log file created", {
"filename": str(log_filename),
"date": today.isoformat()
})
def _cleanup_old_logs(self):
"""Remove log files older than max_days."""
if not self.log_directory.exists():
return
cutoff_date = datetime.now() - timedelta(days=self.max_days)
removed_count = 0
for log_file in self.log_directory.glob("drone_system_*.log"):
try:
# Extract date from filename
date_str = log_file.stem.replace("drone_system_", "")
file_date = datetime.strptime(date_str, "%Y-%m-%d")
if file_date < cutoff_date:
log_file.unlink()
removed_count += 1
except (ValueError, OSError):
continue # Skip invalid filenames or files we can't delete
if removed_count > 0:
self._log_structured(LogLevel.SYSTEM, "LOGGER", f"Cleaned up {removed_count} old log files")
def _log_structured(self, level: LogLevel, component: str, message: str, data: Optional[Dict[str, Any]] = None):
"""Internal method to log structured messages."""
self._ensure_daily_handler()
# Create structured log entry
log_entry = {
"timestamp": datetime.now().isoformat(),
"level": level.value,
"component": component,
"message": message
}
if data:
log_entry["data"] = data
# Format for file output
data_str = ""
if data:
data_str = f" | DATA: {json.dumps(data, separators=(',', ':'))}"
formatted_message = f"{component} | {message}{data_str}"
# Log to appropriate level
if level == LogLevel.FAILURE:
self.logger.error(formatted_message)
elif level == LogLevel.WARNING:
self.logger.warning(formatted_message)
elif level == LogLevel.DEBUG:
self.logger.debug(formatted_message)
else: # EVENT, SYSTEM
self.logger.info(formatted_message)
def log_event(self, component: str, message: str, mode: str = None, data: Optional[Dict[str, Any]] = None):
"""Log a normal system event."""
log_data = {"mode": mode} if mode else {}
if data:
log_data.update(data)
self._log_structured(LogLevel.EVENT, component, message, log_data)
def log_warning(self, component: str, message: str, mode: str = None, data: Optional[Dict[str, Any]] = None):
"""Log a warning."""
log_data = {"mode": mode} if mode else {}
if data:
log_data.update(data)
self._log_structured(LogLevel.WARNING, component, message, log_data)
def log_failure(self, component: str, message: str, mode: str = None, error: str = None, data: Optional[Dict[str, Any]] = None):
"""Log a failure or error."""
log_data = {"mode": mode} if mode else {}
if error:
log_data["error"] = error
if data:
log_data.update(data)
self._log_structured(LogLevel.FAILURE, component, message, log_data)
def log_debug(self, component: str, message: str, mode: str = None, data: Optional[Dict[str, Any]] = None):
"""Log debug information."""
log_data = {"mode": mode} if mode else {}
if data:
log_data.update(data)
self._log_structured(LogLevel.DEBUG, component, message, log_data)
def log_system(self, component: str, message: str, data: Optional[Dict[str, Any]] = None):
"""Log system state changes."""
self._log_structured(LogLevel.SYSTEM, component, message, data)
def get_log_files(self):
"""Get list of available log files."""
if not self.log_directory.exists():
return []
return sorted(self.log_directory.glob("drone_system_*.log"))
def get_log_stats(self):
"""Get statistics about the logging system."""
log_files = self.get_log_files()
total_size = sum(f.stat().st_size for f in log_files if f.exists())
return {
"total_files": len(log_files),
"total_size_mb": round(total_size / 1024 / 1024, 2),
"oldest_log": log_files[0].stem.replace("drone_system_", "") if log_files else None,
"newest_log": log_files[-1].stem.replace("drone_system_", "") if log_files else None,
"retention_days": self.max_days
}
# ===== DESIGN SYSTEM & THEME =====
class DroneTheme:
"""Centralized design system with theme tokens for consistent UI styling"""
# Color Palette - Modern Dark Theme
COLORS = {
# Background layers (darkest to lightest)
'bg_root': '#0f1419', # Main window background
'bg_panel': '#151b23', # Content panel background
'bg_surface': '#1a1f26', # Component surface background
'bg_elevated': '#1f2937', # Elevated component background
'bg_input': '#2d3748', # Input field background
# Text colors
'text_primary': '#ffffff', # Primary text
'text_secondary': '#e2e8f0', # Secondary text
'text_muted': '#9ca3af', # Muted/hint text
'text_disabled': '#6b7280', # Disabled text
# Semantic colors - Actions & States
'primary': '#3b82f6', # Primary actions
'success': '#10b981', # Success states & positive actions
'warning': '#f59e0b', # Warning states
'danger': '#ef4444', # Error states & destructive actions
'info': '#00e5ff', # Information & highlights
# Accent colors - Feature specific
'accent_purple': '#a855f7', # Vision/AI features
'accent_cyan': '#00cec9', # Panorama/camera features
'accent_orange': '#ff8a50', # Connection/status indicators
'accent_green': '#00e676', # Positive feedback
# UI Chrome
'border': '#374151', # Subtle borders
'separator': '#4b5563', # Dividers and separators
'shadow': 'rgba(0,0,0,0.25)', # Drop shadows
}
# Typography Scale
FONTS = {
'family': 'Segoe UI',
'family_mono': 'Consolas',
# Size scale
'size_xs': 8, # Chips, badges
'size_sm': 9, # Captions, hints
'size_base': 10, # Body text, buttons
'size_md': 11, # Input fields
'size_lg': 12, # Section headers
'size_xl': 16, # Page titles
'size_xxl': 20, # Main title
# Weights
'weight_normal': 'normal',
'weight_bold': 'bold',
}
# Spacing Scale (multiples of 4px base unit)
SPACING = {
'xs': 4, # 4px - tight spacing
'sm': 8, # 8px - small gaps
'md': 12, # 12px - medium gaps
'lg': 15, # 15px - large gaps
'xl': 20, # 20px - extra large gaps
'xxl': 24, # 24px - section spacing
}
# Component Styles
STYLES = {
'button': {
'relief': 'flat',
'bd': 0,
'cursor': 'hand2',
'padx': 15,
'pady': 8,
},
'button_large': {
'relief': 'flat',
'bd': 0,
'cursor': 'hand2',
'padx': 20,
'pady': 12,
},
'frame': {
'relief': 'flat',
'bd': 1,
},
'entry': {
'relief': 'flat',
'bd': 1,
}
}
@classmethod
def get_font(cls, size='base', weight='normal', family=None):
"""Get font tuple for tkinter widgets"""
font_family = family or cls.FONTS['family']
font_size = cls.FONTS[f'size_{size}']
font_weight = cls.FONTS[f'weight_{weight}']
return (font_family, font_size, font_weight)
@classmethod
def get_mono_font(cls, size='base', weight='normal'):
"""Get monospace font tuple"""
return cls.get_font(size, weight, cls.FONTS['family_mono'])
@classmethod
def apply_button_style(cls, button, bg_color, style='button'):
"""Apply consistent button styling"""
style_props = cls.STYLES[style].copy()
button.configure(
bg=cls.COLORS[bg_color] if bg_color in cls.COLORS else bg_color,
fg=cls.COLORS['text_primary'],
font=cls.get_font('base', 'bold'),
**style_props
)
@classmethod
def create_styled_frame(cls, parent, bg='bg_surface', **kwargs):
"""Create frame with theme styling"""
frame_props = cls.STYLES['frame'].copy()
frame_props.update(kwargs)
return tk.Frame(
parent,
bg=cls.COLORS[bg] if bg in cls.COLORS else bg,
**frame_props
)
class DroneControlGUI:
def __init__(self, simulation_mode=True):
"""
Initialize the GUI application.
Args:
simulation_mode: Whether to use simulation mode (default: True)
"""
print("🔧 Starting DroneControlGUI initialization...")
try:
self.root = tk.Tk()
self.root.title("🚁 Tello Drone Control System")
self.root.geometry("1200x800")
self.root.configure(bg=DroneTheme.COLORS['bg_root'])
print("✅ GUI window created successfully")
except Exception as e:
print(f"❌ GUI creation failed: {e}")
raise
# Initialize drone agent
print("🔧 Initializing drone agent...")
try:
self.agent = TelloDroneAgent(
simulation_mode=simulation_mode
)
self.simulation_mode = simulation_mode
# Set up vision analysis callback for agent commands
self.agent.vision_analysis_callback = self.thread_safe_vision_analysis
# Mark simulation mode for auto-connection after full initialization
self.pending_auto_connect = simulation_mode
print("✅ Drone agent initialized")
except Exception as e:
print(f"❌ Drone agent failed: {e}")
raise
# GUI state variables
self.is_connected = tk.BooleanVar()
self.is_flying = tk.BooleanVar()
self.battery_level = tk.StringVar(value="--")
self.connection_status = tk.StringVar(value="Disconnected")
self.detection_mode = tk.StringVar(value="Off")
self.follow_mode = tk.StringVar(value="Off")
# Video stream variables
self.video_frame = None
self.video_running = False
self.video_thread = None
# Message queue for thread-safe GUI updates
self.message_queue = queue.Queue()
# Enhanced daily logging system
self.daily_logger = DailyLogger()
mode_text = "SIMULATION" if simulation_mode else "REALTIME"
self.daily_logger.log_system("GUI", f"Drone Control System started in {mode_text} mode", {
"version": "2.0",
"simulation_mode": simulation_mode,
"timestamp": datetime.now().isoformat()
})
# Voice command variables
self.voice_enabled = False
self.voice_running = False
self.voice_thread = None
# Vision analysis variables
self.continuous_vision_enabled = False
self.continuous_vision_running = False
self.continuous_vision_thread = None
self.vision_analysis_interval = 2.0 # Analyze every 2 seconds
# Text-to-speech variables
self.tts_enabled = True # Enable by default
self.tts_engine = None
self.tts_queue = queue.Queue()
self.tts_worker_thread = None
if TTS_AVAILABLE:
self.setup_tts()
if VOICE_AVAILABLE:
self.recognizer = sr.Recognizer()
self.microphone = None
self.voice_command_queue = queue.Queue()
else:
self.recognizer = None
self.microphone = None
self.voice_command_queue = None
# Azure OpenAI configuration
self.azure_openai_client = None
self.ai_enabled = False
self.azure_settings = {
'endpoint': '',
'deployment': '',
'api_key': '',
'api_version': '2024-08-01-preview'
}
# Create the GUI layout
self.create_widgets()
self.setup_layout()
# Defer blocking initialization to avoid GUI startup hang
self.root.after(100, self.deferred_setup)
# Start message processing
self.process_messages()
# Status update timer
self.update_status()
def create_widgets(self):
"""Create all GUI widgets."""
# Main container frames
self.create_header()
self.create_main_content()
self.create_status_bar()
def create_header(self):
"""Create the header with title and connection controls."""
# Header frame with modern gradient-like appearance
self.header_frame = tk.Frame(self.root, bg=DroneTheme.COLORS['bg_surface'], relief='flat', bd=0)
self.header_frame.pack(fill='x', padx=0, pady=0)
# Top row with title and critical controls
top_row = tk.Frame(self.header_frame, bg=DroneTheme.COLORS['bg_surface'])
top_row.pack(fill='x', padx=10, pady=(10, 5))
# Left side - title and mode
left_bar = tk.Frame(top_row, bg=DroneTheme.COLORS['bg_surface'])
left_bar.pack(side='left', fill='x', expand=True)
# Title with modern typography
title_label = tk.Label(
left_bar,
text="🚁 Tello Drone Control System",
font=('Segoe UI', 18, 'bold'),
fg='#ffffff',
bg=DroneTheme.COLORS['bg_surface']
)
title_label.pack(side='left', padx=10, pady=5)
# Mode indicator with toggle button
mode_bar = tk.Frame(left_bar, bg=DroneTheme.COLORS['bg_surface'])
mode_bar.pack(side='left', padx=15)
mode_text = "🎮 SIMULATION MODE" if self.simulation_mode else "🚁 REAL DRONE MODE"
self.mode_label = tk.Label(
mode_bar,
text=mode_text,
font=('Segoe UI', 10, 'bold'),
fg=DroneTheme.COLORS['info'] if self.simulation_mode else DroneTheme.COLORS['accent_orange'],
bg=DroneTheme.COLORS['bg_surface']
)
self.mode_label.pack(side='left', padx=5, pady=5)
# Mode toggle button
self.mode_toggle_btn = tk.Button(
mode_bar,
text="🔄",
width=3,
command=self.toggle_simulation_mode
)
DroneTheme.apply_button_style(self.mode_toggle_btn, 'primary')
self.mode_toggle_btn.pack(side='left', padx=3)
# Right side - connection controls (always visible)
right_bar = tk.Frame(top_row, bg=DroneTheme.COLORS['bg_surface'])
right_bar.pack(side='right', padx=10)
# Connection controls with modern styling
self.connect_btn = tk.Button(
right_bar,
text="🔗 Connect",
width=10,
command=self.toggle_connection
)
DroneTheme.apply_button_style(self.connect_btn, 'success')
self.connect_btn.pack(side='left', padx=3)
self.emergency_btn = tk.Button(
right_bar,
text="🚨 EMERGENCY",
width=12,
command=self.emergency_stop
)
DroneTheme.apply_button_style(self.emergency_btn, 'danger')
self.emergency_btn.pack(side='left', padx=3)
# Bottom row with feature buttons
bottom_row = tk.Frame(self.header_frame, bg=DroneTheme.COLORS['bg_surface'])
bottom_row.pack(fill='x', padx=10, pady=(0, 10))
# Feature buttons container
feature_bar = tk.Frame(bottom_row, bg=DroneTheme.COLORS['bg_surface'])
feature_bar.pack(side='left')
# Mission Planner button
self.mission_planner_btn = tk.Button(
feature_bar,
text="🧠 Mission Planner",
font=('Segoe UI', 9, 'bold'),
bg=DroneTheme.COLORS['accent_purple'],
fg='white',
relief='flat',
bd=0,
padx=10,
pady=6,
cursor='hand2',
command=self.open_mission_planner
)
self.mission_planner_btn.pack(side='left', padx=5)
# Panorama button
self.panorama_btn = tk.Button(
feature_bar,
text="📷 Panorama",
font=('Segoe UI', 9, 'bold'),
bg=DroneTheme.COLORS['accent_cyan'],
fg='white',
relief='flat',
bd=0,
padx=10,
pady=6,
cursor='hand2',
command=self.start_panorama_capture
)
self.panorama_btn.pack(side='left', padx=5)
# Settings button
self.settings_btn = tk.Button(
feature_bar,
text="⚙️",
font=('Segoe UI', 11, 'bold'),
bg=DroneTheme.COLORS['text_muted'],
fg='white',
width=3,
relief='flat',
bd=0,
padx=8,
pady=6,
cursor='hand2',
command=self.open_settings
)
self.settings_btn.pack(side='left', padx=5)
# Force layout update to ensure proper positioning
self.root.update_idletasks()
def create_main_content(self):
"""Create the main content area with video and controls."""
main_frame = tk.Frame(self.root, bg=DroneTheme.COLORS['bg_panel'])
main_frame.pack(fill='both', expand=True, padx=8, pady=8)
# Left panel - Video and status
left_panel = tk.Frame(main_frame, bg=DroneTheme.COLORS['bg_panel'], width=600)
left_panel.pack(side='left', fill='both', expand=True, padx=8)
# Video display
self.create_video_panel(left_panel)
# Right panel - Controls
right_panel = tk.Frame(main_frame, bg=DroneTheme.COLORS['bg_panel'], width=400)
right_panel.pack(side='right', fill='y', padx=8)
# Unified Flight Command Center (combines flight controls, status, voice/text, and AI status)
self.create_command_center(right_panel)
# Log output
self.create_log_panel(right_panel)
def create_video_panel(self, parent):
"""Create the video display panel."""
video_frame = tk.LabelFrame(
parent,
text="📹 Live Video Feed",
font=('Segoe UI', 12, 'bold'),
fg='white',
bg=DroneTheme.COLORS['bg_surface'],
relief='flat',
bd=1,
height=400
)
video_frame.pack(fill='both', expand=True, pady=8)
# Video canvas with modern styling
self.video_canvas = tk.Canvas(
video_frame,
bg=DroneTheme.COLORS['bg_root'],
width=480,
height=360,
highlightthickness=0,
relief='flat'
)
self.video_canvas.pack(expand=True, padx=15, pady=15)
# Vision Analysis Results Panel
vision_frame = tk.LabelFrame(
parent,
text="👁️ Vision Analysis Results",
font=('Segoe UI', 12, 'bold'),
fg='white',
bg=DroneTheme.COLORS['bg_surface'],
relief='flat',
bd=1,
height=150
)
vision_frame.pack(fill='x', pady=8)
# Vision results text area with scrollbar
vision_scroll_frame = tk.Frame(vision_frame, bg=DroneTheme.COLORS['bg_surface'])
vision_scroll_frame.pack(fill='both', expand=True, padx=15, pady=15)
self.vision_results = scrolledtext.ScrolledText(
vision_scroll_frame,
height=6,
width=50,
bg='#0f1419',
fg=DroneTheme.COLORS['info'],
font=('Segoe UI', 10),
insertbackground=DroneTheme.COLORS['info'],
wrap=tk.WORD,
state='disabled',
relief='flat',
bd=0
)
self.vision_results.pack(fill='both', expand=True)
# Video controls with modern styling
video_controls = tk.Frame(video_frame, bg=DroneTheme.COLORS['bg_surface'])
video_controls.pack(fill='x', padx=15, pady=8)
# Primary controls row
primary_controls = tk.Frame(video_controls, bg=DroneTheme.COLORS['bg_surface'])
primary_controls.pack(fill='x', pady=5)
self.video_btn = tk.Button(
primary_controls,
text="📹 Start Video",
command=self.toggle_video
)
DroneTheme.apply_button_style(self.video_btn, 'primary')
self.video_btn.pack(side='left', padx=8)
self.record_btn = tk.Button(
primary_controls,
text="⏺ Record",
command=self.toggle_recording
)
DroneTheme.apply_button_style(self.record_btn, 'accent_orange')
self.record_btn.pack(side='left', padx=8)
def create_command_center(self, parent):
"""Create unified Flight Command Center combining all controls and status."""
command_frame = tk.LabelFrame(
parent,
text="✈️ Flight Command Center & Status",
font=('Segoe UI', 12, 'bold'),
fg='white',
bg=DroneTheme.COLORS['bg_surface'],
relief='flat',
bd=1
)
command_frame.pack(fill='x', pady=8)
# Drone Status Section
status_section = tk.Frame(command_frame, bg=DroneTheme.COLORS['bg_surface'])
status_section.pack(fill='x', padx=15, pady=12)
status_label = tk.Label(
status_section,
text="📊 Drone Status",
font=('Segoe UI', 10, 'bold'),
fg='#ffffff',
bg=DroneTheme.COLORS['bg_surface']
)
status_label.pack(anchor='w')
# Status grid (compact 2x4 layout)
status_grid = tk.Frame(status_section, bg='#1a1f26')
status_grid.pack(fill='x', pady=8)
# Row 1: Connection and Battery
tk.Label(status_grid, text="Connection:", fg='white', bg='#1a1f26', font=('Segoe UI', 9)).grid(row=0, column=0, sticky='w', padx=8)
self.status_connection = tk.Label(status_grid, textvariable=self.connection_status, fg='#ff8a50', bg='#1a1f26', font=('Segoe UI', 9))
self.status_connection.grid(row=0, column=1, sticky='w', padx=8)
tk.Label(status_grid, text="Battery:", fg='white', bg='#1a1f26', font=('Segoe UI', 9)).grid(row=0, column=2, sticky='w', padx=25)
self.status_battery = tk.Label(status_grid, textvariable=self.battery_level, fg='#00e676', bg='#1a1f26', font=('Segoe UI', 9))
self.status_battery.grid(row=0, column=3, sticky='w', padx=8)
# Row 2: Flight Status and Detection
tk.Label(status_grid, text="Flying:", fg='white', bg='#1a1f26', font=('Segoe UI', 9)).grid(row=1, column=0, sticky='w', padx=8)
self.status_flying = tk.Label(status_grid, text="No", fg='#ff8a50', bg='#1a1f26', font=('Segoe UI', 9))
self.status_flying.grid(row=1, column=1, sticky='w', padx=8)
tk.Label(status_grid, text="Detection:", fg='white', bg='#1a1f26', font=('Segoe UI', 9)).grid(row=1, column=2, sticky='w', padx=25)
self.status_detection = tk.Label(status_grid, textvariable=self.detection_mode, fg='#ff8a50', bg='#1a1f26', font=('Segoe UI', 9))
self.status_detection.grid(row=1, column=3, sticky='w', padx=8)
# Separator line
separator = tk.Frame(command_frame, bg='#444444', height=1)
separator.pack(fill='x', padx=10, pady=5)
# Flight Controls Section
controls_label = tk.Label(
command_frame,
text="🎮 Flight Controls",
font=('Segoe UI', 10, 'bold'),
fg='#ffffff',
bg=DroneTheme.COLORS['bg_surface']
)
controls_label.pack(anchor='w', padx=15)
# Top row - Primary actions and AI status
top_row = tk.Frame(command_frame, bg='#1a1f26')
top_row.pack(fill='x', padx=15, pady=12)
# Flight buttons with modern styling
self.takeoff_btn = tk.Button(
top_row,
text="🛫 Takeoff",
width=10,
command=self.takeoff
)
DroneTheme.apply_button_style(self.takeoff_btn, 'accent_green')
self.takeoff_btn.pack(side='left', padx=5)
self.land_btn = tk.Button(
top_row,
text="🛬 Land",
width=10,
command=self.land
)
DroneTheme.apply_button_style(self.land_btn, 'accent_orange')
self.land_btn.pack(side='left', padx=5)
# Voice control button
if VOICE_AVAILABLE:
self.voice_btn = tk.Button(
top_row,
text="🎤 Start Voice",
bg=DroneTheme.COLORS['primary'],
fg='white',
font=('Segoe UI', 10, 'bold'),
width=12,
relief='flat',
bd=0,
padx=15,
pady=8,
cursor='hand2',
command=self.toggle_voice
)
self.voice_btn.pack(side='left', padx=5)
# Voice status
self.voice_status_label = tk.Label(
top_row,
text="🔴 Not Listening",
font=('Segoe UI', 9),
fg='#ff8a50',
bg=DroneTheme.COLORS['bg_surface']
)
self.voice_status_label.pack(side='left', padx=8)
# AI status chip
ai_color = '#10b981' if self.ai_enabled else '#f59e0b'
ai_text = "🤖 AI Ready" if self.ai_enabled else "🤖 Configure"
self.ai_status_chip = tk.Button(
top_row,
text=ai_text,
font=('Segoe UI', 8, 'bold'),
bg=ai_color,
fg='white',
width=12,
relief='flat',
bd=0,
padx=15,
pady=6,
cursor='hand2',
command=self.open_settings
)
self.ai_status_chip.pack(side='right', padx=5)
# Input row - Text command entry with modern styling
input_row = tk.Frame(command_frame, bg='#1a1f26')
input_row.pack(fill='x', padx=15, pady=12)
tk.Label(
input_row,
text="Text Command:",
font=('Segoe UI', 10, 'bold'),
fg='white',
bg=DroneTheme.COLORS['bg_surface']
).pack(side='left', padx=8)
self.command_entry = tk.Entry(
input_row,
font=('Segoe UI', 11),
bg='#2d3748',
fg='white',
insertbackground=DroneTheme.COLORS['info'],
width=80,
relief='flat',
bd=1
)
self.command_entry.pack(side='left', fill='x', expand=True, padx=8)
self.command_entry.bind('<Return>', lambda e: self.execute_command(self.command_entry.get(), "text"))
self.execute_btn = tk.Button(
input_row,
text="▶ Execute",
bg=DroneTheme.COLORS['primary'],
fg='white',
font=('Segoe UI', 10, 'bold'),
relief='flat',
bd=0,
padx=15,
pady=8,
cursor='hand2',
command=lambda: self.execute_command(self.command_entry.get(), "text")
)
self.execute_btn.pack(side='right', padx=5)
# Vision analysis buttons with modern styling
self.vision_analyze_btn = tk.Button(
input_row,
text="👁️ Analyze View",
bg='#a855f7',
fg='white',
font=('Segoe UI', 10, 'bold'),
relief='flat',
bd=0,
padx=15,
pady=8,
cursor='hand2',
command=self.start_vision_analysis
)
self.vision_analyze_btn.pack(side='right', padx=5)
# Continuous vision analysis toggle
self.continuous_vision_btn = tk.Button(
input_row,
text="🔄 Start Auto-Vision",
bg=DroneTheme.COLORS['success'],
fg='white',
font=('Segoe UI', 10, 'bold'),
relief='flat',
bd=0,
padx=15,
pady=8,
cursor='hand2',
command=self.toggle_continuous_vision
)
self.continuous_vision_btn.pack(side='right', padx=5)
# AI Mission Planner button
# Hints row - Examples with modern styling
hints_row = tk.Frame(command_frame, bg='#1a1f26')
hints_row.pack(fill='x', padx=15, pady=(0, 12))
tk.Label(
hints_row,
text="💡 Examples: \"fly forward 2 meters\", \"take photo\", \"describe what you see\", \"analyze current view\"",
font=('Segoe UI', 8),
fg='#9ca3af',
bg=DroneTheme.COLORS['bg_surface'],
wraplength=350
).pack(side='left', padx=8)
def execute_command(self, cmd_text, source):
"""Unified command execution for buttons, voice, and text with sequential processing."""
if not cmd_text or not cmd_text.strip():
return
cmd_text_processed = cmd_text.strip().lower()
# Log command with source
self.log(f"🎯 Command ({source}): {cmd_text_processed}")
# Clear entry immediately (on GUI thread)
if hasattr(self, 'command_entry') and source == "text":
self.command_entry.delete(0, tk.END)
# Safety check - emergency should only be via header button
if 'emergency' in cmd_text_processed or 'stop' in cmd_text_processed:
self.log("⚠️ Use EMERGENCY button for safety stops")
return