-
Notifications
You must be signed in to change notification settings - Fork 0
/
StemBerry_v90.py
2802 lines (2454 loc) · 157 KB
/
StemBerry_v90.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
#!/usr/bin/python3
#do not erase (needed to be executable for autostart)
'''
StemBerry V.90
Last updated: 8/30/2022
Dev: Clayton Bennett
OG dev: Austin Bebee
Description: SOCEM GUI. Connect RPi to Arduino, collect raw data. Save text inputs.
Contents (in order):
- Libraries
- Global Variables
- Global Functions
- GUI Class
- Home / geo. input screen
- Data collection screen
- Runs data collection function
- Stores data & saves data
- Plots F v D graph
- Load cell calibration screen
- Error report screen
- Excute GUI command
V15
- Change to 9 cell and 3 range count inputs
V19
- Rip out defunct calculations
- Clean up code, specifically by organizing statements of place for tkinter items
V37
- Dial in functionality with pretty new GUI.
- barbottom (not barmiddle) set to 70%-90% of stem height
V42
- Develop top level methods
V50
- Functional save state, save files, naming convention edge cases, and crisp appearance
V54
- Generate CSV's, suppress XLSX's
V56
- Retain 9-cell variables, for EI assessment upon saving counts, without reopening CSV files
V67
- So many things.
v77
- Serial collection functial, drinking from a waterhose, high hz
- Tare button message.
- PeakClick popup window.
V84
- The way peak clicks are handled and saved was moved to the inside of the choose peaks code, becuase plt.show() won't give up.
- Shut down plt.show after CSV file is saved.
V88
- GUI.filename_force updated on page change to either record force frame or final inputs page
- nameBlackBox updated to remove excess hyphen when direction ==''
- XLSX compilation file functional, currently set to seek force and EI files
- EI calcualtion works - only needs 1 file for all four nine-cell-scheme tests.
- This thing is getting heavy, 2844 lines.
V90
- Identify OS and choose filepath accordingly.
Fix:
- Fix serial connection problem between RasPi and Arduino (mostly fixed)
- Check that the Aruino is recieving ser.write characters ('x','d','s','t') # resolved
- Compile Csv's into Excel workbook # can be done
- Remove auto graph button, or at least uncheck it: use it to refer to auto clicker
- Develop autoclicker to be used for more than just side hits
- Finish autoclicker by setting plt.show() into an inset tkinter gui popup, and then mainoop.
Use: FigureCanvasTkAgg,NavigationToolbar2Tk,plt,Cursor.
- dev port is currently defined manually, given dev_manualOverride
- move header variable inputs
- make directory inputtable using dropdown menu item and textbox
- upgrade tkinter items to CustomTkinter
- PRIORITY: CREATE BASE NAME FROM VARIABLE AND PLOT: GUI.filename_force.get() is getting dangerous.
Notes:
- exec() is your friend. Use is to run multiple lines of code which you can copy and paste into a shell, using triple ' commenting
- save as separate CSV files, then as one combined XLSX file with multiple pages
'''
''' Libraries '''
import serial
from serial import Serial
# from serial import *
import serial.tools.list_ports # need this
import tkinter as tk
from tkinter import * # tk.Label == Label, tk.Button == Button, tk.Entry == Entry
import threading
from multiprocessing import Process
import csv
import matplotlib
from matplotlib import style
matplotlib.use("TkAgg")
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
from matplotlib.figure import Figure
#import matplotlib.animation as animation
import matplotlib.pyplot as plt
from matplotlib.widgets import Cursor
import itertools
from itertools import zip_longest
import subprocess
import sys
import os
import platform
from os import path
import numpy as np
import pandas as pd
#import peakutils
#from PeakUtils.Plot import plot as pplot
import math
import struct
from PIL import ImageTk,Image
import datetime
from datetime import date
import time
''' Global Variables '''
script = os.path.basename(__file__)
directory = os.path.dirname(__file__)
operatingsystem = platform.system() #determine OS
# use or sys.plaform instead of platform.system, to avoid importing platform
print("operatingsystem = ",operatingsystem)
print("os.getlogin() = ",os.getlogin())
today = date.today()
datestring = today.strftime("%b-%d-%Y")
ignoreserial = False # True
#ignoreserial = True # delete this # if RecordForce.ser.isOpen() == False:
barlength = 76 # cm. this shouldn't ever change, unless the bar is replaced. i.e. the width of a side hit cell.
dev_manualOverride = True
useInitialPlot_PeackClick = False
disReferenced_PeakClick = False
#dev_manual = 'COM7' # manual override
barradius = 1 # 1 cm = 0.32 inches
default_stemheight = 20.0 # cm
initial_barbottomOverStemheight_coeff = 0.8
convert_KgToLbs = 2.20462262 #kg to lbs
convert_KgToN = 9.81 #kg to N # CHECK FOR ACCURACY CB 8/9/2022
inchonvert = (((math.pi*(0.764))*31.4136)/359) # converts displacement to inches, wheel diameter = 31.4136
visualizeDatastream = False #True #set to live graph for data display
#visualizeDatastream = True
# visualizeDatastream ( search: "def datafeed(" ) is broken right now. Refer to earlier versions (pre v65)for reference of how Bebee left it.
if operatingsystem == 'Windows':
if os.getlogin() == 'clayt':
address = r'C:\Users\clayton\OneDrive - University of Idaho\AqMEQ\SOCEM\Data - Instron and SOCEM - 2020, 2021\SOCEM_DATA_2021'
dev_manual = 'COM3' # manual override, windows 10 OS
else:
dev_manualOverride = False
address = directory + '/SOCEM_data'
if not os.path.exists(address):
os.makedirs(address)
elif operatingsystem == 'Linux':
dev_manual = '/dev/ttyACM0' # manual override raspian OS
address = '/home/pi/Desktop/SOCEM_data_2022'
else:
address = directory + '/SOCEM_data'
dev_manualOverride = False
if not os.path.exists(address):
os.makedirs(address)
''' matplotlib Graph Settings '''
'''
style.use("ggplot")
f = Figure(figsize=(4.85,3.9), dpi=75)
a = f.add_subplot(111)
a.set_ylim(0, 25)
'''
''' Methods'''
# Determine Arduino serial port address
def SerConnect():
#try:
ports = serial.tools.list_ports.comports()
try:
dev = ports[0].device
except:
dev = '/dev/ttyACM0' # only works on pi
if dev_manualOverride == True:
dev = dev_manual # manual override
try:
ser = serial.Serial(dev, 115200, timeout=4,writeTimeout = 2,) # 1 second timeout
#print(type(ser))
print("dev = "+dev)
ser.reset_input_buffer()
#ser.isOpen()
#GUI.ignoreserial = False
return ser # this is the only spot it should be called ser, not RecordForce.ser
except:
GUI.ignoreserial = True
error = 'serial connection never established'
eCode = 'e1' # eCode = e1
GUI.errors.append(error) # append error label
GUI.errorCodes.append(eCode) # append error code
#popup('serial connection')
print("eCode = "+eCode)
# if serial disconnect (unplugged) reconnect - NOTE: doesn't properly work currently.
def SerReconnect():
try:
#if GUI.ignoreserial == False:
GUI.ignoreserial = False
try:
RecordForce.ser.close()
GUI.ignoreserial = False
except:
GUI.ignoreserial = True
RecordForce.ser = SerConnect()
print("SerReconnect()")
except:
#else:
GUI.ignoreserial = True
print("\nYou hit the 'SerReconnect' dropdown menu item while GUI.ignoreserial == True.\nSerial cannot be reconnected because\neither an arduino is not connected to your computer\nor the arduino is not sought by StemBerry.")
RecordForce.message_connectArduino()
def overwriteGuard(filename):# prevents overwriting by checking if filename already exists in saving folder
return path.exists(filename) # True = already exits, False = doesn't exist
def overwriteGuardPage(filename):# prevents overwriting by checking if filename already exists in saving folder
#return path.exists(filename) # True = already exits, False = doesn't exist
return False # don't mess up!
def data_display(visual): #changes display method #DELETE?
global visualizeDatastream
visualizeDatastream = visual
return visualizeDatastream
#if any error occurs, display popup error msg
def popup(error):
popup = tk.Tk()
popup.wm_title("Error")
E_label = Label(popup, text="A {} error occurred.".format(error), font=("arial", 12, "bold"))
E_label.pack(side="top", fill="x", pady=10)
popup.mainloop()
def popup_chooseFolder():
popup_chooseFolder = tk.Tk()
popup_chooseFolder.wm_title("Choose Folder")
E_label = Label(popup_chooseFolder, text="Paste file output directory here.", font=("arial", 12, "bold"))
#E_label.pack(side="top", fill="x", pady=10)
E_label.grid(row=0, column=1)
#GUI.addressInput.set("")
folder_entry = Entry(popup_chooseFolder, textvariable=GUI.addressInput, font = ("arial", 11, "bold"), width= 70, bg="white", fg="gray1")
folder_entry.grid(row=1, column=1)
save_button = Button(popup_chooseFolder,text = "Save", font = ("arial", 14, "bold"), height = 1, width = 6, fg = "ghost white", bg = "dodgerblue3",command=lambda:updateAdress())
save_button.grid(row=2, column=1)
popup_chooseFolder.mainloop()
''' Frame: Folder Input Field''
barset_frame = tk.LabelFrame(self, text='Bar Bottom Quickset',font = ("arial", 14, "bold"), width= 10, bg="white", fg="gray1")
barset_frame.place(x = 340, y = 230)
''' ''
def updateAdress():
print("updateAddress is broken. Please develop.")
print("GUI.addressInput.get() = ",GUI.addressInput.get())
print("GUI.address = ",GUI.address)
#GUI.address = GUI.addressInput.get() # broken right now
#print("GUI.address = ",GUI.address)
def showErrors():
GUI.show_frame(ErrorReport) # show Error Report page
ErrorReport.showErrors2(GUI.frames[ErrorReport]) # display errors in lists
def update_filename_preTest():
filename_preTest = nameBlackBox("preTest",GUI.filename_preTest.get())
GUI.filename_preTest.set(filename_preTest)
filename_all = filename_preTest.replace("preTest","all")
GUI.filename_all.set(filename_all)
def testForNineCellFilename(): # used to identify when nine-cell force, distance, and time data exists, and passes it to state data.
# the purpose of this is to avoid reopening CSV files in order to assess nine-cell data
# because, we have to wait for counts after to assess EI
# it would be easier to test right away to get peaks
# have a check box for nine cell test
# EI cannot be assessed for non-nine cell, because counts don't exist
# if box not checked, post test frame goes to single input for stem count, one number, with another number for range distance of count
# # Assessment is trigged at save state button push
#ninecellfilename = GUI.varietyname.get()+","+GUI.plotname.get()+"_"
ninecellfilename = GUI.varietyname.get()+","+GUI.plotname.get()
ninecellfilename_side1 = ninecellfilename+"_side1"
ninecellfilename_side2 = ninecellfilename+"_side2"
ninecellfilename_side3 = ninecellfilename+"_side3"
ninecellfilename_forward = ninecellfilename+"_foward"
currentFilename_force = GUI.filename_force.get()
# create GUI variable, for handling without reopening CSV's
#if (currentFilename_force == ninecellfilename_side1):
if (GUI.currentdirection.get() == "side1"):
GUI.forcePushed_side1 = GUI.forcePushed
GUI.distanceTraveled_side1 = GUI.distanceTraveled
GUI.timeElapsed_side1 = GUI.timeElapsed
#if (currentFilename_force == ninecellfilename_side2):
if (GUI.currentdirection.get() == "side2"):
GUI.forcePushed_side2 = GUI.forcePushed
GUI.distanceTraveled_side2 = GUI.distanceTraveled
GUI.timeElapsed_side2 = GUI.timeElapsed
#if (currentFilename_force == ninecellfilename_side3):
if (GUI.currentdirection.get() == "side3"):
GUI.forcePushed_side3 = GUI.forcePushed
GUI.distanceTraveled_side3 = GUI.distanceTraveled
GUI.timeElapsed_side3 = GUI.timeElapsed
#if (currentFilename_force == ninecellfilename_forward):
if (GUI.currentdirection.get() == "forward"):
GUI.forcePushed_forward = GUI.forcePushed
GUI.distanceTraveled_forward = GUI.distanceTraveled
GUI.timeElapsed_forward = GUI.timeElapsed
def createBackupFile():
''' Create a temp text file, with a list of all variables and variable names, that would be awesome '''
'''update_filename_preTest()
update_filename_postTest()
sniff_filename_force()
update_filename_postTest()
saveState_update_filenames()'''
now = datetime.datetime.now()
unix_now = time.mktime(now.timetuple())
unix_now_int = int(unix_now) # still gets seconds # the purpose of this is to append to filenames
str(unix_now_int)
filename_savestate = "backup_stemberry_"+str(unix_now_int)+".txt"
filename_savestate_full = GUI.address+"/"+filename_savestate
print("State saved at "+str(datetime.datetime.fromtimestamp(unix_now_int))+": "+filename_savestate)
# list all GUI vars, add them to a txt file
GUI.masslist=[GUI.cell1Mass.get(),GUI.cell2Mass.get(),GUI.cell3Mass.get(),GUI.cell4Mass.get(),GUI.cell5Mass.get(),GUI.cell6Mass.get(),GUI.cell7Mass.get(),GUI.cell8Mass.get(),GUI.cell9Mass.get()]
GUI.stemcounts=[GUI.cell1Count.get(),GUI.cell2Count.get(),GUI.cell3Count.get(),GUI.cell4Count.get(),GUI.cell5Count.get(),GUI.cell6Count.get(),GUI.cell7Count.get(),GUI.cell8Count.get(),GUI.cell9Count.get()]
GUI.diameters_cell1 = [GUI.cell1Diameter1.get(),GUI.cell1Diameter2.get(),GUI.cell1Diameter3.get(),GUI.cell1Diameter4.get()]
GUI.diameters_cell2 = [GUI.cell2Diameter1.get(),GUI.cell2Diameter2.get(),GUI.cell2Diameter3.get(),GUI.cell2Diameter4.get()]
GUI.diameters_cell3 = [GUI.cell3Diameter1.get(),GUI.cell3Diameter2.get(),GUI.cell3Diameter3.get(),GUI.cell3Diameter4.get()]
GUI.diameters_cell4 = [GUI.cell4Diameter1.get(),GUI.cell4Diameter2.get(),GUI.cell4Diameter3.get(),GUI.cell4Diameter4.get()]
GUI.diameters_cell5 = [GUI.cell5Diameter1.get(),GUI.cell5Diameter2.get(),GUI.cell5Diameter3.get(),GUI.cell5Diameter4.get()]
GUI.diameters_cell6 = [GUI.cell6Diameter1.get(),GUI.cell6Diameter2.get(),GUI.cell6Diameter3.get(),GUI.cell6Diameter4.get()]
GUI.diameters_cell7 = [GUI.cell7Diameter1.get(),GUI.cell7Diameter2.get(),GUI.cell7Diameter3.get(),GUI.cell7Diameter4.get()]
GUI.diameters_cell8 = [GUI.cell8Diameter1.get(),GUI.cell8Diameter2.get(),GUI.cell8Diameter3.get(),GUI.cell8Diameter4.get()]
GUI.diameters_cell9 = [GUI.cell9Diameter1.get(),GUI.cell9Diameter2.get(),GUI.cell9Diameter3.get(),GUI.cell9Diameter4.get()]
lines = [
'Units: diameter (mm), height (cm), range (cm), length (cm), mass (kg), time (ms), force (N) \n',
'script = '+script,
'directory = '+directory+'/',
'GUI.ignoreserial = '+str(GUI.ignoreserial),
'barlength = '+str(barlength),
'datestring = '+datestring,
'today = '+str(today),
'now = '+str(now),
'unix_now '+str(unix_now),
'unix_now_int = '+str(unix_now_int),
'backup filename unix_now_int decoded: '+ str(datetime.datetime.fromtimestamp(unix_now_int))+'\n',
'GUI.timestring.get() = '+GUI.timestring.get(),
'GUI.errors = '+makeDataString(GUI.errors),
'GUI.errorCodes = '+makeDataString(GUI.errorCodes),
'GUI.varietyname.get() = '+GUI.varietyname.get(),
'GUI.plotname.get() = '+GUI.plotname.get(),
'GUI.currentdirection.get() = '+GUI.currentdirection.get(),
'GUI.filename_force.get() = '+GUI.filename_force.get(),
'GUI.filename_preTest.get() = '+GUI.filename_preTest.get(),
'GUI.filename_postTest.get() = '+GUI.filename_postTest.get(),
'GUI.stemheight.get() = '+str(GUI.stemheight.get()),
'GUI.barmiddle.get() = '+str(GUI.barmiddle.get()),
'GUI.barbottom.get() = '+str(GUI.barbottom.get()),
'GUI.passfillednames_checkbox.get() = '+str(GUI.passfillednames_checkbox.get()),
'GUI.startRange1.get() = '+str(GUI.startRange1.get()),
'GUI.startRange2.get() = '+str(GUI.startRange2.get()),
'GUI.startRange3.get() = '+str(GUI.startRange3.get()),
'GUI.travelvelocity = '+str(GUI.travelvelocity),
'GUI.samplingrate = '+str(GUI.samplingrate),
'GUI.masslist = '+makeDataString(GUI.masslist),
'GUI.stemcounts = '+makeDataString(GUI.stemcounts),
'GUI.diameters_cell1 = '+makeDataString(GUI.diameters_cell1),
'GUI.diameters_cell2 = '+makeDataString(GUI.diameters_cell2),
'GUI.diameters_cell3 = '+makeDataString(GUI.diameters_cell3),
'GUI.diameters_cell4 = '+makeDataString(GUI.diameters_cell4),
'GUI.diameters_cell5 = '+makeDataString(GUI.diameters_cell5),
'GUI.diameters_cell6 = '+makeDataString(GUI.diameters_cell6),
'GUI.diameters_cell7 = '+makeDataString(GUI.diameters_cell7),
'GUI.diameters_cell8 = '+makeDataString(GUI.diameters_cell8),
'GUI.diameters_cell9 = '+makeDataString(GUI.diameters_cell9),
'GUI.EI_fullcontact = '+makeDataString(GUI.EI_fullcontact),
'GUI.EI_intermediatecontact = '+makeDataString(GUI.EI_intermediatecontact),
'GUI.EI_nocontact = '+makeDataString(GUI.EI_nocontact),
'GUI.AvgEI_intermediatecontact = '+makeDataString(GUI.AvgEI_intermediatecontact),
str(datetime.datetime.now())+'\n']
evenmorelines = [
'GUI.filename_all.get() = '+GUI.filename_all.get(), # no longer exists, compilation XLSX
'GUI.distanceTraveled = '+makeDataString(GUI.distanceTraveled),
'GUI.forcePushed = '+makeDataString(GUI.forcePushed),
'GUI.timeElapsed = '+makeDataString(GUI.timeElapsed)+'\n',
'Collected data, nine cell scheme:',
'GUI.forcePushed_side1 = '+makeDataString(GUI.forcePushed_side1),
'GUI.distanceTraveled_side1 = '+makeDataString(GUI.distanceTraveled_side1),
'GUI.timeElapsed_side1 = '+makeDataString(GUI.timeElapsed_side1),
'GUI.forcePushed_side2 = '+makeDataString(GUI.forcePushed_side2),
'GUI.distanceTraveled_side2 = '+makeDataString(GUI.distanceTraveled_side2),
'GUI.timeElapsed_side2 = '+makeDataString(GUI.timeElapsed_side2),
'GUI.forcePushed_side3 = '+makeDataString(GUI.forcePushed_side3),
'GUI.distanceTraveled_side3 = '+makeDataString(GUI.distanceTraveled_side3),
'GUI.timeElapsed_side3 = '+makeDataString(GUI.timeElapsed_side3),
'GUI.forcePushed_forward = '+makeDataString(GUI.forcePushed_forward),
'GUI.distanceTraveled_forward = '+makeDataString(GUI.distanceTraveled_forward),
'GUI.timeElapsed_forward = '+makeDataString(GUI.timeElapsed_forward),
str(datetime.datetime.now())]
try:
morelines = [
'\n',
'RecordForce.ser = '+str(RecordForce.ser),
str(datetime.datetime.now())]
except:
morelines = [
'\n',
'RecordForce.ser = '+'error',
str(datetime.datetime.now())]
with open(filename_savestate_full, 'w') as f:
f.write('\n'.join(lines))
f.write('\n'.join(morelines))
try:
f.write('\n'.join(evenmorelines))
except:
pass
def makeDataString(dataVector):
#timeElapsed_string = ' '.join(str(e) for e in GUI.timeElapsed)
dataString = ' '.join(str(e) for e in dataVector)
return dataString
def restoreState():
print("Please develop.")
# choose txt file (example: backup_stemberry_1660192559.txt
# trigger GUI directory and file selection would be sick.
# only restore postTest fields? start there.
def rename(filename): #if filename already exists - prompt user to rename
popup = tk.Tk()
popup.wm_title('Prompt Rename')
renameIt = Label(popup, text = 'Filename\n"{}"\nalready exists in the saving location.\nPlease rename and press Save.'.format(filename), font = ('arial', 10, 'bold'))
increment_button = Button(popup,text = "Auto Modify", font = ("arial", 14, "bold"), height = 2, width = 6, fg = "ghost white", bg = "dodgerblue3",command=lambda:incrementRename(filename))
overwrite_button = Button(popup, text = "Overwrite", font = ("arial", 14, "bold"), height = 2, width = 6, fg = "ghost white", bg = "red4",command=lambda:overwrite(filename))
renameIt.pack(side='top', fill='x', ipadx=10, ipady=10)
increment_button.pack(side='top', fill='both', ipadx=10, ipady=1)
overwrite_button.pack(side='top', fill='both', ipadx=10,ipady=1)
popup.mainloop()
def renamePage(filename):
print("Please develop, prevent pages from being overwritten in the filename_all spreadsheet")
def incrementRename(filename):
print("please develop, auto modify filename")
def overwrite(filename):
print("please develop, overwrite filename")
#closes GUI (from file menubar)
def close():
createBackupFile()
python = sys.executable
os.execl(python, python, * sys.argv)
def datafeed():
#frame = tk.Frame.RecordForce
frame = RecordForce.container
RecordForce.datafeed_frame
print("frame = ",frame)
if visualizeDatastream == True:# data displayed in scrollbars (default)
# Displays incoming data
# scroll = Scrollbar(RecordForce.datafeed_frame)
scroll = Scrollbar(frame)# what is this? TK!
print("scroll = ",scroll)
#scroll = Scrollbar(self)# what is this? TK!
''
RecordForce.time_label = Label(RecordForce.datafeed_frame, text = "Time (s)",font = ("arial", 14, "bold"), fg = "dodgerblue3", bg = "ghost white")
RecordForce.Timelist = Listbox(RecordForce.datafeed_frame, yscrollcommand = scroll.set, bg = "ghost white",highlightbackground = "gray2", width = 7, height = 1, font = ("arial", 14, "bold"), fg = "dodgerblue3")
RecordForce.dis_label = Label(RecordForce.datafeed_frame, text = "Distance (cm)",font = ("arial", 14, "bold"), fg = "dodgerblue3", bg = "ghost white")
RecordForce.Dislist = Listbox(RecordForce.datafeed_frame, yscrollcommand = scroll.set, bg = "ghost white",highlightbackground = "gray2", width = 7, height = 1, font = ("arial", 14, "bold"), fg = "dodgerblue3")
RecordForce.force_label = Label(RecordForce.datafeed_frame, text = "Force (N)",font = ("arial", 14, "bold"), fg = "dodgerblue3", bg = "ghost white")
RecordForce.Forcelist = Listbox(RecordForce.datafeed_frame, yscrollcommand = scroll.set, bg = "ghost white",highlightbackground = "gray2", width = 7, height = 5, font = ("arial", 14, "bold"), fg = "dodgerblue3")
'''
RecordForce.time_label = Label(frame, text = "Time (s)",font = ("arial", 14, "bold"), fg = "dodgerblue3", bg = "ghost white")
RecordForce.Timelist = Listbox(frame, yscrollcommand = scroll.set, bg = "ghost white",highlightbackground = "gray2", width = 7, height = 1, font = ("arial", 14, "bold"), fg = "dodgerblue3")
RecordForce.dis_label = Label(frame, text = "Distance (cm)",font = ("arial", 14, "bold"), fg = "dodgerblue3", bg = "ghost white")
RecordForce.Dislist = Listbox(frame, yscrollcommand = scroll.set, bg = "ghost white",highlightbackground = "gray2", width = 7, height = 1, font = ("arial", 14, "bold"), fg = "dodgerblue3")
RecordForce.force_label = Label(frame, text = "Force (N)",font = ("arial", 14, "bold"), fg = "dodgerblue3", bg = "ghost white")
RecordForce.Forcelist = Listbox(frame, yscrollcommand = scroll.set, bg = "ghost white",highlightbackground = "gray2", width = 7, height = 5, font = ("arial", 14, "bold"), fg = "dodgerblue3")
'''
RecordForce.time_label.place(x = 180, y = 110)
RecordForce.Timelist.place(x = 180, y = 140)
RecordForce.dis_label.place(x = 280, y = 110)
RecordForce.Dislist.place(x = 280, y = 140)
RecordForce.force_label.place(x = 420, y = 110)
RecordForce.Forcelist.place(x = 420, y = 140)
else:# user decided for no data display
try:#clear scrollbars if they were there
RecordForce.Dislist.place_forget()
RecordForce.Forcelist.place_forget()
RecordForce.Timelist.place_forget()
RecordForce.dis_label.place_forget()
RecordForce.force_label.place_forget()
RecordForce.time_label.place_forget()
except:# no scrollbars
pass
def passData():
'''Scrollbars Options'''
# if scrollbars option = on:
if visualizeDatastream == True:
try: # puts data on GUI display by default (user can turn off)
RecordForce.Dislist.insert(END, str(GUI.distanceTraveled[i]))# inserts at end of listbox to actually display
RecordForce.Dislist.see(END)# makes sure listbox is at end so it displays live data
RecordForce.Forcelist.insert(END, str('%.2f' % GUI.forcePushed[i]))
RecordForce.Forcelist.see(END)
RecordForce.Timelist.insert(END, str('%.2f' % GUI.timeElapsed[i]))
RecordForce.Timelist.see(END)
#scrollbars options = off
'''
except:
pass
'''
except:
GUI.errors.append('data append') # label
eCode = 'e4'
GUI.errorCodes.append(eCode)
print("eCode = "+eCode) # eCode = e4
# * # DATA COLLECTION FUNCTION - Acquires live data from Arduino # * #
def collectData():
hang=0
nothingToRead=0 # controls timeout
blankline = "b'\n"
while RecordForce.hasStarted==True and RecordForce.hasSentStop==False:
#time.sleep(0.02)
bytecount = RecordForce.ser.in_waiting
print("RecordForce.ser.in_waiting = ",bytecount)
if bytecount > 5 and RecordForce.hasSentStop==False: # this does happen
print("datachunk...") # stopping after this
try:
time.sleep(0.2) # no luck
ser_bytes = RecordForce.ser.read(bytecount)
if blankline in str(ser_bytes):
print("blankline")
continue
except:
print("Failed: ser_bytes = RecordForce.ser.readline()")
continue
hang = 0
nothingToRead=0
#print("ser_bytes = ",ser_bytes)
line = ser_bytes.decode('utf-8').rstrip()
datapacket = line.splitlines()
# parse datapacket
for i in datapacket:
split = i.split("|")
if RecordForce.hasSentStop == False:
try:
#print("split = ",split, float(split[0]),float(split[1]),float(split[2]))
print("split = ",split)
distance = round(float(split[0]),3)
force = round(float(split[1]),3)
timetick = round(float(split[2]),3)
GUI.timeElapsed.append(timetick)# list of GUI.distanceTraveled time
GUI.distanceTraveled.append(distance)# list of inches traveled @ does this happen with the whole list, or one element at a time?
GUI.forcePushed.append(force)# list of force traveled
except:
print("missed a line, list index out of range.")
pass
if line =="Stopped!":
RecordForce.sendStop()
# the purpose of this elif is to allow the while loop to iterate if there's nothing to read.
# But also, it has primarily been entered if the serial connection has already timed out
elif bytecount < 6 and bytecount > 0 :
ser_bytes = RecordForce.ser.read(bytecount)
#print("ser_bytes = ",ser_bytes)
nothingToRead +=1
if nothingToRead>5: # if the while loop goes through five iterations, without seeing anything worth recording, give up.
RecordForce.sendStop()
print("Hung up.")
SerReconnect()
GUI.show_frame(InitialInputs)
else:
hang +=1
print("go back to top of while loop")
if hang>10: # if the while loop goes through ten iterations of radio silence, give up. The serial connection probably timed out. search 'timeout = '
RecordForce.sendStop()
print("Hung up, timeout.")
SerReconnect()
GUI.show_frame(InitialInputs)
def runDataCollect():
try:
RecordForce.sendStart()
except:
print("run fail")
GUI.errors.append('serial com. (start data)') # label
eCode = 'e2' # eCode = e2
GUI.errorCodes.append(eCode)
print("eCode = "+eCode)
popup('start data collect')
RecordForce.thread2_collectData = threading.Thread(target = collectData)
RecordForce.thread2_collectData.start()
def incrementName(filename):
hyphen = "_"
# determine last few characters from a filename
def incrementvars(filename):
lastchar = filename[len(filename)-1]
secondtolastchar = filename[len(filename)-2]
thirdtolastchar = filename[len(filename)-3]
lastcharandsecondtolastchar = str(secondtolastchar+lastchar)
return lastchar, secondtolastchar, thirdtolastchar, lastcharandsecondtolastchar
#check if the last two are hyphens. if there is more than one hypthen, remove the last character until there is only one hyphen.
def hyphencheck(filename,hyphen,lastchar, secondtolastchar, thirdtolastchar, lastcharandsecondtolastchar):
while lastchar == hyphen and secondtolastchar == hyphen: # if two hyphens at the end
filename = filename[:-1] # remove last character
incrementvars()
return filename, lastchar, secondtolastchar, thirdtolastchar, lastcharandsecondtolastchar
if filename == "": # default, if user tried to increment without inputting any varietyname, plotname, or filename
filename = datestring+","+GUI.timestring.get()
lastchar, secondtolastchar, thirdtolastchar, lastcharandsecondtolastchar = incrementvars(filename)
filename, lastchar, secondtolastchar, thirdtolastchar, lastcharandsecondtolastchar = hyphencheck(filename,hyphen,lastchar, secondtolastchar, thirdtolastchar, lastcharandsecondtolastchar)
if lastchar == hyphen: # if last character is a hyphen
newName = str(filename+str("1"))
elif secondtolastchar == hyphen and lastchar.isnumeric: # if single digit preceded by a hyphen
#newName = str(filename+str(int(lastchar)+1))
filename = filename[:-1] # remove last character
newName = str(filename+str(int(lastchar)+1))
elif thirdtolastchar == hyphen and lastcharandsecondtolastchar.isnumeric: # if double digits preceded by a hyphen
filename = filename[:-1] # remove last character
filename = filename[:-1] # remove last character
newName = str(filename+str(int(lastcharandsecondtolastchar)+1))
elif filename == "":
newName = date
else:
newName = str(filename+"_1")
return newName
#GUI.filename_force.set(newName)
''' Edge cases: Filenaming '''
def nameDirectionScrub(filename):
if ("_side1" in filename):
filename=filename.replace("_side1","")
print(filename)
if ("_side2" in filename):
filename=filename.replace("_side2","")
if ("_side3" in filename):
filename=filename.replace("_side3","")
if ("_forward" in filename):
filename=filename.replace("_forward","")
if ("_postTest" in filename):
filename=filename.replace("_postTest","")
return filename
def nameMissing(varietyname,plotname):
if varietyname == "":
varietyname = datestring
if plotname == "":
plotname = GUI.timestring.get() # plotname = GUI.timestring.get() # if you want the timestring (serving at plotname) to not change...but then it will never change
return varietyname, plotname
def nameBlackBox(direction,filename):
varietyname = GUI.varietyname.get()
plotname = GUI.plotname.get()
check=GUI.passfillednames_checkbox.get()
if GUI.filename_force.get()=="" and check==1 and direction=='':
varietyname, plotname = nameMissing(varietyname, plotname)
#print(varietyname, plotname)
filename = str(varietyname+str(",")+plotname)
elif GUI.filename_force.get()=="" and check==1 and direction!='':
varietyname, plotname = nameMissing(varietyname, plotname)
filename = str(varietyname+str(",")+plotname+"_"+direction)
elif GUI.filename_force.get()=="" and check==0 and direction !='':
filename = datestring+","+time.strftime("%H%M")+"_"+direction
elif GUI.filename_force.get()!="" and check==1 and direction !='':
varietyname, plotname = nameMissing(varietyname, plotname)
filename = str(varietyname+str(",")+plotname+str("_")+direction)
elif GUI.filename_force.get()!="" and check==0 and direction !='':
if ("side1" in filename) or ("side2" in filename) or ("side3" in filename) or ("forward" in filename) or ("postTest" in filename):
filename = nameDirectionScrub(GUI.filename_force.get())
filename = filename+"_"+direction
else:
filename = filename+"_"+direction
elif GUI.filename_force.get()=="" and check==0 and direction =='':
filename = datestring+","+time.strftime("%H%M")
elif GUI.filename_force.get()!="" and check==1 and direction =='':
varietyname, plotname = nameMissing(varietyname, plotname)
filename = str(varietyname+str(",")+plotname)
elif GUI.filename_force.get()!="" and check==0 and direction =='':
if ("side1" in filename) or ("side2" in filename) or ("side3" in filename) or ("forward" in filename) or ("postTest" in filename):
filename = nameDirectionScrub(GUI.filename_force.get())
filename = filename
else:
filename = filename
#GUI.filename_postTest.set(filename_postTest)
return filename
''' end: Edge cases: Filenaming '''
''' Single XLSX workbook created from all expected CSV files for 9-cell study'''
def generateXSLXcombinedFile():
writer = pd.ExcelWriter('default.xlsx')
for csvfilename in sys.ar[1:]:
df = pd.read.csv(csvfilename)
#FIX df.to_excel(writer.sheet_names=os.path.splitext(csvfilename)[0]) # "keyword cannot be an expression"
writer.save()
def peakClickRunAndSave(filename):
PeakClick() # you cannot put in counts first....because they haven't been collected yet!
#ergo, run clicks after triggered XLSX workbook creation
''' trigger with button, on Initial Inputs page. Button also clears all data from stemberry, wait it dods not triggers PeakClick.py, which saves to a separate CSV before all CSV's are wrapped into a xlsx workbook.
'''
'''Classes, Tkinter GUI'''
# GUI overarching class
class GUI(tk.Tk):
def __init__(self, *args, **kwargs):# automatically runs
tk.Tk.__init__(self, *args, **kwargs)
GUI.initializeVarsGUI()
GUI.refreshAll()
container = tk.Frame(self)
container.pack(side='top', fill='both',expand = True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
# top menu configuration
menubar = Menu(container)
filemenu = Menu(menubar, tearoff=0)
datamenu = Menu(menubar, tearoff=0)
pagemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label='Serial Reconnect', command = lambda:SerReconnect())
filemenu.add_command(label='Choose Output Folder', command = lambda:popup_chooseFolder())
filemenu.add_command(label='Errors', command = lambda:showErrors())
filemenu.add_command(label='Save State', command = lambda:createBackupFile())
filemenu.add_command(label="Exit", command = lambda:close())
pagemenu.add_command(label="Guide", command=lambda:GUI.show_frame(Guide))
pagemenu.add_command(label="Initial Inputs", command=lambda:GUI.show_frame(InitialInputs))
pagemenu.add_command(label="Record Force", command=lambda:GUI.show_frame(RecordForce))
pagemenu.add_command(label="Post Test Inputs", command=lambda:GUI.show_frame(FinalInputs))
pagemenu.add_command(label="Calibrate", command=lambda:GUI.show_frame(Calibrate))
pagemenu.add_command(label="Stem Count PreTest, Classic", command=lambda:GUI.show_frame(StemCountClassic))
datamenu.add_command(label="Data Feed Display, On", command = lambda:data_display(True))
datamenu.add_command(label="Data Feed Display, Off", command = lambda:data_display(False))
menubar.add_cascade(label='File', menu=filemenu)
menubar.add_cascade(label="Pages", menu=pagemenu)
menubar.add_cascade(label="Livestream Data Recording", menu=datamenu)
tk.Tk.config(self, menu=menubar)
GUI.frames = {}# empty dictionary
for F in (InitialInputs, RecordForce, FinalInputs, Calibrate, Guide, ErrorReport, StemCountClassic):# must put all pages in here
frame = F(container, self)
self.frames[F] = frame
frame.grid(row=0, column=0, sticky='nsew')
frame.configure(background = 'ghost white')
GUI.show_frame(InitialInputs)
def initializeVarsGUI():
GUI.filename_force = StringVar()
GUI.filename_preTest = StringVar()
GUI.filename_postTest = StringVar()
GUI.filename_all = StringVar()
GUI.varietyname = StringVar()
GUI.plotname = StringVar()
GUI.stemheight = DoubleVar()
GUI.currentdirection = StringVar()#
GUI.barmiddle = DoubleVar() #
GUI.barbottom = DoubleVar() #
GUI.passfillednames_checkbox = IntVar() # revert
GUI.timestring = StringVar()
GUI.startRange1, GUI.startRange2, GUI.startRange3 = DoubleVar(), DoubleVar(), DoubleVar() # cm = StringVar()
GUI.addressInput = StringVar()
GUI.cell1Mass,GUI.cell2Mass,GUI.cell3Mass,GUI.cell4Mass,GUI.cell5Mass,GUI.cell6Mass,GUI.cell7Mass,GUI.cell8Mass,GUI.cell9Mass = DoubleVar(), DoubleVar(), DoubleVar(), DoubleVar(), DoubleVar(), DoubleVar(), DoubleVar(), DoubleVar(), DoubleVar()
GUI.cell1Count,GUI.cell2Count,GUI.cell3Count,GUI.cell4Count,GUI.cell5Count,GUI.cell6Count,GUI.cell7Count,GUI.cell8Count,GUI.cell9Count = DoubleVar(), DoubleVar(), DoubleVar(), DoubleVar(), DoubleVar(), DoubleVar(), DoubleVar(), DoubleVar(), DoubleVar()
GUI.cell1Diameter1,GUI.cell2Diameter1,GUI.cell3Diameter1,GUI.cell4Diameter1,GUI.cell5Diameter1,GUI.cell6Diameter1,GUI.cell7Diameter1,GUI.cell8Diameter1,GUI.cell9Diameter1 = DoubleVar(), DoubleVar(), DoubleVar(), DoubleVar(), DoubleVar(), DoubleVar(), DoubleVar(), DoubleVar(), DoubleVar()
GUI.cell1Diameter2,GUI.cell2Diameter2,GUI.cell3Diameter2,GUI.cell4Diameter2,GUI.cell5Diameter2,GUI.cell6Diameter2,GUI.cell7Diameter2,GUI.cell8Diameter2,GUI.cell9Diameter2 = DoubleVar(), DoubleVar(), DoubleVar(), DoubleVar(), DoubleVar(), DoubleVar(), DoubleVar(), DoubleVar(), DoubleVar()
GUI.cell1Diameter3,GUI.cell2Diameter3,GUI.cell3Diameter3,GUI.cell4Diameter3,GUI.cell5Diameter3,GUI.cell6Diameter3,GUI.cell7Diameter3,GUI.cell8Diameter3,GUI.cell9Diameter3 = DoubleVar(), DoubleVar(), DoubleVar(), DoubleVar(), DoubleVar(), DoubleVar(), DoubleVar(), DoubleVar(), DoubleVar()
GUI.cell1Diameter4,GUI.cell2Diameter4,GUI.cell3Diameter4,GUI.cell4Diameter4,GUI.cell5Diameter4,GUI.cell6Diameter4,GUI.cell7Diameter4,GUI.cell8Diameter4,GUI.cell9Diameter4 = DoubleVar(), DoubleVar(), DoubleVar(), DoubleVar(), DoubleVar(), DoubleVar(), DoubleVar(), DoubleVar(), DoubleVar()
''' Non-tkinter GUI vars, initialize ''' # for nine cell assessment, save state
# may as well keep everything here, for fun
GUI.errors = [] # for tracking errors
GUI.errorCodes = [] # for tracking errors
GUI.ignoreserial = ignoreserial
GUI.address = address
GUI.forcePushed = []
GUI.distanceTraveled = []
GUI.timeElapsed = []
GUI.travelvelocity = []
GUI.samplingrate = []
GUI.forcePushed_side1 = []
GUI.forcePushed_side2 = []
GUI.forcePushed_side3 = []
GUI.forcePushed_forward = []
GUI.distanceTraveled_side1 = []
GUI.distanceTraveled_side2 = []
GUI.distanceTraveled_side3 = []
GUI.distanceTraveled_forward = []
GUI.timeElapsed_side1 = []
GUI.timeElapsed_side2 = []
GUI.timeElapsed_side3 = []
GUI.timeElapsed_forward = []
GUI.peaks_force_side1 = []
GUI.peaks_force_side2 = []
GUI.peaks_force_side3 = []
GUI.peaks_force_forward = []
GUI.peaks_distance_side1 = []
GUI.peaks_distance_side2 = []
GUI.peaks_distance_side3 = []
GUI.peaks_distance_forward = []
GUI.peaks_time_side1 = []
GUI.peaks_time_side2 = []
GUI.peaks_time_side3 = []
GUI.peaks_time_forward = []
GUI.peaks_force = []
GUI.peaks_distance = []
GUI.peaks_time = []
peakclick.peaks_force = []
peakclick.peaks_distance = []
peakclick.peaks_time = []
GUI.stemcounts = []
GUI.peak_force_cell1, GUI.peak_force_cell2, GUI.peak_force_cell3, GUI.peak_force_cell4, GUI.peak_force_cell5, GUI.peak_force_cell6, GUI.peak_force_cell7, GUI.peak_force_cell8, GUI.peak_force_cell9 = [],[],[],[],[],[],[],[],[]
GUI.peak_distance_cell1, GUI.peak_distance_cell2, GUI.peak_distance_cell3, GUI.peak_distance_cell4, GUI.peak_distance_cell5, GUI.peak_distance_cell6, GUI.peak_distance_cell7, GUI.peak_distance_cell8, GUI.peak_distance_cell9 = [],[],[],[],[],[],[],[],[]
GUI.peak_time_cell1, GUI.peak_time_cell2, GUI.peak_time_cell3, GUI.peak_time_cell4, GUI.peak_time_cell5, GUI.peak_time_cell6, GUI.peak_time_cell7, GUI.peak_time_cell8, GUI.peak_time_cell9 = [],[],[],[],[],[],[],[],[]
GUI.data_preTest,GUI.data_recordForce,GUI.data_postTest,GUI.data_peaks,GUI.data_EI = [],[],[],[],[]
def refreshAll(): #clearall(self)?
GUI.filename_force.set("")
GUI.filename_preTest.set("")
GUI.filename_postTest.set("")
GUI.filename_all.set("")
GUI.varietyname.set("")
GUI.plotname.set("")
GUI.startRange1.set(50)
GUI.startRange2.set(150)
GUI.startRange3.set(250) # centimeters
GUI.stemheight.set(default_stemheight) # cm
GUI.barbottom.set(round(GUI.stemheight.get()*initial_barbottomOverStemheight_coeff,3)) # cm
GUI.barmiddle.set(round(GUI.barbottom.get()+barradius,3)) # cm
GUI.passfillednames_checkbox.set(1)
GUI.timestring.set(time.strftime("%H%M"))
GUI.currentdirection.set("")
GUI.addressInput.set("")
''' Set post test variables for mass, count, and diameter'''
GUI.cell1Mass.set(0),GUI.cell2Mass.set(0),GUI.cell3Mass.set(0),GUI.cell4Mass.set(0),GUI.cell5Mass.set(0),GUI.cell6Mass.set(0),GUI.cell7Mass.set(0),GUI.cell8Mass.set(0),GUI.cell9Mass.set(0)
GUI.cell1Count.set(0),GUI.cell2Count.set(0),GUI.cell3Count.set(0),GUI.cell4Count.set(0),GUI.cell5Count.set(0),GUI.cell6Count.set(0),GUI.cell7Count.set(0),GUI.cell8Count.set(0),GUI.cell9Count.set(0)
GUI.cell1Diameter1.set(0),GUI.cell2Diameter1.set(0),GUI.cell3Diameter1.set(0),GUI.cell4Diameter1.set(0),GUI.cell5Diameter1.set(0),GUI.cell6Diameter1.set(0),GUI.cell7Diameter1.set(0),GUI.cell8Diameter1.set(0),GUI.cell9Diameter1.set(0)
GUI.cell1Diameter2.set(0),GUI.cell2Diameter2.set(0),GUI.cell3Diameter2.set(0),GUI.cell4Diameter2.set(0),GUI.cell5Diameter2.set(0),GUI.cell6Diameter2.set(0),GUI.cell7Diameter2.set(0),GUI.cell8Diameter2.set(0),GUI.cell9Diameter2.set(0)
GUI.cell1Diameter3.set(0),GUI.cell2Diameter3.set(0),GUI.cell3Diameter3.set(0),GUI.cell4Diameter3.set(0),GUI.cell5Diameter3.set(0),GUI.cell6Diameter3.set(0),GUI.cell7Diameter3.set(0),GUI.cell8Diameter3.set(0),GUI.cell9Diameter3.set(0)
GUI.cell1Diameter4.set(0),GUI.cell2Diameter4.set(0),GUI.cell3Diameter4.set(0),GUI.cell4Diameter4.set(0),GUI.cell5Diameter4.set(0),GUI.cell6Diameter4.set(0),GUI.cell7Diameter4.set(0),GUI.cell8Diameter4.set(0),GUI.cell9Diameter4.set(0)
''' end '''
''' Non-tkinter GUI vars, initialize ''' # for nine cell assessment, save state
# may as well keep everything here, for fun
GUI.errors = [] # for tracking errors
GUI.errorCodes = [] # for tracking errors
GUI.forcePushed = []
GUI.distanceTraveled = []
GUI.timeElapsed = []
GUI.forcePushed_side1 = []
GUI.forcePushed_side2 = []
GUI.forcePushed_side3 = []
GUI.forcePushed_forward = []
GUI.distanceTraveled_side1 = []
GUI.distanceTraveled_side2 = []
GUI.distanceTraveled_side3 = []
GUI.distanceTraveled_forward = []
GUI.timeElapsed_side1 = []
GUI.timeElapsed_side2 = []
GUI.timeElapsed_side3 = []
GUI.timeElapsed_forward = []
GUI.peaks_force_side1 = []
GUI.peaks_force_side2 = []
GUI.peaks_force_side3 = []
GUI.peaks_force_forward = []
GUI.peaks_distance_side1 = []
GUI.peaks_distance_side2 = []
GUI.peaks_distance_side3 = []
GUI.peaks_distance_forward = []
GUI.peaks_time_side1 = []
GUI.peaks_time_side2 = []
GUI.peaks_time_side3 = []
GUI.peaks_force = []
GUI.peaks_distance = []
GUI.peaks_time = []
GUI.stemcounts = []
GUI.peak_force_cell1, GUI.peak_force_cell2, GUI.peak_force_cell3, GUI.peak_force_cell4, GUI.peak_force_cell5, GUI.peak_force_cell6, GUI.peak_force_cell7, GUI.peak_force_cell8, GUI.peak_force_cell9 = [],[],[],[],[],[],[],[],[]
GUI.peak_distance_cell1, GUI.peak_distance_cell2, GUI.peak_distance_cell3, GUI.peak_distance_cell4, GUI.peak_distance_cell5, GUI.peak_distance_cell6, GUI.peak_distance_cell7, GUI.peak_distance_cell8, GUI.peak_distance_cell9 = [],[],[],[],[],[],[],[],[]
GUI.peak_time_cell1, GUI.peak_time_cell2, GUI.peak_time_cell3, GUI.peak_time_cell4, GUI.peak_time_cell5, GUI.peak_time_cell6, GUI.peak_time_cell7, GUI.peak_time_cell8, GUI.peak_time_cell9 = [],[],[],[],[],[],[],[],[]
GUI.peak_EI_fullcontact_cell1, GUI.peak_EI_fullcontact_cell2, GUI.peak_EI_fullcontact_cell3, GUI.peak_EI_fullcontact_cell4, GUI.peak_EI_fullcontact_cell5, GUI.peak_EI_fullcontact_cell6, GUI.peak_EI_fullcontact_cell7, GUI.peak_EI_fullcontact_cell8, GUI.peak_EI_fullcontact_cell9 = [],[],[],[],[],[],[],[],[]
GUI.peak_EI_intermediatecontact_cell1, GUI.peak_EI_intermediatecontact_cell2, GUI.peak_EI_intermediatecontact_cell3, GUI.peak_EI_intermediatecontact_cell4, GUI.peak_EI_intermediatecontact_cell5, GUI.peak_EI_intermediatecontact_cell6, GUI.peak_EI_intermediatecontact_cell7, GUI.peak_EI_intermediatecontact_cell8, GUI.peak_EI_intermediatecontact_cell9 = [],[],[],[],[],[],[],[],[]
GUI.peak_EI_nocontact_cell1, GUI.peak_EI_nocontact_cell2, GUI.peak_EI_nocontact_cell3, GUI.peak_EI_nocontact_cell4, GUI.peak_EI_nocontact_cell5, GUI.peak_EI_nocontact_cell6, GUI.peak_EI_nocontact_cell7, GUI.peak_EI_nocontact_cell8, GUI.peak_EI_nocontact_cell9 = [],[],[],[],[],[],[],[],[]
GUI.peaks_time_forward = []
GUI.EI_fullcontact = []
GUI.EI_intermediatecontact = []
GUI.EI_nocontact = []
GUI.AvgEI_intermediatecontact = []
GUI.data_preTest,GUI.data_recordForce,GUI.data_postTest,GUI.data_peaks,GUI.data_EI = [],[],[],[],[]
def show_frame(cont):
frame = GUI.frames[cont]
frame.tkraise()
frame.event_generate("<<ShowFrame>>") # event
# buttons that are the same for each page
#'''
class repeatPageButtons:
def __init__(self, parent, controller): # automatically runs
filler=1
def showButtons(self, parent, controller):
guide_button = Button(self, text = "Guide", font = ("arial", 14, "bold"), height = 2, width = 8, fg = "ghost white", bg = "gray2",command=lambda:GUI.show_frame(Guide))
initialInputs_button = Button(self, text = "Initial\nInputs", font = ("arial", 14, "bold"), height = 2, width = 8, fg = "ghost white", bg = "gray2",command=lambda:GUI.show_frame(InitialInputs))
recordForce_button = Button(self, text = "Record\nForce", font = ("arial", 14, "bold"), height = 2, width = 8, fg = "ghost white", bg = "gray2",command=lambda:GUI.show_frame(RecordForce))
postInputs_button = Button(self, text = "Post Test\nInputs", font = ("arial", 14, "bold"), height = 2, width = 8, fg = "ghost white", bg = "gray2",command=lambda:GUI.show_frame(FinalInputs))
guide_button.place(x = 0, y = 340)
initialInputs_button.place(x = 375/3*1, y = 340)
recordForce_button.place(x = 375/3*2, y = 340)
postInputs_button.place(x = 375/3*3, y = 340)
#'''
#Home page
class InitialInputs(tk.Frame):
def __init__(self, parent, controller): # automatically runs
# Once the program launches, the InitialInput screen will be shown for the first time, prompting serial connection
try:
RecordForce.ser = SerConnect()
except:
GUI.ignoreserial = True
print("Serial not connected.")
tk.Frame.__init__(self, parent)
''' GUI design, non-frame '''
pageButtons = repeatPageButtons.showButtons(self, parent, controller)
homeheader = Label(self, text = "INITIAL INPUTS", font = ("arial", 17, "bold"), fg = "gray3", bg="ghost white")
unit_label = Label(self, text=str("Distance and height are in centimeters."), font = ("arial", 12, "italic"), fg = "red4", bg="ghost white")
savePreTestInputs_button = Button(self, text ="Save Initial Inputs", font = ("arial", 16, "bold"), height = 1, width = 20, fg = "ghost white", bg = "dodgerblue3", command=lambda:self.savePreTestInputs())
variety_label = Label(self, text = "Variety: ", font = ("arial", 14, "bold"), fg = "gray3", bg="ghost white")
varietyname_entryBox = Entry(self, textvariable=GUI.varietyname, font = ("arial", 14, "bold"), width="20", bg="white", fg="gray1")
plotname_label = Label(self, text = "Plot: ", font = ("arial", 14, "bold"), fg = "gray3", bg="ghost white")
plotname_entryBox = Entry(self, textvariable=GUI.plotname, font = ("arial", 14, "bold"), width="10", bg="white", fg="gray1")
passfillednames_checkbox = Checkbutton(self, text = "Use variety & plot names", variable = GUI.passfillednames_checkbox, width=23, height=2, font = ("arial", 12), bg='ghost white')
stemHeight_label = Label(self, text = "Avg. Stem Height (cm):", font = ("arial", 14, "bold"), fg = "gray3", bg="ghost white")
stemHeight_entry = Entry(self, textvariable=GUI.stemheight, font = ("arial", 14, "bold"), width= 6, bg="white", fg="gray1")
barHeight_label = Label(self, text = "Bar Middle Height (cm):", font = ("arial", 14, "bold"), fg = "gray3", bg="ghost white")
barHeight_entry = Entry(self, textvariable=GUI.barmiddle, font = ("arial", 14, "bold"), width= 6, bg="white", fg="gray1")
homeheader.place(x=275,y=0)
unit_label.place(x=500,y=0)
savePreTestInputs_button.place(x = 510, y = 340)
variety_label.place(x=0,y=35)
varietyname_entryBox.place(x = 80, y = 35)
plotname_label.place(x=310,y=35)
plotname_entryBox.place(x = 360, y = 35)
passfillednames_checkbox.place(x = 540 , y = 25)
stemHeight_label.place(x=0,y=240)
stemHeight_entry.place(x = 220, y = 240)
barHeight_label.place(x=0,y=280)
barHeight_entry.place(x = 220, y = 280)
''' Frame: Range'''
range_frame = tk.LabelFrame(self, text='Side Hit Ranges',font = ("arial", 14, "bold"), width= 10, bg="white", fg="gray1")
range_frame.place(x = 20, y = 80)
startRange1Dis_label = Label(range_frame, text = "Range 1 start (cm):", font = ("arial", 14, "bold"), fg = "gray3", bg="ghost white").grid(row=2, column=0)