-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
470 lines (391 loc) Β· 20.3 KB
/
Copy pathapp.py
File metadata and controls
470 lines (391 loc) Β· 20.3 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
import tkinter as tk
from tkinter import ttk, messagebox
import serial
import serial.tools.list_ports
import threading
import time
import random
BAUD_RATES = [9600, 38400, 115200]
class GestureVisualizer(tk.Canvas):
"""Visual feedback for gestures with animated hand"""
def __init__(self, parent):
# Premium dark slate theme matching modern aesthetics
super().__init__(parent, height=260, bg='#1A1A2E', highlightthickness=0)
self.center_x = 300
self.center_y = 130
# Draw dynamic glowing background borders on canvas
self.create_rounded_rect(10, 10, 580, 250, radius=20, fill='#1A1A2E', outline='#16213E', width=3)
# Create hand emoji that will move
self.hand_id = self.create_text(
self.center_x, self.center_y - 15, text="β", font=("Segoe UI Emoji", 90), fill="#FFFFFF"
)
# Gesture text below
self.gesture_text = self.create_text(
self.center_x, self.center_y + 80, text="WAITING FOR GESTURE",
font=("Montserrat", 16, "bold"), fill="#8E9AA6"
)
# Modern glowing position indicators
self.left_indicator = self.create_oval(40, 115, 60, 135, fill="#00E5FF", outline="", state='hidden')
self.center_indicator = self.create_oval(290, 115, 310, 135, fill="#00E676", outline="", state='hidden')
self.right_indicator = self.create_oval(540, 115, 560, 135, fill="#FF2D55", outline="", state='hidden')
self.current_position = "CENTER"
self.animation_in_progress = False
def create_rounded_rect(self, x1, y1, x2, y2, radius=25, **kwargs):
points = [x1+radius, y1,
x1+radius, y1,
x2-radius, y1,
x2-radius, y1,
x2, y1,
x2, y1+radius,
x2, y1+radius,
x2, y2-radius,
x2, y2-radius,
x2, y2,
x2-radius, y2,
x2-radius, y2,
x1+radius, y2,
x1+radius, y2,
x1, y2,
x1, y2-radius,
x1, y2-radius,
x1, y1+radius,
x1, y1+radius,
x1, y1]
return self.create_polygon(points, **kwargs, smooth=True)
def show_gesture(self, gesture):
"""Animate hand to gesture position with color change"""
if self.animation_in_progress:
# Complete current animation immediately or bypass to keep UI responsive
self.animation_in_progress = False
gesture_config = {
"LEFT": {
"x": 120,
"emoji": "π",
"color": "#00E5FF",
"text": "βοΈ LEFT GESTURE DETECTED",
"indicator": self.left_indicator
},
"CENTER": {
"x": self.center_x,
"emoji": "π",
"color": "#00E676",
"text": "π CENTER DETECTED",
"indicator": self.center_indicator
},
"RIGHT": {
"x": 480,
"emoji": "π",
"color": "#FF2D55",
"text": "βΆοΈ RIGHT GESTURE DETECTED",
"indicator": self.right_indicator
},
"NONE": {
"x": self.center_x,
"emoji": "β",
"color": "#8E9AA6",
"text": "β NO GESTURE DETECTED",
"indicator": self.center_indicator
}
}
if gesture not in gesture_config:
return
config = gesture_config[gesture]
# Hide all indicators
self.itemconfig(self.left_indicator, state='hidden')
self.itemconfig(self.center_indicator, state='hidden')
self.itemconfig(self.right_indicator, state='hidden')
# Show target indicator
self.itemconfig(config["indicator"], state='normal')
# Run smooth animated slide transition
self.animate_to_position(config["x"], config["emoji"], config["color"], config["text"])
self.current_position = gesture
def animate_to_position(self, target_x, emoji, color, text):
"""Smooth slide & pop transition animation"""
self.animation_in_progress = True
current_coords = self.coords(self.hand_id)
if not current_coords:
return
current_x = current_coords[0]
steps = 12
dx = (target_x - current_x) / steps
def move_step(step):
if not self.animation_in_progress:
return
if step < steps:
self.move(self.hand_id, dx, 0)
self.after(10, lambda: move_step(step + 1))
else:
self.coords(self.hand_id, target_x, self.center_y - 15)
self.itemconfig(self.hand_id, text=emoji, fill=color)
self.itemconfig(self.gesture_text, text=text, fill=color)
# Pop scale micro-animation
self.scale(self.hand_id, target_x, self.center_y - 15, 1.2, 1.2)
self.after(100, lambda: self.scale(self.hand_id, target_x, self.center_y - 15, 0.833, 0.833))
self.after(200, lambda: setattr(self, 'animation_in_progress', False))
move_step(0)
class HC05App:
def __init__(self, root):
self.root = root
self.root.title("π― HC-05 Gesture Controller Suite")
self.root.geometry("620://800" if False else "620x820")
self.root.resizable(False, False)
# Dark Space Palette
self.root.configure(bg='#0F0F1A')
self.ser = None
self.is_connected = False
self.sim_active = False
self.gesture_count = {"LEFT": 0, "CENTER": 0, "RIGHT": 0, "NONE": 0}
self.total_gestures = 0
self.setup_ui()
self.refresh_ports(show_msg=False)
def setup_ui(self):
# Configure ttk styles
style = ttk.Style()
style.theme_use('clam')
style.configure("TCombobox",
fieldbackground="#16213E",
background="#0F0F1A",
foreground="#FFFFFF",
bordercolor="#00E5FF",
darkcolor="#16213E",
lightcolor="#16213E")
main_frame = tk.Frame(self.root, bg='#0F0F1A', padx=20, pady=15)
main_frame.pack(fill=tk.BOTH, expand=True)
title = tk.Label(main_frame, text="π― GESTURE CONTROLLER", font=("Montserrat", 22, "bold"),
bg='#0F0F1A', fg='#00E5FF')
title.pack(pady=(5, 2))
subtitle = tk.Label(main_frame, text="Ultrasonic Sensor Live Bluetooth Suite",
font=("Segoe UI", 11), bg='#0F0F1A', fg='#8E9AA6')
subtitle.pack(pady=(0, 15))
# --- CONNECTION CARD ---
connection_frame = tk.Frame(main_frame, bg='#161625', bd=0)
connection_frame.pack(fill=tk.X, pady=(0, 15))
# Status indicators
status_container = tk.Frame(connection_frame, bg='#161625', pady=12)
status_container.pack(fill=tk.X)
self.status_dot = tk.Canvas(status_container, width=18, height=18, bg='#161625', highlightthickness=0)
self.status_dot.pack(side=tk.LEFT, padx=(20, 10))
self.dot_id = self.status_dot.create_oval(2, 2, 16, 16, fill='#FF2D55', outline='')
self.status_label = tk.Label(status_container, text="Not Connected", font=("Montserrat", 13, "bold"),
bg='#161625', fg='#FF2D55')
self.status_label.pack(side=tk.LEFT)
# Port Selection row
port_frame = tk.Frame(connection_frame, bg='#161625', pady=8)
port_frame.pack(fill=tk.X, padx=20)
tk.Label(port_frame, text="COM Port:", font=("Segoe UI", 11, "bold"), bg='#161625', fg='#8E9AA6').pack(side=tk.LEFT, padx=(0, 10))
self.com_var = tk.StringVar()
self.com_box = ttk.Combobox(port_frame, textvariable=self.com_var, state="readonly", width=18, font=("Segoe UI", 11))
self.com_box.pack(side=tk.LEFT, padx=(0, 10))
refresh_btn = tk.Button(port_frame, text="π Refresh", command=lambda: self.refresh_ports(show_msg=True),
bg='#00E5FF', fg='#0F0F1A', font=("Segoe UI", 10, "bold"),
activebackground='#00B8D4', activeforeground='#0F0F1A',
relief=tk.FLAT, padx=10, cursor='hand2')
refresh_btn.pack(side=tk.LEFT)
# Connect & Disconnect buttons
btn_frame = tk.Frame(connection_frame, bg='#161625', pady=15)
btn_frame.pack()
self.connect_btn = tk.Button(btn_frame, text="π Connect", command=self.connect_hc05,
bg='#00E676', fg='#0F0F1A', font=("Segoe UI", 11, "bold"),
activebackground='#00C853', activeforeground='#0F0F1A',
relief=tk.FLAT, padx=22, pady=8, cursor='hand2')
self.connect_btn.pack(side=tk.LEFT, padx=8)
self.disconnect_btn = tk.Button(btn_frame, text="βΈοΈ Disconnect", command=self.disconnect_hc05,
bg='#FF2D55', fg='#FFFFFF', font=("Segoe UI", 11, "bold"),
activebackground='#D500F9', activeforeground='#FFFFFF',
relief=tk.FLAT, padx=22, pady=8, state=tk.DISABLED, cursor='hand2')
self.disconnect_btn.pack(side=tk.LEFT, padx=8)
# --- GESTURE VISUALIZER ---
viz_label = tk.Label(main_frame, text="π‘ Live Hand Tracking", font=("Montserrat", 14, "bold"),
bg='#0F0F1A', fg='#FFFFFF')
viz_label.pack(pady=(5, 3))
self.visualizer = GestureVisualizer(main_frame)
self.visualizer.pack(fill=tk.X, pady=(0, 15))
# --- SIMULATOR INJECTION CONTROL PANEL ---
sim_lbl_frame = tk.Frame(main_frame, bg='#0F0F1A')
sim_lbl_frame.pack(fill=tk.X)
tk.Label(sim_lbl_frame, text="πΉοΈ Manual Gesture Simulator (Demo Mode)", font=("Montserrat", 11, "bold"),
bg='#0F0F1A', fg='#00E5FF').pack(side=tk.LEFT, pady=(5, 3))
sim_btn_frame = tk.Frame(main_frame, bg='#161625', pady=12)
sim_btn_frame.pack(fill=tk.X, pady=(0, 15))
sim_gestures = [
("π LEFT", "LEFT", "#00E5FF"),
("π CENTER", "CENTER", "#00E676"),
("π RIGHT", "RIGHT", "#FF2D55"),
("β NONE", "NONE", "#8E9AA6")
]
for name, gesture_val, color in sim_gestures:
btn = tk.Button(sim_btn_frame, text=name,
command=lambda g=gesture_val: self.inject_simulation_gesture(g),
bg='#252538', fg=color, font=("Segoe UI", 10, "bold"),
activebackground='#35354A', activeforeground=color,
relief=tk.FLAT, padx=12, pady=6, cursor='hand2')
btn.pack(side=tk.LEFT, expand=True, padx=4)
# --- STATISTICS CARD ---
stats_frame = tk.Frame(main_frame, bg='#161625', pady=15)
stats_frame.pack(fill=tk.BOTH, expand=True)
tk.Label(stats_frame, text="π Gesture Detection Analytics", font=("Montserrat", 13, "bold"),
bg='#161625', fg='#FFFFFF').pack(pady=(0, 10))
count_grid = tk.Frame(stats_frame, bg='#161625')
count_grid.pack(pady=5)
gestures_config = [
("LEFT", "π", "#00E5FF"),
("RIGHT", "π", "#FF2D55"),
("CENTER", "π", "#00E676"),
("NONE", "β", "#8E9AA6")
]
self.count_labels = {}
for i, (name, emoji, color) in enumerate(gestures_config):
frame = tk.Frame(count_grid, bg='#1A1A2E', relief=tk.FLAT, padx=18, pady=8)
frame.grid(row=i//2, column=i%2, padx=10, pady=8, sticky='ew')
tk.Label(frame, text=emoji, font=("Segoe UI Emoji", 20), bg='#1A1A2E', fg='#FFFFFF').pack()
tk.Label(frame, text=name, font=("Segoe UI", 9, "bold"), bg='#1A1A2E', fg='#8E9AA6').pack()
count_label = tk.Label(frame, text="0", font=("Montserrat", 18, "bold"), bg='#1A1A2E', fg=color)
count_label.pack()
self.count_labels[name] = count_label
# Total Counter & Console Row
bottom_frame = tk.Frame(stats_frame, bg='#161625', padx=20)
bottom_frame.pack(fill=tk.X, pady=(8, 0))
self.total_label = tk.Label(bottom_frame, text="Total: 0", font=("Montserrat", 12, "bold"),
bg='#161625', fg='#00E676')
self.total_label.pack(side=tk.LEFT)
# Last Received Data Log
self.received_label = tk.Label(bottom_frame, text="Waiting for connection...", font=("Segoe UI", 10),
bg='#161625', fg='#8E9AA6')
self.received_label.pack(side=tk.RIGHT)
# Reset Button
reset_btn = tk.Button(stats_frame, text="π Reset Analytics", command=self.reset_stats,
bg='#E65100', fg='white', font=("Segoe UI", 10, "bold"),
activebackground='#F57C00', activeforeground='white',
relief=tk.FLAT, padx=15, pady=6, cursor='hand2')
reset_btn.pack(pady=(12, 0))
def refresh_ports(self, show_msg=True):
ports = serial.tools.list_ports.comports()
devices = [p.device for p in ports]
devices.append("π SIMULATOR MODE") # Fallback demo simulator mode
self.com_box['values'] = devices
if devices:
self.com_box.current(0)
if show_msg:
messagebox.showinfo("Ports Refreshed", f"Found {len(ports)} active hardware COM port(s).")
def connect_hc05(self):
com = self.com_var.get()
if not com:
messagebox.showwarning("Select Port", "Please select an interface port or select 'π SIMULATOR MODE'")
return
if "SIMULATOR" in com:
self.sim_active = True
self.is_connected = True
self.status_dot.itemconfig(self.dot_id, fill='#00E5FF')
self.status_label.config(text="SIMULATOR ACTIVE", fg='#00E5FF')
self.connect_btn.config(state=tk.DISABLED)
self.disconnect_btn.config(state=tk.NORMAL)
self.com_box.config(state=tk.DISABLED)
self.received_label.config(text="β
Simulator Engine Online!")
return
try:
connected = False
for baud in BAUD_RATES:
try:
print(f"Connecting to {com} at {baud} baud...")
self.ser = serial.Serial(
port=com,
baudrate=baud,
timeout=1.5,
bytesize=serial.EIGHTBITS,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE
)
time.sleep(1.5)
self.ser.reset_input_buffer()
self.ser.reset_output_buffer()
print(f"Connection success at {baud}!")
connected = True
break
except Exception as e:
if self.ser and self.ser.is_open:
self.ser.close()
continue
if not connected:
raise Exception("Could not open port. Double check HC-05 power and pairing.")
self.is_connected = True
self.status_dot.itemconfig(self.dot_id, fill='#00E676')
self.status_label.config(text=f"Connected: {com}", fg='#00E676')
self.connect_btn.config(state=tk.DISABLED)
self.disconnect_btn.config(state=tk.NORMAL)
self.com_box.config(state=tk.DISABLED)
self.received_label.config(text="β
Connected! Listening for gestures...")
# Start background reader thread
threading.Thread(target=self.read_from_hc05, daemon=True).start()
except Exception as e:
messagebox.showerror("Connection Error", f"Failed to connect:\n{str(e)}")
def inject_simulation_gesture(self, gesture):
"""Allow manual simulation inject triggers even if disconnected, or warn nicely"""
if not self.is_connected:
self.received_label.config(text="β οΈ Please click 'Connect' to enable Simulator Mode first!")
return
timestamp = time.strftime("%H:%M:%S")
self.received_label.config(text=f"π¨ [SIMULATED]: {gesture} at {timestamp}")
self.visualizer.show_gesture(gesture)
self.gesture_count[gesture] += 1
self.total_gestures += 1
self.update_stats()
def disconnect_hc05(self):
self.is_connected = False
self.sim_active = False
if self.ser and self.ser.is_open:
try:
self.ser.close()
except:
pass
self.status_dot.itemconfig(self.dot_id, fill='#FF2D55')
self.status_label.config(text="Not Connected", fg='#FF2D55')
self.connect_btn.config(state=tk.NORMAL)
self.disconnect_btn.config(state=tk.DISABLED)
self.com_box.config(state='readonly')
self.received_label.config(text="Waiting for data...")
def reset_stats(self):
self.gesture_count = {"LEFT": 0, "CENTER": 0, "RIGHT": 0, "NONE": 0}
self.total_gestures = 0
self.update_stats()
messagebox.showinfo("Analytics Reset", "All gesture statistics have been successfully cleared.")
def update_stats(self):
for gesture, count in self.gesture_count.items():
self.count_labels[gesture].config(text=str(count))
self.total_label.config(text=f"Total: {self.total_gestures}")
def read_from_hc05(self):
print("Starting background serial thread reader...")
while self.is_connected:
try:
if self.ser and self.ser.is_open and self.ser.in_waiting > 0:
line = self.ser.readline().decode('utf-8', errors='ignore').strip()
print(f"Received raw line: '{line}'")
if line:
gesture = None
if "[BT:" in line:
start = line.find("[BT:") + 4
end = line.find("]", start)
if start > 3 and end > start:
gesture = line[start:end].strip().upper()
else:
gesture = line.upper()
timestamp = time.strftime("%H:%M:%S")
safe_line = line[:25] + "..." if len(line) > 25 else line
self.root.after(0, lambda l=safe_line: self.received_label.config(
text=f"π¨ {l} at {timestamp}"
))
if gesture in ["LEFT", "CENTER", "RIGHT", "NONE"]:
# Animate the visualizer
self.root.after(0, lambda g=gesture: self.visualizer.show_gesture(g))
# Increment counters
self.gesture_count[gesture] += 1
self.total_gestures += 1
self.root.after(0, self.update_stats)
except Exception as e:
print(f"Serial reader exception: {e}")
time.sleep(0.02)
def main():
root = tk.Tk()
app = HC05App(root)
root.mainloop()
if __name__ == "__main__":
main()