-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathclick_receiver.py
More file actions
3043 lines (2431 loc) · 134 KB
/
click_receiver.py
File metadata and controls
3043 lines (2431 loc) · 134 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import datetime as dt
import tkinter as tk
from tkinter import messagebox
import time
import threading
import pyautogui
import sys
import socket
import os
import csv
import json
import statistics
from pathlib import Path
from PIL import Image, ImageTk, ImageDraw
import ctypes
import platform
from datetime import datetime, timedelta
# Integrated logging functionality (replaces shared_logging dependency)
class IntegratedLogger:
"""Integrated logging utility for consistent file management"""
def __init__(self, app_name):
self.app_name = app_name
self._setup_directories()
def _setup_directories(self):
"""Setup centralized DIC Quality Control directory structure"""
# Use Documents folder as the base
documents_path = Path.home() / "Documents"
# Create main DIC Quality Control directory
self.main_dic_directory = documents_path / "DIC Quality Control"
# Create app-specific directory within DIC Quality Control
self.base_log_directory = self.main_dic_directory / self.app_name
self.export_directory = self.base_log_directory # Direct export to app folder
# Create directories
self.main_dic_directory.mkdir(parents=True, exist_ok=True)
self.base_log_directory.mkdir(parents=True, exist_ok=True)
def get_camera_log_directory(self):
"""Get the camera logs directory path as string"""
return str(self.export_directory)
def get_export_directory(self):
"""Get the exports directory path as string"""
return str(self.export_directory)
def get_log_file_path(self, directory_type, filename):
"""Get full path for a log file"""
return str(self.export_directory / filename)
def create_timestamped_filename(self, prefix, extension, include_microseconds=True):
"""Create a timestamped filename"""
if include_microseconds:
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S_%f")[:-3] # Remove last 3 digits for milliseconds
else:
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
return f"{prefix}_{timestamp}.{extension}"
def write_csv_log(self, directory_type, filename, data, fieldnames=None):
"""Write data to a CSV log file"""
if not data:
return
if fieldnames is None and data:
fieldnames = list(data[0].keys())
filepath = self.get_log_file_path(directory_type, filename)
with open(filepath, 'w', newline='', encoding='utf-8') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(data)
return filepath
def append_csv_log(self, directory_type, filename, data, fieldnames=None):
"""Append data to a CSV log file"""
filepath = self.get_log_file_path(directory_type, filename)
# Convert single dict to list
if isinstance(data, dict):
data = [data]
# Check if file exists
file_exists = os.path.exists(filepath)
with open(filepath, 'a', newline='', encoding='utf-8') as csvfile:
if fieldnames is None and data:
fieldnames = list(data[0].keys())
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
# Write header if file is new
if not file_exists:
writer.writeheader()
writer.writerows(data)
return filepath
def print_directory_structure(self):
"""Print the directory structure for debugging"""
print(" DIC Quality Control Directory Structure:")
print(f" Main DIC Directory: {self.main_dic_directory}")
print(f" App Folder ({self.app_name}): {self.base_log_directory}")
print(" Files are saved directly to the app folder")
# Create logger instance for this app
shared_logger = IntegratedLogger("Receiver")
class ClockSyncManager:
def __init__(self, is_forwarder=False):
self.is_forwarder = is_forwarder
self.time_offset = 0.0 # Time difference in seconds (positive means remote is ahead)
self.sync_accuracy = None # Standard deviation of measurements
self.last_sync_time = None
self.sync_measurements = []
# Network settings
self.sync_port = 9998 # Different from main UDP port
self.sync_socket = None
self.sync_listening = False
# Sync statistics
self.round_trip_times = []
self.time_differences = []
# Enhanced sync settings
self.max_measurements = 50 # Keep more measurements for better accuracy
self.min_measurements_for_sync = 5 # Require more measurements before updating
self.outlier_threshold = 2.0 # More aggressive outlier removal
self.force_sync_samples = 10 # Take multiple samples during force sync
def start_sync_service(self):
"""Start the clock sync service"""
try:
self.sync_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.sync_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.sync_socket.bind(('', self.sync_port))
self.sync_socket.settimeout(1.0)
self.sync_listening = True
sync_thread = threading.Thread(target=self._sync_listener, daemon=True)
sync_thread.start()
print(f" Clock sync service started on port {self.sync_port}")
return True
except Exception as e:
print(f" Clock sync service failed to start: {e}")
return False
def stop_sync_service(self):
"""Stop the clock sync service"""
self.sync_listening = False
if self.sync_socket:
self.sync_socket.close()
self.sync_socket = None
def _sync_listener(self):
"""Listen for sync requests/responses"""
while self.sync_listening:
try:
data, addr = self.sync_socket.recvfrom(1024)
self._handle_sync_message(data, addr)
except socket.timeout:
continue
except Exception as e:
if self.sync_listening:
print(f" Sync listener error: {e}")
break
def _handle_sync_message(self, data, addr):
"""Handle incoming sync messages with improved timing - FIXED VERSION"""
try:
# Capture receive timestamp immediately
receive_time = time.time()
message = json.loads(data.decode('utf-8'))
if message['type'] == 'sync_request':
# Respond with our timestamp immediately
response_time = time.time()
response = {
'type': 'sync_response',
'original_timestamp': message['timestamp'],
'response_timestamp': response_time,
'receive_timestamp': receive_time, # When we received the request
'responder': 'forwarder' if self.is_forwarder else 'clicker'
}
self.sync_socket.sendto(
json.dumps(response).encode('utf-8'),
addr
)
elif message['type'] == 'sync_response':
# Calculate time difference with improved algorithm
current_time = time.time()
# Calculate round trip time
round_trip = current_time - message['original_timestamp']
# Use receive timestamp if available for better accuracy
if 'receive_timestamp' in message:
# More accurate: use actual receive time at remote
processing_delay = message['response_timestamp'] - message['receive_timestamp']
one_way_trip = (round_trip - processing_delay) / 2
remote_time_when_received = message['receive_timestamp']
our_time_when_remote_received = message['original_timestamp'] + one_way_trip
time_diff = remote_time_when_received - our_time_when_remote_received
else:
# Fallback to simple method
estimated_one_way = round_trip / 2
remote_time_at_response = message['response_timestamp']
our_time_at_remote_response = current_time - estimated_one_way
time_diff = remote_time_at_response - our_time_at_remote_response
# Only accept measurements with reasonable round trip times
if round_trip < 0.1: # Less than 100ms round trip
self.round_trip_times.append(round_trip)
self.time_differences.append(time_diff)
# Keep only recent measurements
if len(self.time_differences) > self.max_measurements:
self.time_differences.pop(0)
self.round_trip_times.pop(0)
# Update offset with improved filtering
if len(self.time_differences) >= self.min_measurements_for_sync:
self._update_time_offset()
# FIX: Use datetime instead of datetime.datetime
self.last_sync_time = datetime.now()
print(f" Sync measurement: offset={time_diff * 1000:+.1f}ms, rtt={round_trip * 1000:.1f}ms")
else:
print(f" Discarded sync measurement: RTT too high ({round_trip * 1000:.1f}ms)")
except Exception as e:
print(f" Sync message handling error: {e}")
# Fix 3: Replace the format_sync_status method in ClockSyncManager:
def format_sync_status(self):
"""Format sync status for display - FIXED VERSION"""
if not self.last_sync_time:
return " No sync data available"
# FIX: Use datetime instead of datetime.datetime
age = (datetime.now() - self.last_sync_time).total_seconds()
offset_ms = self.time_offset * 1000
accuracy_ms = self.sync_accuracy * 1000 if self.sync_accuracy else 0
status_emoji = "" if abs(offset_ms) < 50 and accuracy_ms < 10 else "" if abs(offset_ms) < 100 else ""
return f"""{status_emoji} Clock Sync Status:
Offset: {offset_ms:+.1f}ms (remote vs local)
Accuracy: ±{accuracy_ms:.1f}ms
Last sync: {age:.0f}s ago
Measurements: {len(self.time_differences)} ({len(self._advanced_filter_outliers(self.time_differences))} filtered)"""
def _update_time_offset(self):
"""Update time offset with improved filtering"""
if len(self.time_differences) < self.min_measurements_for_sync:
return
# Use multiple filtering techniques
filtered_diffs = self._advanced_filter_outliers(self.time_differences)
if len(filtered_diffs) >= 3:
# Use median for robustness against outliers
old_offset = self.time_offset
self.time_offset = statistics.median(filtered_diffs)
self.sync_accuracy = statistics.stdev(filtered_diffs) if len(filtered_diffs) > 1 else 0
offset_change = abs(self.time_offset - old_offset) * 1000
if offset_change > 10: # Significant change
print(
f" Clock offset updated: {old_offset * 1000:+.1f}ms → {self.time_offset * 1000:+.1f}ms (change: {offset_change:.1f}ms)")
def _advanced_filter_outliers(self, values):
"""Advanced outlier filtering using multiple methods"""
if len(values) < 4:
return values
# Method 1: IQR filtering
sorted_values = sorted(values)
q1 = sorted_values[len(values) // 4]
q3 = sorted_values[3 * len(values) // 4]
iqr = q3 - q1
lower_bound = q1 - self.outlier_threshold * iqr
upper_bound = q3 + self.outlier_threshold * iqr
iqr_filtered = [v for v in values if lower_bound <= v <= upper_bound]
# Method 2: Standard deviation filtering
if len(iqr_filtered) > 3:
mean_val = statistics.mean(iqr_filtered)
std_val = statistics.stdev(iqr_filtered)
# Keep values within 2 standard deviations
std_filtered = [v for v in iqr_filtered if abs(v - mean_val) <= 2 * std_val]
return std_filtered if len(std_filtered) >= 3 else iqr_filtered
return iqr_filtered
def force_sync_with_multiple_samples(self, remote_ip, samples=None):
"""Force sync with multiple rapid samples for better accuracy"""
if not self.sync_socket:
return False
samples = samples or self.force_sync_samples
print(f" Starting force sync with {samples} samples...")
successful_samples = 0
start_time = time.time()
for i in range(samples):
try:
# Send sync request
request = {
'type': 'sync_request',
'timestamp': time.time(),
'sender': 'forwarder' if self.is_forwarder else 'clicker',
'sample_number': i + 1,
'total_samples': samples
}
self.sync_socket.sendto(
json.dumps(request).encode('utf-8'),
(remote_ip, self.sync_port)
)
successful_samples += 1
# Small delay between samples to avoid overwhelming
if i < samples - 1:
time.sleep(0.1)
except Exception as e:
print(f" Force sync sample {i + 1} failed: {e}")
# Wait a bit for responses to come back
time.sleep(1.0)
elapsed = time.time() - start_time
print(f" Force sync completed: {successful_samples}/{samples} samples sent in {elapsed:.1f}s")
return successful_samples > 0
def sync_with_remote(self, remote_ip):
"""Regular sync with remote computer (single sample)"""
if not self.sync_socket:
return False
try:
# Send sync request
request = {
'type': 'sync_request',
'timestamp': time.time(),
'sender': 'forwarder' if self.is_forwarder else 'clicker'
}
self.sync_socket.sendto(
json.dumps(request).encode('utf-8'),
(remote_ip, self.sync_port)
)
return True
except Exception as e:
print(f" Sync request failed: {e}")
return False
def get_synchronized_timestamp(self):
"""Get timestamp adjusted for remote computer's clock"""
local_time = time.time()
return local_time + self.time_offset
def get_sync_info(self):
"""Get current synchronization information"""
return {
'time_offset_ms': self.time_offset * 1000,
'sync_accuracy_ms': self.sync_accuracy * 1000 if self.sync_accuracy else None,
'last_sync': self.last_sync_time.isoformat() if self.last_sync_time else None,
'round_trip_avg_ms': statistics.mean(self.round_trip_times) * 1000 if self.round_trip_times else None,
'round_trip_min_ms': min(self.round_trip_times) * 1000 if self.round_trip_times else None,
'round_trip_max_ms': max(self.round_trip_times) * 1000 if self.round_trip_times else None,
'measurements_count': len(self.time_differences),
'measurements_filtered': len(
self._advanced_filter_outliers(self.time_differences)) if self.time_differences else 0
}
def reset_sync_data(self):
"""Reset all sync measurements and start fresh"""
print(" Resetting all sync data...")
self.time_offset = 0.0
self.sync_accuracy = None
self.last_sync_time = None
self.round_trip_times.clear()
self.time_differences.clear()
print(" Sync data reset - ready for fresh measurements")
def get_detailed_sync_stats(self):
"""Get detailed statistics for troubleshooting"""
if not self.time_differences:
return "No sync data available"
stats = []
stats.append(f" DETAILED SYNC STATISTICS")
stats.append(f"{'=' * 40}")
stats.append(f"Total measurements: {len(self.time_differences)}")
stats.append(f"Filtered measurements: {len(self._advanced_filter_outliers(self.time_differences))}")
stats.append(f"Current offset: {self.time_offset * 1000:+.2f}ms")
if self.sync_accuracy:
stats.append(f"Accuracy (std dev): ±{self.sync_accuracy * 1000:.2f}ms")
if self.round_trip_times:
rtt_ms = [rtt * 1000 for rtt in self.round_trip_times]
stats.append(f"Round trip times (ms):")
stats.append(f" Min: {min(rtt_ms):.2f}")
stats.append(f" Max: {max(rtt_ms):.2f}")
stats.append(f" Avg: {statistics.mean(rtt_ms):.2f}")
stats.append(f" Med: {statistics.median(rtt_ms):.2f}")
if self.time_differences:
offset_ms = [diff * 1000 for diff in self.time_differences]
filtered_ms = [diff * 1000 for diff in self._advanced_filter_outliers(self.time_differences)]
stats.append(f"Time differences (all, ms):")
stats.append(f" Min: {min(offset_ms):+.2f}")
stats.append(f" Max: {max(offset_ms):+.2f}")
stats.append(f" Avg: {statistics.mean(offset_ms):+.2f}")
stats.append(f" Med: {statistics.median(offset_ms):+.2f}")
if filtered_ms:
stats.append(f"Time differences (filtered, ms):")
stats.append(f" Min: {min(filtered_ms):+.2f}")
stats.append(f" Max: {max(filtered_ms):+.2f}")
stats.append(f" Avg: {statistics.mean(filtered_ms):+.2f}")
stats.append(f" Med: {statistics.median(filtered_ms):+.2f}")
return "\n".join(stats)
class SystemClockAdjuster:
"""Handle system clock adjustments for both Windows and Linux"""
@staticmethod
def can_adjust_clock():
"""Check if we have permission to adjust system clock"""
try:
if platform.system() == "Windows":
return ctypes.windll.shell32.IsUserAnAdmin()
else:
return os.geteuid() == 0
except:
return False
@staticmethod
def adjust_system_clock(offset_seconds):
"""Adjust system clock by offset_seconds"""
try:
if platform.system() == "Windows":
return SystemClockAdjuster._adjust_windows_clock(offset_seconds)
else:
return SystemClockAdjuster._adjust_linux_clock(offset_seconds)
except Exception as e:
print(f" Clock adjustment failed: {e}")
return False
@staticmethod
def _adjust_windows_clock(offset_seconds):
"""Adjust Windows system clock"""
try:
import ctypes
from ctypes import wintypes
# Get current system time
class SYSTEMTIME(ctypes.Structure):
_fields_ = [
('wYear', wintypes.WORD),
('wMonth', wintypes.WORD),
('wDayOfWeek', wintypes.WORD),
('wDay', wintypes.WORD),
('wHour', wintypes.WORD),
('wMinute', wintypes.WORD),
('wSecond', wintypes.WORD),
('wMilliseconds', wintypes.WORD),
]
# Calculate new time
current_time = datetime.now()
new_time = current_time + timedelta(seconds=offset_seconds)
# Set up SYSTEMTIME structure
st = SYSTEMTIME()
st.wYear = new_time.year
st.wMonth = new_time.month
st.wDay = new_time.day
st.wHour = new_time.hour
st.wMinute = new_time.minute
st.wSecond = new_time.second
st.wMilliseconds = new_time.microsecond // 1000
st.wDayOfWeek = new_time.weekday()
# Set system time
result = ctypes.windll.kernel32.SetSystemTime(ctypes.byref(st))
if result:
print(f" Windows clock adjusted by {offset_seconds * 1000:+.1f}ms")
return True
else:
print(f" Windows clock adjustment failed")
return False
except Exception as e:
print(f" Windows clock adjustment error: {e}")
return False
@staticmethod
def _adjust_linux_clock(offset_seconds):
"""Adjust Linux system clock"""
try:
import subprocess
# Calculate new time
current_time = datetime.now()
new_time = current_time + timedelta(seconds=offset_seconds)
# Format for date command
time_string = new_time.strftime("%Y-%m-%d %H:%M:%S")
# Use date command to set system time
result = subprocess.run(['sudo', 'date', '-s', time_string],
capture_output=True, text=True)
if result.returncode == 0:
print(f" Linux clock adjusted by {offset_seconds * 1000:+.1f}ms")
return True
else:
print(f" Linux clock adjustment failed: {result.stderr}")
return False
except Exception as e:
print(f" Linux clock adjustment error: {e}")
return False
class ScreenOverlay:
def __init__(self, parent_app, screenshot, button_type="START"):
self.parent_app = parent_app
self.screenshot = screenshot
self.button_type = button_type
self.selected_position = None
# Create fullscreen overlay window
self.overlay = tk.Toplevel()
emoji = "" if button_type == "START" else ""
self.overlay.title(f"Select {emoji} {button_type} Click Position")
self.overlay.configure(bg="black", cursor="crosshair")
# Make it fullscreen and topmost
self.overlay.attributes('-fullscreen', True)
self.overlay.attributes('-topmost', True)
self.overlay.focus_force()
# Convert screenshot to PhotoImage
self.photo = ImageTk.PhotoImage(screenshot)
# Create label with screenshot
self.screen_label = tk.Label(self.overlay, image=self.photo, cursor="crosshair")
self.screen_label.pack(fill="both", expand=True)
# Instructions overlay with button type
instruction_frame = tk.Frame(self.overlay, bg="yellow", relief="raised", bd=3)
instruction_frame.place(x=20, y=20)
instructions = tk.Label(instruction_frame,
text=f"Click where you want the {emoji} {button_type} button click to happen\nPress ESC to cancel",
font=("Arial", 14, "bold"), bg="yellow", fg="black", padx=10, pady=5)
instructions.pack()
# Bind events
self.screen_label.bind("<Button-1>", self.on_click)
self.overlay.bind("<KeyPress-Escape>", self.cancel)
self.overlay.bind("<KeyPress>", self.on_key)
# Focus for keyboard events
self.overlay.focus_set()
def on_click(self, event):
# Get the actual screen coordinates
self.selected_position = (event.x_root, event.y_root)
# Visual feedback - draw crosshair on screenshot
self.draw_crosshair(event.x, event.y)
# Show confirmation dialog
self.overlay.after(100, self.confirm_selection)
def draw_crosshair(self, x, y):
# Create a copy of screenshot with crosshair
marked_image = self.screenshot.copy()
draw = ImageDraw.Draw(marked_image)
# Choose color based on button type
color = "green" if self.button_type == "START" else "red"
# Draw crosshair
size = 20
thickness = 3
# Colored crosshair
draw.line([x - size, y, x + size, y], fill=color, width=thickness)
draw.line([x, y - size, x, y + size], fill=color, width=thickness)
# White outline for visibility
draw.line([x - size - 1, y - 1, x + size + 1, y - 1], fill="white", width=1)
draw.line([x - size - 1, y + 1, x + size + 1, y + 1], fill="white", width=1)
draw.line([x - 1, y - size - 1, x - 1, y + size + 1], fill="white", width=1)
draw.line([x + 1, y - size - 1, x + 1, y + size + 1], fill="white", width=1)
# Draw circle around point
circle_size = 8
draw.ellipse([x - circle_size, y - circle_size, x + circle_size, y + circle_size],
outline=color, width=2)
draw.ellipse([x - circle_size - 1, y - circle_size - 1, x + circle_size + 1, y + circle_size + 1],
outline="white", width=1)
# Update display
self.photo = ImageTk.PhotoImage(marked_image)
self.screen_label.config(image=self.photo)
def confirm_selection(self):
emoji = "" if self.button_type == "START" else ""
result = messagebox.askyesno("Confirm Position",
f"{emoji} {self.button_type} click position selected: {self.selected_position}\n\n"
f"Use this position for {self.button_type} button clicks?",
parent=self.overlay)
if result:
self.parent_app.set_click_position(self.selected_position, self.button_type)
self.close()
else:
# Reset and allow new selection
self.photo = ImageTk.PhotoImage(self.screenshot)
self.screen_label.config(image=self.photo)
self.selected_position = None
def on_key(self, event):
if event.keysym == "Escape":
self.cancel(event)
def cancel(self, event=None):
self.close()
def close(self):
self.overlay.destroy()
class UDPTriggeredClickTimerWithLogging:
# Replace the __init__ method and create_widgets methods in your click_receiver.py with these compact versions:
def __init__(self, root):
self.root = root
self.root.title("UDP Click Reciever")
self.root.geometry("350x800") # More reasonable size
self.root.configure(bg="#f0f0f0")
self.root.resizable(True, True)
# Set minimum size
self.root.minsize(475, 800)
# Set window icon
self.set_window_icon()
# Initialize variables (keep all existing variables)
self.start_click_position = None
self.stop_click_position = None
self.udp_listening = False
self.udp_socket = None
self.udp_thread = None
self.cancel_event = threading.Event()
# UDP settings
self.udp_port = 9999
self.last_trigger_time = None
self.events_received = 0
# CLOCK SYNC
self.forwarder_ip = "192.168.1.2"
self.sync_manager = ClockSyncManager(is_forwarder=False)
self.sync_thread = None
# SESSION LOGGING
self.current_session = None
self.session_logs = []
self.log_directory = shared_logger.get_camera_log_directory()
# Auto-click state
self.auto_click_enabled = False
# Loop click state
self.loop_enabled = False
self.loop_interval = 15.0 # Default interval in seconds
self.loop_thread = None
self.loop_stop_event = threading.Event()
self.loop_click_position = None
self.loop_click_type = None # START or STOP
self.loop_click_count = 0
# Disable pyautogui failsafe
pyautogui.FAILSAFE = False
# Create scrollable interface
self.create_scrollable_interface()
self.update_displays()
self.ensure_log_directory()
# Start clock sync
self.start_clock_sync()
# Add this for window management
self.diagnostic_windows = [] # Track open diagnostic windows
def create_scrollable_interface(self):
"""Create a scrollable interface with compact layout"""
# Create main canvas and scrollbar
self.main_canvas = tk.Canvas(self.root, bg="#f0f0f0")
self.scrollbar = tk.Scrollbar(self.root, orient="vertical", command=self.main_canvas.yview)
self.scrollable_frame = tk.Frame(self.main_canvas, bg="#f0f0f0")
# Configure scrolling
self.scrollable_frame.bind(
"<Configure>",
lambda e: self.main_canvas.configure(scrollregion=self.main_canvas.bbox("all"))
)
self.main_canvas.create_window((0, 0), window=self.scrollable_frame, anchor="nw")
self.main_canvas.configure(yscrollcommand=self.scrollbar.set)
# Pack canvas and scrollbar
self.main_canvas.pack(side="left", fill="both", expand=True)
self.scrollbar.pack(side="right", fill="y")
# Enable mouse wheel scrolling
def _on_mousewheel(event):
self.main_canvas.yview_scroll(int(-1 * (event.delta / 120)), "units")
self.root.bind("<MouseWheel>", _on_mousewheel) # Windows
self.root.bind("<Button-4>", lambda e: self.main_canvas.yview_scroll(-1, "units")) # Linux
self.root.bind("<Button-5>", lambda e: self.main_canvas.yview_scroll(1, "units")) # Linux
# Create all widgets in the scrollable frame
self.create_compact_widgets()
def create_compact_widgets(self):
"""Create widgets with a more compact layout"""
# Title - more compact
title_label = tk.Label(self.scrollable_frame,
text=" UDP Click Timer with Logging & Sync",
font=("Arial", 12, "bold"), bg="#f0f0f0", fg="#333")
title_label.pack(pady=(5, 2))
# Current time display - smaller
self.current_time_label = tk.Label(self.scrollable_frame, text="",
font=("Arial", 12), bg="#f0f0f0", fg="#666")
self.current_time_label.pack(pady=1)
# Create compact sections
self.create_compact_sync_section()
self.create_compact_udp_section()
self.create_compact_position_section()
self.create_compact_auto_click_section()
self.create_compact_loop_click_section()
self.create_compact_session_section()
self.create_compact_status_section()
def create_compact_sync_section(self):
"""Clean and intuitive clock sync section"""
sync_frame = tk.LabelFrame(self.scrollable_frame, text=" Clock Synchronization",
font=("Arial", 12, "bold"), bg="#f0f0f0",
padx=5, pady=3)
sync_frame.pack(pady=3, padx=10, fill="x")
# Status display
self.sync_status_label = tk.Label(sync_frame, text=" Initializing clock sync...",
bg="#f0f0f0", fg="#FF9800",
font=("Arial", 12), wraplength=350)
self.sync_status_label.pack(pady=2)
# Main action buttons - clearer labels
sync_row1 = tk.Frame(sync_frame, bg="#f0f0f0")
sync_row1.pack(pady=2, fill="x")
tk.Button(sync_row1, text=" Force Sync", command=self.force_sync_update,
bg="#2196F3", fg="white", font=("Arial", 12, "bold"), width=12).pack(side=tk.LEFT, padx=2)
tk.Button(sync_row1, text=" Statistics", command=self.show_sync_statistics,
bg="#4CAF50", fg="white", font=("Arial", 12), width=10).pack(side=tk.LEFT, padx=2)
tk.Button(sync_row1, text=" Diagnostics", command=self.show_advanced_sync_diagnostics,
bg="#FF9800", fg="white", font=("Arial", 12), width=12).pack(side=tk.LEFT, padx=2)
# Second row for advanced features
sync_row2 = tk.Frame(sync_frame, bg="#f0f0f0")
sync_row2.pack(pady=1, fill="x")
tk.Button(sync_row2, text=" Live Monitor", command=self.show_live_sync_monitor,
bg="#9C27B0", fg="white", font=("Arial", 12), width=12).pack(side=tk.LEFT, padx=2)
tk.Button(sync_row2, text=" Triple Sync", command=self.triple_force_sync,
bg="#E91E63", fg="white", font=("Arial", 12), width=12).pack(side=tk.LEFT, padx=2)
tk.Button(sync_row2, text="️ Reset Data", command=self.reset_sync_data,
bg="#795548", fg="white", font=("Arial", 12), width=12).pack(side=tk.LEFT, padx=2)
def create_compact_udp_section(self):
"""Compact UDP section"""
udp_frame = tk.LabelFrame(self.scrollable_frame, text=" UDP Trigger",
font=("Arial", 12, "bold"), bg="#f0f0f0",
padx=5, pady=3)
udp_frame.pack(pady=3, padx=10, fill="x")
# UDP controls in one row
udp_controls = tk.Frame(udp_frame, bg="#f0f0f0")
udp_controls.pack(pady=2, fill="x")
self.udp_button = tk.Button(udp_controls, text=" Start UDP",
command=self.toggle_udp_listening,
bg="#4CAF50", fg="white", font=("Arial", 12, "bold"),
width=16, cursor="hand2")
self.udp_button.pack(side=tk.LEFT, padx=2)
tk.Button(udp_controls, text=" Test", command=self.test_udp_receiver,
bg="#FF9800", fg="white", font=("Arial", 12), width=6).pack(side=tk.LEFT, padx=2)
# Compact status
self.udp_status_label = tk.Label(udp_frame, text=" Not listening",
bg="#f0f0f0", fg="#f44336", font=("Arial", 12))
self.udp_status_label.pack(pady=1)
self.events_label = tk.Label(udp_frame, text="Events: 0",
bg="#f0f0f0", fg="#666", font=("Arial", 12))
self.events_label.pack()
def create_compact_position_section(self):
"""Compact position setup section"""
pos_frame = tk.LabelFrame(self.scrollable_frame, text=" Click Positions",
font=("Arial", 12, "bold"), bg="#f0f0f0",
padx=5, pady=3)
pos_frame.pack(pady=3, padx=10, fill="x")
# START section - horizontal layout
start_section = tk.Frame(pos_frame, bg="#f0f0f0")
start_section.pack(pady=2, fill="x")
tk.Label(start_section, text=" START:", bg="#f0f0f0",
font=("Arial", 12, "bold"), fg="#4CAF50", width=8).pack(side=tk.LEFT)
tk.Button(start_section, text=" Screen",
command=lambda: self.show_screen_overlay("START"),
bg="#4CAF50", fg="white", font=("Arial", 12), width=8).pack(side=tk.LEFT, padx=1)
tk.Button(start_section, text=" Manual",
command=lambda: self.manual_position_entry("START"),
bg="#4CAF50", fg="white", font=("Arial", 12), width=6).pack(side=tk.LEFT, padx=1)
self.start_test_button = tk.Button(start_section, text=" Test",
command=lambda: self.test_click("START"),
bg="#FF9800", fg="white", font=("Arial", 12), width=6,
state="disabled")
self.start_test_button.pack(side=tk.LEFT, padx=1)
# START position display - compact
self.start_position_label = tk.Label(pos_frame, text=" No START position",
bg="#f0f0f0", fg="#f44336", font=("Arial", 12))
self.start_position_label.pack(pady=(0, 2))
# STOP section - horizontal layout
stop_section = tk.Frame(pos_frame, bg="#f0f0f0")
stop_section.pack(pady=2, fill="x")
tk.Label(stop_section, text=" STOP:", bg="#f0f0f0",
font=("Arial", 12, "bold"), fg="#f44336", width=8).pack(side=tk.LEFT)
tk.Button(stop_section, text=" Screen",
command=lambda: self.show_screen_overlay("STOP"),
bg="#f44336", fg="white", font=("Arial", 12), width=8).pack(side=tk.LEFT, padx=1)
tk.Button(stop_section, text=" Manual",
command=lambda: self.manual_position_entry("STOP"),
bg="#f44336", fg="white", font=("Arial", 12), width=6).pack(side=tk.LEFT, padx=1)
self.stop_test_button = tk.Button(stop_section, text=" Test",
command=lambda: self.test_click("STOP"),
bg="#FF9800", fg="white", font=("Arial", 12), width=6,
state="disabled")
self.stop_test_button.pack(side=tk.LEFT, padx=1)
# STOP position display - compact
self.stop_position_label = tk.Label(pos_frame, text=" No STOP position",
bg="#f0f0f0", fg="#f44336", font=("Arial", 12))
self.stop_position_label.pack(pady=(0, 2))
def create_compact_auto_click_section(self):
"""Compact auto-click section"""
auto_frame = tk.LabelFrame(self.scrollable_frame, text=" Auto-Click",
font=("Arial", 12, "bold"), bg="#f0f0f0",
padx=5, pady=3)
auto_frame.pack(pady=3, padx=10, fill="x")
# Mode selection - horizontal
mode_frame = tk.Frame(auto_frame, bg="#f0f0f0")
mode_frame.pack(pady=2, fill="x")
tk.Label(mode_frame, text="Mode:", bg="#f0f0f0", font=("Arial", 12, "bold")).pack(side=tk.LEFT)
self.auto_mode_var = tk.StringVar(value="BOTH")
tk.Radiobutton(mode_frame, text="START", variable=self.auto_mode_var, value="START",
bg="#f0f0f0", font=("Arial", 12)).pack(side=tk.LEFT, padx=5)
tk.Radiobutton(mode_frame, text="STOP", variable=self.auto_mode_var, value="STOP",
bg="#f0f0f0", font=("Arial", 12)).pack(side=tk.LEFT, padx=5)
tk.Radiobutton(mode_frame, text="BOTH", variable=self.auto_mode_var, value="BOTH",
bg="#f0f0f0", font=("Arial", 12)).pack(side=tk.LEFT, padx=5)
# Enable button and status
self.auto_click_button = tk.Button(auto_frame, text=" Enable Auto-Click",
command=self.toggle_auto_click,
bg="#4CAF50", fg="white", font=("Arial", 12, "bold"),
state="disabled")
self.auto_click_button.pack(pady=2, fill="x")
self.auto_status_label = tk.Label(auto_frame, text="Auto-click disabled",
bg="#f0f0f0", fg="#666", font=("Arial", 12))
self.auto_status_label.pack(pady=1)
def create_compact_loop_click_section(self):
"""Loop click section for repeated automated clicks"""
loop_frame = tk.LabelFrame(self.scrollable_frame, text=" Loop Click",
font=("Arial", 12, "bold"), bg="#f0f0f0",
padx=5, pady=3)
loop_frame.pack(pady=3, padx=10, fill="x")
# Click type selection
type_frame = tk.Frame(loop_frame, bg="#f0f0f0")
type_frame.pack(pady=2, fill="x")
tk.Label(type_frame, text="Click Type:", bg="#f0f0f0", font=("Arial", 12, "bold")).pack(side=tk.LEFT)
self.loop_click_type_var = tk.StringVar(value="START")
tk.Radiobutton(type_frame, text="START", variable=self.loop_click_type_var, value="START",
bg="#f0f0f0", font=("Arial", 12)).pack(side=tk.LEFT, padx=5)
tk.Radiobutton(type_frame, text="STOP", variable=self.loop_click_type_var, value="STOP",
bg="#f0f0f0", font=("Arial", 12)).pack(side=tk.LEFT, padx=5)
# Interval input
interval_frame = tk.Frame(loop_frame, bg="#f0f0f0")
interval_frame.pack(pady=2, fill="x")
tk.Label(interval_frame, text="Interval (s):", bg="#f0f0f0", font=("Arial", 12)).pack(side=tk.LEFT)
self.loop_interval_var = tk.StringVar(value="15.0")
self.loop_interval_entry = tk.Entry(interval_frame, textvariable=self.loop_interval_var,
font=("Arial", 12), width=10)
self.loop_interval_entry.pack(side=tk.LEFT, padx=5)
# Control buttons
button_frame = tk.Frame(loop_frame, bg="#f0f0f0")
button_frame.pack(pady=2, fill="x")
self.loop_start_button = tk.Button(button_frame, text=" Start Loop",
command=self.start_loop_click,
bg="#2196F3", fg="white", font=("Arial", 11, "bold"),
state="disabled")
self.loop_start_button.pack(side=tk.LEFT, padx=2, fill="x", expand=True)
self.loop_stop_button = tk.Button(button_frame, text=" Stop Loop",
command=self.stop_loop_click,
bg="#f44336", fg="white", font=("Arial", 11, "bold"),
state="disabled")
self.loop_stop_button.pack(side=tk.LEFT, padx=2, fill="x", expand=True)
# Status label
self.loop_status_label = tk.Label(loop_frame, text="Loop disabled",
bg="#f0f0f0", fg="#666", font=("Arial", 11))
self.loop_status_label.pack(pady=2)