-
Notifications
You must be signed in to change notification settings - Fork 1
/
output_view_ui.py
2420 lines (2151 loc) · 118 KB
/
output_view_ui.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import _tkinter
import glob
import json
import os
import pathlib
import pickle
import threading
import time
import traceback
from tkinter import *
from tkinter import filedialog, messagebox, ttk
from tkinter.ttk import Combobox
import matplotlib.animation as animation
import matplotlib.pyplot as plt
import numpy as np
from tkvideoutils import VideoRecorder, VideoPlayer
from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg)
# Implement the default Matplotlib key bindings.
from matplotlib.figure import Figure
# Custom library imports
from ttkwidgets import TickScale
from pywoodway.treadmill import SplitBelt, find_treadmills
from session_time_fields import SessionTimeFields
from tkinter_utils import build_treeview, clear_treeview, AddWoodwayProtocolStep, AddBleProtocolStep, \
CalibrateVibrotactors, CalibrateWoodway, select_focus, scroll_to, EditEventPopup
from ui_params import treeview_bind_tag_dict, treeview_tags, treeview_bind_tags, crossmark, checkmark
from pytactor import VibrotactorArray, VibrotactorArraySide
from pyempatica.empaticae4 import EmpaticaE4, EmpaticaDataStreams, EmpaticaClient, EmpaticaServerConnectError
class OutputViewPanel:
def __init__(self, caller, parent, x, y, height, width, button_size, ksf,
field_font, header_font, video_import_cb, slider_change_cb, config, session_dir,
thresholds):
self.KEY_VIEW, self.E4_VIEW, self.VIDEO_VIEW, self.WOODWAY_VIEW, self.BLE_VIEW = 0, 1, 2, 3, 4
self.config = config
self.height, self.width = height, width
self.x, self.y, self.button_size = x, y, button_size
self.current_button = 0
self.view_buttons = []
self.view_frames = []
self.time_change_sources = False
self.frame = Frame(parent, width=width, height=height)
self.frame.place(x=x, y=y)
clean_view = Frame(self.frame, width=width,
height=button_size[1], bg='white')
clean_view.place(x=0, y=0)
key_frame = Frame(parent, width=width, height=height)
key_frame.place(x=x, y=y + self.button_size[1])
self.view_frames.append(key_frame)
video_frame = Frame(parent, width=width, height=height)
self.view_frames.append(video_frame)
key_button = Button(self.frame, text="Key Bindings", command=self.switch_key_frame, width=12,
font=field_font)
self.view_buttons.append(key_button)
self.KEY_VIEW = len(self.view_buttons) - 1
self.view_buttons[self.KEY_VIEW].place(x=(len(self.view_buttons) - 1) * button_size[0], y=0,
width=button_size[0], height=button_size[1])
self.view_buttons[self.KEY_VIEW].config(relief=SUNKEN)
self.key_view = KeystrokeDataFields(self.view_frames[self.KEY_VIEW], ksf,
height=self.height - self.button_size[1], width=self.width,
field_font=field_font, header_font=header_font, button_size=button_size,
caller=caller)
if self.config.get_e4():
e4_output_button = Button(self.frame, text="E4 Streams", command=self.switch_e4_frame, width=12,
font=field_font)
self.view_buttons.append(e4_output_button)
self.E4_VIEW = len(self.view_buttons) - 1
self.view_buttons[self.E4_VIEW].place(x=(len(self.view_buttons) - 1) * button_size[0], y=0,
width=button_size[0], height=button_size[1])
self.e4_view = ViewE4(self.view_frames[self.E4_VIEW],
height=self.height - self.button_size[1], width=self.width,
field_font=field_font, header_font=header_font, button_size=button_size,
e4_button=e4_output_button)
e4_frame = Frame(parent, width=width, height=height)
self.view_frames.append(e4_frame)
else:
self.e4_view = None
if self.config.get_ble():
self.time_change_sources = False
ble_output_button = Button(self.frame, text="BLE Input", command=self.switch_ble_frame, width=12,
font=field_font)
self.view_buttons.append(ble_output_button)
self.BLE_VIEW = len(self.view_buttons) - 1
self.view_buttons[self.BLE_VIEW].place(x=(len(self.view_buttons) - 1) * button_size[0], y=0,
width=button_size[0], height=button_size[1])
self.ble_view = ViewBLE(self.view_frames[self.BLE_VIEW],
height=self.height - self.button_size[1], width=self.width,
field_font=field_font, header_font=header_font, button_size=button_size,
session_dir=session_dir, ble_thresh=thresholds[0:2],
ble_button=ble_output_button,
config=config, caller=caller)
ble_frame = Frame(parent, width=width, height=height)
self.view_frames.append(ble_frame)
else:
self.ble_view = None
if self.config.get_woodway():
self.time_change_sources = False
woodway_output_button = Button(self.frame, text="Woodway", command=self.switch_woodway_frame, width=12,
font=field_font)
self.view_buttons.append(woodway_output_button)
self.WOODWAY_VIEW = len(self.view_buttons) - 1
self.view_buttons[self.WOODWAY_VIEW].place(x=(len(self.view_buttons) - 1) * button_size[0], y=0,
width=button_size[0], height=button_size[1])
self.woodway_view = ViewWoodway(self.view_frames[self.WOODWAY_VIEW],
height=self.height - self.button_size[1], width=self.width,
field_font=field_font, header_font=header_font, button_size=button_size,
config=config, session_dir=session_dir, woodway_thresh=thresholds[2],
woodway_button=woodway_output_button, caller=caller)
woodway_frame = Frame(parent, width=width, height=height)
self.view_frames.append(woodway_frame)
else:
self.woodway_view = None
video_button = Button(self.frame, text="Video View", command=self.switch_video_frame, width=12,
font=field_font)
self.view_buttons.append(video_button)
self.VIDEO_VIEW = len(self.view_buttons) - 1
self.view_buttons[self.VIDEO_VIEW].place(x=(len(self.view_buttons) - 1) * button_size[0], y=0,
width=button_size[0], height=button_size[1])
self.video_view = ViewVideo(caller, self.view_frames[self.VIDEO_VIEW],
height=self.height - self.button_size[1], width=self.width,
field_font=field_font, header_font=header_font, button_size=button_size,
video_import_cb=video_import_cb, slider_change_cb=slider_change_cb,
fps=self.config.get_fps(), kdf=self.key_view, video_button=video_button)
self.event_history = []
def switch_key_frame(self):
self.switch_frame(self.KEY_VIEW)
def switch_ble_frame(self):
self.switch_frame(self.BLE_VIEW)
def switch_woodway_frame(self):
self.switch_frame(self.WOODWAY_VIEW)
def switch_e4_frame(self):
self.switch_frame(self.E4_VIEW)
def switch_video_frame(self):
self.switch_frame(self.VIDEO_VIEW)
def switch_frame(self, view):
"""
https://stackoverflow.com/a/23354009
:param view:
:return:
"""
self.view_buttons[self.current_button].config(relief=RAISED)
self.view_frames[self.current_button].place_forget()
self.current_button = view
self.view_buttons[view].config(relief=SUNKEN)
self.view_frames[view].place(x=self.x, y=self.y + self.button_size[1])
def close(self):
if self.e4_view:
self.e4_view.stop_plot()
self.e4_view.disconnect_e4()
if self.video_view:
if self.video_view.player:
self.video_view.player.loading = False
if self.video_view.recorder:
self.video_view.recorder.stop_recording()
self.video_view.recorder.stop_playback()
if self.ble_view:
self.ble_view.disconnect_ble()
if self.woodway_view:
self.woodway_view.disconnect_woodway()
def start_session(self, recording_path=None):
if self.e4_view:
self.e4_view.start_session()
if self.video_view.recorder:
self.recording_path = recording_path
audio_path = os.path.join(pathlib.Path(recording_path).parent, pathlib.Path(recording_path).stem + ".wav")
self.video_view.recorder.start_recording(video_output=recording_path, audio_output=audio_path)
if self.ble_view:
self.ble_view.start_session()
if self.woodway_view:
self.woodway_view.start_session()
if self.video_view:
self.video_view.clear_event_treeview()
if self.key_view:
self.key_view.clear_sh_treeview()
def enable_video_slider(self):
if self.video_view.player:
self.video_view.video_slider.config(state='active')
def disable_video_slider(self):
if self.video_view.player:
self.video_view.video_slider.config(state='disabled')
def stop_session(self, final_time):
if self.key_view:
self.check_duration_keys(final_time)
if self.e4_view:
self.e4_view.session_started = False
self.e4_view.streaming = False
if self.video_view.recorder:
self.video_view.recorder.stop_recording()
self.video_view.recorder.stop_playback()
self.video_view.recorder.merge_sources(output=self.recording_path,
ffmpeg_path=os.environ['IMAGEIO_FFMPEG_EXE'])
if self.woodway_view:
self.woodway_view.stop_session()
if self.ble_view:
self.ble_view.stop_session()
def check_event(self, key_char, start_time):
# Make sure it is not None
if key_char:
current_frame = None
current_audio_frame = None
# Get the current frame of the video if it's playing
if self.video_view.player:
current_frame = self.video_view.player.current_frame
if self.video_view.player.audio_loaded:
current_audio_frame = self.video_view.player.audio_index
elif self.video_view.recorder:
current_frame = self.video_view.recorder.current_frame
current_window = None
# Add the frame and key to the latest E4 window reading if streaming
if self.e4_view:
if self.e4_view.e4:
current_window = EmpaticaE4.get_unix_timestamp()
# Get the appropriate key event
key_events = self.key_view.check_key(key_char, start_time, current_frame, current_window,
current_audio_frame)
# Add to session history
if key_events:
self.key_view.add_session_event(key_events)
self.video_view.add_event(key_events)
else:
print("INFO: No key events returned")
def check_duration_keys(self, final_time):
for i in range(0, len(self.key_view.dur_bindings)):
if self.key_view.dur_sticky[i]:
self.check_event(self.key_view.dur_bindings[i][0], final_time)
def edit_last_event(self):
self.delete_last_event()
self.key_view.editing = True
self.video_view.editing = True
def delete_last_event(self):
self.key_view.delete_last_event()
self.video_view.delete_last_event()
def undo_last_delete(self):
self.key_view.undo_last_delete()
self.video_view.undo_last_delete()
def get_session_data(self):
video_data = None
if self.video_view:
video_data = self.video_view.video_file
e4_data = None
if self.e4_view:
if self.e4_view.e4:
e4_data = [
self.e4_view.e4.acc_3d,
self.e4_view.e4.acc_x,
self.e4_view.e4.acc_y,
self.e4_view.e4.acc_z,
self.e4_view.e4.acc_timestamps,
self.e4_view.e4.bvp, self.e4_view.e4.bvp_timestamps,
self.e4_view.e4.gsr, self.e4_view.e4.gsr_timestamps,
self.e4_view.e4.tmp, self.e4_view.e4.tmp_timestamps,
self.e4_view.e4.tag, self.e4_view.e4.tag_timestamps,
self.e4_view.e4.ibi, self.e4_view.e4.ibi_timestamps,
self.e4_view.e4.bat, self.e4_view.e4.bat_timestamps,
self.e4_view.e4.hr, self.e4_view.e4.hr_timestamps
]
ble_prot = None
if self.ble_view:
if self.ble_view.protocol_steps:
ble_prot = self.ble_view.protocol_steps
woodway_prot = None
if self.woodway_view:
if self.woodway_view.protocol_steps:
woodway_prot = self.woodway_view.protocol_steps
return self.key_view.event_history, e4_data, video_data, ble_prot, woodway_prot
def save_session(self, filename, keystrokes):
if self.e4_view:
if self.e4_view.windowed_readings:
try:
for keystroke in keystrokes:
try:
if type(keystroke[1]) is tuple:
self.e4_view.windowed_readings[int(keystroke[1][0]) - 1][-1].append(keystroke[0])
self.e4_view.windowed_readings[int(keystroke[1][1]) - 1][-1].append(keystroke[0])
else:
self.e4_view.windowed_readings[int(keystroke[1]) - 1][-1].append(keystroke[0])
except Exception as e:
print(f"ERROR: Exception encountered:\n{str(e)}\n" + traceback.print_exc())
with open(filename, 'wb') as f:
pickle.dump(self.e4_view.windowed_readings, f)
except TypeError as e:
with open(filename, 'wb') as f:
pickle.dump(self.e4_view.windowed_readings, f)
print(f"ERROR: Exception encountered:\n{str(e)}\n" + traceback.print_exc())
class ViewWoodway:
def __init__(self, parent, height, width, field_font, header_font, button_size, config, session_dir,
woodway_button, caller, woodway_thresh=None):
self.woodway = None
self.caller = caller
self.tab_button = woodway_button
self.session_dir = session_dir
self.config = config
self.root = parent
self.protocol_steps = []
self.selected_step = 0
self.load_protocol_thread = None
self.prot_file = None
self.step_time = 0
self.step_duration = 0
self.woodway_speed_r, self.woodway_speed_l = 0, 0
self.woodway_incline = 0
self.session_started = False
self.changed_protocol = True
self.__connected = False
self.paused = False
if woodway_thresh:
self.calibrated = True
self.woodway_thresh = woodway_thresh
print(f"INFO: Woodway calibrated already - Thresh: {self.woodway_thresh} Calibrated: {self.calibrated}")
else:
self.calibrated = False
self.woodway_thresh = None
print("INFO: Woodway is not calibrated!")
# region EXPERIMENTAL PROTOCOL
element_height_adj = 100
self.exp_prot_label = Label(parent, text="Experimental Protocol", font=header_font, anchor=CENTER)
self.exp_prot_label.place(x=int(width * 0.23) + 18, y=10, anchor=N)
self.prot_treeview_parents = []
prot_heading_dict = {"#0": ["Duration", 'w', 20, YES, 'w']}
prot_column_dict = {"1": ["LS", 'c', 1, YES, 'c'],
"2": ["RS", 'c', 1, YES, 'c'],
"3": ["Incline", 'c', 1, YES, 'c'],
"4": ["F", 'c', 50, NO, 'c'],
"5": ["D", 'c', 50, NO, 'c']}
treeview_offset = int(width * 0.03)
# TODO: When the session is paused the woodway and vibrotactors should stop, equalize speeds first??
self.prot_treeview, self.prot_filescroll = build_treeview(parent, x=treeview_offset, y=40,
height=height - element_height_adj - 40,
heading_dict=prot_heading_dict,
column_dict=prot_column_dict,
width=(int(width * 0.5) - int(width * 0.05)),
button_1_bind=self.select_protocol_step,
double_bind=self.__edit_protocol_step,
button_3_bind=self.__delete_protocol_step)
self.prot_add_button = Button(parent, text="Add", font=field_font, command=self.__add_protocol_step)
self.prot_add_button.place(x=(treeview_offset + ((int(width * 0.5) - int(width * 0.05)) * 0.25)),
y=(height - element_height_adj),
anchor=N,
width=(int(width * 0.5) - int(width * 0.05)) / 2, height=button_size[1])
self.woodway_connect_button = Button(parent, text="Connect", font=field_font,
command=self.__connect_to_woodway, bg='#4abb5f')
self.woodway_connect_button.place(x=(treeview_offset + ((int(width * 0.5) - int(width * 0.05)) * 0.25)),
y=(height - element_height_adj) + button_size[1] * 2,
anchor=N,
width=(int(width * 0.5) - int(width * 0.05)) / 2, height=button_size[1])
self.prot_load_button = Button(parent, text="Load File", font=field_font,
command=self.__load_protocol_from_file)
self.prot_load_button.place(x=(treeview_offset + ((int(width * 0.5) - int(width * 0.05)) * 0.25)),
y=(height - element_height_adj) + button_size[1],
anchor=N,
width=(int(width * 0.5) - int(width * 0.05)) / 2, height=button_size[1])
self.prot_save_button = Button(parent, text="Save To File", font=field_font,
command=self.__save_protocol_to_file)
self.prot_save_button.place(x=(treeview_offset + ((int(width * 0.5) - int(width * 0.05)) * 0.75)),
y=(height - element_height_adj) + button_size[1],
anchor=N,
width=(int(width * 0.5) - int(width * 0.05)) / 2, height=button_size[1])
self.prot_save_button['state'] = 'disabled'
self.prot_del_button = Button(parent, text="Delete", font=field_font,
command=self.__delete_protocol_step)
self.prot_del_button.place(x=(treeview_offset + ((int(width * 0.5) - int(width * 0.05)) * 0.75)),
y=(height - element_height_adj),
anchor=N,
width=(int(width * 0.5) - int(width * 0.05)) / 2, height=button_size[1])
self.woodway_disconnect_button = Button(parent, text="Disconnect", font=field_font,
command=self.disconnect_woodway, bg='red')
self.woodway_disconnect_button.place(x=(treeview_offset + ((int(width * 0.5) - int(width * 0.05)) * 0.75)),
y=(height - element_height_adj) + button_size[1] * 2,
anchor=N,
width=(int(width * 0.5) - int(width * 0.05)) / 2, height=button_size[1])
# endregion
# region BELT CONTROL
# Vertical sliders speed and inclination for each treadmill
slider_height_adj = element_height_adj
self.belt_speed_label = Label(parent, text="Belt Speeds", font=header_font, anchor=CENTER)
self.belt_speed_label.place(x=int(width * 0.625), y=10, anchor=N)
self.belt_speed_l_label = Label(parent, text='Left', font=field_font, anchor=CENTER)
self.belt_speed_l_label.place(x=int(width * 0.575), y=40, anchor=N)
self.belt_speed_r_label = Label(parent, text='Right', font=field_font, anchor=CENTER)
self.belt_speed_r_label.place(x=int(width * 0.675), y=40, anchor=N)
self.belt_speed_l_var = StringVar(parent)
self.belt_speed_l = Scale(parent, orient="vertical", variable=self.belt_speed_l_var, showvalue=False,
command=self.__write_l_speed, length=int(height * 0.7), from_=29.9, to=-29.9,
digits=3, resolution=0.1)
self.belt_speed_l.place(x=int(width * 0.575), y=70, anchor=N)
self.belt_speed_l_value = Label(parent, text="0 MPH", anchor=CENTER, font=field_font)
self.belt_speed_l_value.place(x=int(width * 0.575), y=80 + int(height * 0.7), anchor=N)
self.belt_speed_r_var = StringVar(parent)
self.belt_speed_r = Scale(parent, orient="vertical", variable=self.belt_speed_r_var, showvalue=False,
command=self.__write_r_speed, length=int(height * 0.7), from_=29.9, to=-29.9,
digits=3, resolution=0.1)
self.belt_speed_r.place(x=int(width * 0.675), y=70, anchor=N)
self.belt_speed_r_value = Label(parent, text="0 MPH", anchor=CENTER, font=field_font)
self.belt_speed_r_value.place(x=int(width * 0.675), y=80 + int(height * 0.7), anchor=N)
# This section gets 25% of the panel
self.belt_incline_label = Label(parent, text="Belt Incline", font=header_font, anchor=CENTER)
self.belt_incline_label.place(x=int(width * 0.875), y=10, anchor=N)
self.belt_incline_l_var = StringVar(parent)
self.belt_incline_l = Scale(parent, orient="vertical", variable=self.belt_incline_l_var, showvalue=False,
command=self.__write_incline, length=int(height * 0.7), from_=29.9, to=0,
digits=3, resolution=0.1)
self.belt_incline_l.place(x=int(width * 0.875), y=70, anchor=N)
self.belt_incline_l_value = Label(parent, text="0\u00b0", anchor=CENTER, font=field_font)
self.belt_incline_l_value.place(x=int(width * 0.875), y=80 + int(height * 0.7), anchor=N)
self.calibrate_button = Button(parent, text='Calibrate Woodway Threshold', font=field_font,
command=self.__calibrate_woodway)
self.calibrate_button.place(x=int(width * 0.75), y=(height - element_height_adj) + button_size[1] * 2,
anchor=N,
width=int(width * 0.45), height=button_size[1])
self.__disable_ui_elements()
# endregion
self.woodway_dir = os.path.join(self.session_dir, "Woodway")
if os.path.exists(self.woodway_dir):
try:
latest_protocol = max(pathlib.Path(self.woodway_dir).glob("*.json"), key=lambda f: f.stat().st_ctime)
self.__load_protocol_from_file(latest_protocol)
except ValueError:
print("WARNING: Protocol folder exists with no protocols!")
def disable_ui_elements(self):
self.__disable_ui_elements()
# self.prot_add_button.config(state='disabled')
# self.prot_del_button.config(state='disabled')
# self.prot_save_button.config(state='disabled')
# self.prot_load_button.config(state='disabled')
self.calibrate_button.config(state='disabled')
def __enable_connect_button(self):
self.woodway_connect_button.config(state='active')
def __disable_ui_elements(self):
self.belt_incline_l.config(state='disabled')
self.belt_speed_l.config(state='disabled')
self.belt_speed_r.config(state='disabled')
self.woodway_disconnect_button.config(state='disabled')
def __enable_ui_elements(self):
self.belt_incline_l.config(state='active')
self.belt_speed_l.config(state='active')
self.belt_speed_r.config(state='active')
self.woodway_disconnect_button.config(state='active')
self.woodway_connect_button.config(state='disabled')
def get_calibration_thresholds(self):
if not self.is_calibrated():
raise ValueError("Woodway are not calibrated!")
else:
self.woodway_speed_l, self.woodway_speed_r = self.woodway_thresh, self.woodway_thresh
return self.woodway_thresh
def start_session(self):
self.session_started = True
self.woodway.belt_a.set_speed(self.woodway_speed_l)
self.woodway.belt_b.set_speed(self.woodway_speed_r)
self.__save_protocol_to_file()
def stop_session(self):
if self.woodway:
self.session_started = False
self.disconnect_woodway()
def next_protocol_step(self, current_time):
if self.selected_step >= len(self.protocol_steps):
return
if current_time == 1:
self.selected_step = 0
self.__update_woodway_protocol()
if (self.step_time - current_time) == 0:
self.selected_step += 1
self.__update_woodway_protocol()
def pause_woodway(self):
if self.session_started:
self.belt_speed_l.set(0.0)
self.belt_speed_r.set(0.0)
if self.woodway:
self.belt_speed_l_value.config(text=f"{float(0.0):.1f} MPH")
self.belt_speed_r_value.config(text=f"{float(0.0):.1f} MPH")
self.woodway.set_speed(0.0, 0.0)
self.__write_incline(0.0)
self.paused = True
def start_woodway(self):
self.paused = False
self.__update_woodway()
def __update_woodway_protocol(self):
if self.selected_step >= len(self.protocol_steps):
self.woodway_speed_l = 0.0
self.woodway_speed_r = 0.0
self.woodway_incline = 0.0
self.__update_woodway()
return
self.selected_command = self.protocol_steps[self.selected_step]
self.step_duration = self.selected_command[0]
self.step_time += self.step_duration
self.woodway_speed_l = self.woodway_thresh + self.selected_command[1]
self.woodway_speed_r = self.woodway_thresh + self.selected_command[2]
self.woodway_incline += self.selected_command[3]
self.__update_woodway()
select_focus(self.prot_treeview, self.prot_treeview_parents[self.selected_step])
scroll_to(self.prot_treeview, self.selected_step)
if self.config.get_protocol_beep():
SessionTimeFields.beep()
if self.selected_command[4] != '':
self.caller.handle_key_press(self.selected_command[4])
if self.selected_command[5] != '':
self.caller.handle_key_press(self.selected_command[5])
def __update_woodway(self):
self.__write_incline(self.woodway_incline)
self.__write_speed()
def is_connected(self):
return self.__connected
def is_calibrated(self):
return self.calibrated
def calibrate_return(self, woodway_threshold):
self.calibrated = True
self.woodway_thresh = woodway_threshold
def __calibrate_woodway(self):
if self.woodway:
if self.woodway.is_connected():
CalibrateWoodway(self, self.root, self.woodway)
else:
messagebox.showerror("Error",
"Something went wrong connecting to the Woodway!\nCannot be calibrated!")
self.tab_button['text'] = 'Woodway' + crossmark
else:
messagebox.showerror("Error", "Connect to Woodway first!\nCannot be calibrated!")
self.tab_button['text'] = 'Woodway' + crossmark
def select_protocol_step(self, event):
selection = self.prot_treeview.identify_row(event.y)
if selection:
self.selected_step = int(selection)
def populate_protocol_steps(self):
if self.protocol_steps:
for i in range(0, len(self.protocol_steps)):
self.prot_treeview_parents.append(
self.prot_treeview.insert("", 'end', str(i + 1), text=str(self.protocol_steps[i][0]),
values=(self.protocol_steps[i][1], self.protocol_steps[i][2],
self.protocol_steps[i][3], self.protocol_steps[i][4],
self.protocol_steps[i][5]),
tags=(treeview_tags[(i + 1) % 2])))
def __heal_legacy_protocol(self):
for step in self.protocol_steps:
if len(step) == 4:
step.extend(['', ''])
with open(self.prot_file, 'w') as f:
x = {"Steps": self.protocol_steps}
json.dump(x, f)
def __load_protocol_from_file(self, selected_file=None):
try:
if selected_file:
self.selected_step = 0
self.prot_file = selected_file
with open(self.prot_file, 'r') as f:
self.protocol_steps = json.load(f)['Steps']
if len(self.protocol_steps[0]) == 4:
self.__heal_legacy_protocol()
self.repopulate_treeview()
else:
selected_file = filedialog.askopenfilename(filetypes=(("JSON Files", "*.json"),))
if selected_file:
self.selected_step = 0
self.prot_file = selected_file
with open(self.prot_file, 'r') as f:
self.protocol_steps = json.load(f)['Steps']
if len(self.protocol_steps[0]) == 4:
self.__heal_legacy_protocol()
self.repopulate_treeview()
self.changed_protocol = True
self.prot_save_button['state'] = 'active'
else:
messagebox.showwarning("Warning", "No file selected, please try again!")
self.tab_button['text'] = 'Woodway' + checkmark
except Exception as ex:
messagebox.showerror("Exception Encountered", f"Error encountered when loading protocol file!\n{str(ex)}")
self.tab_button['text'] = 'Woodway' + crossmark
def __save_protocol_to_file(self):
try:
if self.changed_protocol:
if self.prot_file:
file_dir = os.path.join(self.session_dir, "Woodway")
if not os.path.exists(file_dir):
os.mkdir(file_dir)
if pathlib.Path(self.prot_file).parent != file_dir:
self.prot_file = os.path.join(file_dir, pathlib.Path(self.prot_file).name)
file_count = len(glob.glob1(file_dir, "*.json"))
if file_count > 0:
new_file = os.path.join(pathlib.Path(self.prot_file).parent,
'_'.join(pathlib.Path(self.prot_file).stem.split('_')[
:-1]) + f"_V{file_count}.json")
else:
new_file = os.path.join(pathlib.Path(self.prot_file).parent,
pathlib.Path(self.prot_file).stem + f"_V{file_count}.json")
with open(new_file, 'w') as f:
x = {"Steps": self.protocol_steps}
json.dump(x, f)
self.__load_protocol_from_file(selected_file=new_file)
self.changed_protocol = False
self.prot_save_button['state'] = 'disabled'
else:
file_dir = os.path.join(self.session_dir, "Woodway")
if not os.path.exists(file_dir):
os.mkdir(file_dir)
new_file = os.path.join(file_dir, "woodway_protocol.json")
if new_file:
self.prot_file = new_file
with open(self.prot_file, 'w') as f:
x = {"Steps": self.protocol_steps}
json.dump(x, f)
self.changed_protocol = False
self.prot_save_button['state'] = 'disabled'
else:
messagebox.showwarning("Warning", "No filename supplied! Can't save, please try again!")
except Exception as ex:
messagebox.showerror("Exception Encountered", f"Error encountered when saving protocol file!\n{str(ex)}")
def popup_return(self, new_step, edit=False):
if edit:
if self.selected_step:
self.protocol_steps[int(self.selected_step) - 1] = new_step
self.repopulate_treeview()
else:
self.protocol_steps.append(new_step)
self.repopulate_treeview()
self.changed_protocol = True
self.prot_save_button['state'] = 'active'
def repopulate_treeview(self):
clear_treeview(self.prot_treeview)
self.prot_treeview_parents = []
self.populate_protocol_steps()
def __edit_protocol_step(self, event):
if self.selected_step:
step = self.protocol_steps[int(self.selected_step) - 1]
AddWoodwayProtocolStep(self, self.root, edit=True, dur=step[0], ls=step[1], rs=step[2], incl=step[3],
freq_key=step[4], dur_key=step[5])
def __add_protocol_step(self):
AddWoodwayProtocolStep(self, self.root)
def __delete_protocol_step(self, event=None):
if self.selected_step:
self.protocol_steps.pop(self.selected_step - 1)
self.repopulate_treeview()
self.changed_protocol = True
self.prot_save_button['state'] = 'active'
def __connect_to_woodway(self):
try:
a_port, b_port = find_treadmills(a_sn=self.config.get_woodway_a(), b_sn=self.config.get_woodway_b())
if a_port and b_port:
self.woodway = SplitBelt(b_port.name, a_port.name)
self.woodway.start_belts(True, False, True, False)
self.__enable_ui_elements()
self.__connected = True
messagebox.showinfo("Success!", "Woodway Split Belt treadmill connected!")
self.tab_button['text'] = 'Woodway' + checkmark
else:
messagebox.showerror("Error", "No treadmills found! Check serial numbers and connections!")
self.tab_button['text'] = 'Woodway' + crossmark
except Exception as ex:
messagebox.showerror("Exception Encountered",
f"Encountered exception when connecting to Woodway!\n{str(ex)}")
self.tab_button['text'] = 'Woodway' + crossmark
def disconnect_woodway(self):
if self.woodway:
self.woodway.stop_belts()
self.woodway.set_elevations(float(0.0))
self.woodway.close()
self.woodway = None
self.__disable_ui_elements()
self.__enable_connect_button()
self.__connected = False
self.tab_button['text'] = 'Woodway'
def __write_speed(self):
if self.session_started:
self.belt_speed_l.set(self.woodway_speed_l)
self.belt_speed_r.set(self.woodway_speed_r)
if self.woodway:
self.belt_speed_l_value.config(text=f"{float(self.woodway_speed_l):.1f} MPH")
self.belt_speed_r_value.config(text=f"{float(self.woodway_speed_r):.1f} MPH")
self.woodway.set_speed(self.woodway_speed_l, self.woodway_speed_r)
def __write_l_speed(self, speed):
if self.session_started:
self.belt_speed_l.set(float(speed))
if self.woodway:
self.belt_speed_l_value.config(text=f"{float(speed):.1f} MPH")
self.woodway.belt_a.set_speed(float(speed))
def __write_r_speed(self, speed):
if self.session_started:
self.belt_speed_r.set(float(speed))
if self.woodway:
self.belt_speed_r_value.config(text=f"{float(speed):.1f} MPH")
self.woodway.belt_b.set_speed(float(speed))
def __write_incline(self, incline):
if self.session_started:
self.belt_incline_l.set(float(incline))
if self.woodway:
self.belt_incline_l_value.config(text=f"{float(incline):.1f}\u00b0")
self.woodway.set_elevations(float(incline))
class ViewBLE:
def __init__(self, parent, height, width, field_font, header_font, button_size,
session_dir, ble_button, config, caller, ble_thresh=None):
self.root = parent
self.caller = caller
self.config = config
self.tab_button = ble_button
self.session_dir = session_dir
self.ble_instance = VibrotactorArray.get_ble_instance()
self.left_vta, self.right_vta = None, None
self.ble_connect_thread = None
self.protocol_steps = []
self.selected_step = 0
self.prot_file = None
self.step_duration = 0
self.step_time = 0
self.session_started = False
self.changed_protocol = True
self.__connected = False
self.paused = False
self.r_ble_1_3_value, self.r_ble_4_6_value, self.r_ble_7_9_value, self.r_ble_10_12_value = 0, 0, 0, 0
self.l_ble_1_3_value, self.l_ble_4_6_value, self.l_ble_7_9_value, self.l_ble_10_12_value = 0, 0, 0, 0
if ble_thresh[0] and ble_thresh[1]:
self.calibrated = True
self.right_ble_thresh = ble_thresh[0]
self.left_ble_thresh = ble_thresh[1]
print(
f"INFO: Vibrotactors already calibrated - Right: {self.right_ble_thresh} Left: {self.left_ble_thresh} "
f"Calibrated: {self.calibrated}")
else:
self.calibrated = False
self.right_ble_thresh = None
self.left_ble_thresh = None
print("INFO: Vibrotactors not calibrated!")
# region EXPERIMENTAL PROTOCOL
element_height_adj = 100
self.exp_prot_label = Label(parent, text="Experimental Protocol", font=header_font, anchor=CENTER)
self.exp_prot_label.place(x=int(width * 0.23) + 18, y=10, anchor=N)
self.prot_treeview_parents = []
prot_heading_dict = {"#0": ["Duration", 'w', 20, YES, 'w']}
prot_column_dict = {"1": ["Left", 'c', 1, YES, 'c'],
"2": ["Right", 'c', 1, YES, 'c'],
"3": ["F", 'c', 50, NO, 'c'],
"4": ["D", 'c', 50, NO, 'c']}
treeview_offset = int(width * 0.03)
self.prot_treeview, self.prot_filescroll = build_treeview(parent, x=treeview_offset, y=40,
height=height - element_height_adj - 40,
heading_dict=prot_heading_dict,
column_dict=prot_column_dict,
width=(int(width * 0.5) - int(width * 0.05)),
button_1_bind=self.select_protocol_step,
double_bind=self.__edit_protocol_step,
button_3_bind=self.__delete_protocol_step)
self.prot_add_button = Button(parent, text="Add", font=field_font, command=self.__add_protocol_step)
self.prot_add_button.place(x=(treeview_offset + ((int(width * 0.5) - int(width * 0.05)) * 0.25)),
y=(height - element_height_adj),
anchor=N,
width=(int(width * 0.5) - int(width * 0.05)) / 2, height=button_size[1])
self.ble_connect_button = Button(parent, text="Connect", font=field_font,
command=self.__connect_to_ble, bg='#4abb5f')
self.ble_connect_button.place(x=(treeview_offset + ((int(width * 0.5) - int(width * 0.05)) * 0.25)),
y=(height - element_height_adj) + button_size[1] * 2,
anchor=N,
width=(int(width * 0.5) - int(width * 0.05)) / 2, height=button_size[1])
self.prot_load_button = Button(parent, text="Load File", font=field_font,
command=self.__load_protocol_from_file)
self.prot_load_button.place(x=(treeview_offset + ((int(width * 0.5) - int(width * 0.05)) * 0.25)),
y=(height - element_height_adj) + button_size[1],
anchor=N,
width=(int(width * 0.5) - int(width * 0.05)) / 2, height=button_size[1])
self.prot_save_button = Button(parent, text="Save To File", font=field_font,
command=self.__save_protocol_to_file)
self.prot_save_button.place(x=(treeview_offset + ((int(width * 0.5) - int(width * 0.05)) * 0.75)),
y=(height - element_height_adj) + button_size[1],
anchor=N,
width=(int(width * 0.5) - int(width * 0.05)) / 2, height=button_size[1])
self.prot_save_button['state'] = 'disabled'
self.prot_del_button = Button(parent, text="Delete", font=field_font,
command=self.__delete_protocol_step)
self.prot_del_button.place(x=(treeview_offset + ((int(width * 0.5) - int(width * 0.05)) * 0.75)),
y=(height - element_height_adj),
anchor=N,
width=(int(width * 0.5) - int(width * 0.05)) / 2, height=button_size[1])
self.ble_disconnect_button = Button(parent, text="Disconnect", font=field_font,
command=self.disconnect_ble, bg='red')
self.ble_disconnect_button.place(x=(treeview_offset + ((int(width * 0.5) - int(width * 0.05)) * 0.75)),
y=(height - element_height_adj) + button_size[1] * 2,
anchor=N,
width=(int(width * 0.5) - int(width * 0.05)) / 2, height=button_size[1])
# endregion
# region VIBROTACTOR SLIDERS
slider_vars = [
(self.update_ble_1, IntVar(parent)),
(self.update_ble_2, IntVar(parent)),
(self.update_ble_3, IntVar(parent)),
(self.update_ble_4, IntVar(parent)),
(self.update_ble_5, IntVar(parent)),
(self.update_ble_6, IntVar(parent)),
(self.update_ble_7, IntVar(parent)),
(self.update_ble_8, IntVar(parent)),
(self.update_ble_9, IntVar(parent)),
(self.update_ble_10, IntVar(parent)),
(self.update_ble_11, IntVar(parent)),
(self.update_ble_12, IntVar(parent)),
(self.update_frequency, IntVar(parent))
]
self.slider_objects = []
slider_separation = int((width * 0.4) / 6)
slider_separation_h = 40
slider_count = 0
label = Label(parent, text="Vibrotactor Control", font=header_font, anchor=N)
label.place(x=int(width * 0.60) - slider_separation + int(slider_separation * 3), y=10, anchor=N)
for i in range(0, 12):
if i == 6:
slider_count = 0
slider_separation_h += int(height * 0.4)
label = Label(parent, text=f"{i + 1}", font=field_font, anchor=N, width=4)
label.place(x=int(width * 0.6) + int(slider_count * slider_separation), y=slider_separation_h, anchor=N)
temp_slider = Scale(parent, orient="vertical", variable=slider_vars[i][1], showvalue=False,
command=slider_vars[i][0], length=int(height * 0.35), from_=255, to=0)
temp_slider.place(x=int(width * 0.6) + int(slider_count * slider_separation), y=slider_separation_h + 25,
anchor=N)
self.slider_objects.append(temp_slider)
slider_count += 1
slider_separation_h = 40
label = Label(parent, text="Freq", font=field_font, anchor=CENTER, width=6)
label.place(x=int(width * 0.60) - slider_separation, y=slider_separation_h, anchor=N)
self.freq_slider = Scale(parent, orient="vertical", variable=slider_vars[12][1], showvalue=False,
command=slider_vars[12][0], length=int(height * 0.75), from_=7, to=0)
self.freq_slider.place(x=int(width * 0.60) - slider_separation, y=slider_separation_h + 25, anchor=N)
self.calibrate_button = Button(parent, text='Calibrate Vibrotactor Threshold', font=field_font,
command=self.__calibrate_ble)
self.calibrate_button.place(x=int(width * 0.75), y=(height - element_height_adj) + button_size[1] * 2,
anchor=N,
width=int(width * 0.45), height=button_size[1])
self.__disable_ui_elements()
self.ble_dir = os.path.join(self.session_dir, "BLE")
if os.path.exists(self.ble_dir):
try:
latest_protocol = max(pathlib.Path(self.ble_dir).glob("*.json"), key=lambda f: f.stat().st_ctime)
self.__load_protocol_from_file(latest_protocol)
except ValueError:
print("WARNING: Protocol folder exists with no protocols!")
# endregion
def __enable_ui_elements(self):
self.ble_connect_button.config(state='disabled')
self.ble_disconnect_button.config(state='active')
self.freq_slider.config(state='active')
for slider in self.slider_objects:
slider.config(state='active')
def disable_ui_elements(self):
for slider in self.slider_objects:
slider.config(state='active')
self.ble_disconnect_button.config(state='disabled')
# self.prot_add_button.config(state='disabled')
# self.prot_del_button.config(state='disabled')
# self.prot_save_button.config(state='disabled')
# self.prot_load_button.config(state='disabled')
self.calibrate_button.config(state='disabled')
def __enable_connect_button(self):
self.ble_connect_button.config(state='active')
def __disable_ui_elements(self):
self.ble_disconnect_button.config(state='disabled')
self.__enable_connect_button()
self.freq_slider.config(state='disabled')
for slider in self.slider_objects:
slider.config(state='disabled')
def get_calibration_thresholds(self):
if not self.is_calibrated():
raise ValueError("Vibrotactors are not calibrated!")
else:
self.r_ble_1_3_value = self.right_ble_thresh
self.r_ble_4_6_value = self.right_ble_thresh
self.r_ble_7_9_value = self.right_ble_thresh
self.r_ble_10_12_value = self.right_ble_thresh
self.l_ble_1_3_value = self.left_ble_thresh
self.l_ble_4_6_value = self.left_ble_thresh
self.l_ble_7_9_value = self.left_ble_thresh
self.l_ble_10_12_value = self.left_ble_thresh
return self.right_ble_thresh, self.left_ble_thresh
def start_session(self):
self.session_started = True
self.right_vta.write_all_motors(self.right_ble_thresh)
self.left_vta.write_all_motors(self.left_ble_thresh)
self.right_vta.start_imu()
self.left_vta.start_imu()
self.__save_protocol_to_file()
def stop_session(self):
self.session_started = False
self.right_vta.stop_imu()
self.left_vta.stop_imu()
self.disconnect_ble()
def is_connected(self):
return self.__connected
def is_calibrated(self):
return self.calibrated
def calibrate_return(self, left_threshold, right_threshold):
self.calibrated = True
self.left_ble_thresh = left_threshold
self.right_ble_thresh = right_threshold
def __calibrate_ble(self):
if self.right_vta and self.left_vta:
if self.right_vta.is_connected() and self.left_vta.is_connected():
CalibrateVibrotactors(self, self.root, self.left_vta, self.right_vta)
else:
messagebox.showerror("Error",
"Something went wrong connecting to the vibrotactors!\nCannot be calibrated!")
self.tab_button['text'] = 'BLE Input' + crossmark
else:
messagebox.showerror("Error", "Connect to vibrotactors first!\nCannot be calibrated!")