-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcobot_malfunction_split.py
265 lines (220 loc) · 9.29 KB
/
cobot_malfunction_split.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
import socket
import random
import time
import csv
import datetime
import os
from tkinter import scrolledtext
import tkinter as tk
button_params = [
{'text': 'Baseline', 'num_block': 1, 'wait_time': 5.0},
{'text': 'Practice', 'num_block': 2, 'wait_time': 5.0},
{'text': 'Block 1', 'num_block': 3, 'wait_time': 5.0},
{'text': 'Block 2', 'num_block': 4, 'wait_time': 5.0},
{'text': 'Block 3', 'num_block': 5, 'wait_time': 5.0},
]
host = '192.168.0.37'
port = 8888
# Define the color and trajectory mappings
color_map = {1: "Green", 2: "Green", 3: "Red", 4: "Red"}
trajectory_map = {1: True, 2: False, 3: True, 4: False}
# Global variable to store the clicked button's label
clicked_button_label = None
def custom_print(sequence, text_widget):
text_widget.config(state=tk.NORMAL) # Make the widget editable
text_widget.insert(tk.END, "left ")
for num in sequence:
color = color_map[num]
trajectory = trajectory_map[num]
if color == "Green":
text_widget.insert(tk.END, str(trajectory) + " ", "green")
else:
text_widget.insert(tk.END, str(trajectory) + " ", "red")
text_widget.insert(tk.END, " right\n")
text_widget.config(state=tk.DISABLED) # Make the widget read-only
def gen_seq(num_block):
match num_block:
case 1:
sequence = [1,3]*2
random.shuffle(sequence)
case 2:
sequence = [1,3]*2
random.shuffle(sequence)
case 3:
seq_1 = [1,3]*4
random.shuffle(seq_1)
seq_2 = [1,3]*4
random.shuffle(seq_2)
sequence = seq_1 + seq_2
case 4:
seq_1 = [2,4]
random.shuffle(seq_1)
seq_2 = [1,3]+[1,2,3,4]
random.shuffle(seq_2)
seq_3 = [1,2,3,4]*2
random.shuffle(seq_3)
sequence = seq_1 + seq_2 + seq_3
case 5:
seq_1 = [1,3]*4
random.shuffle(seq_1)
seq_2 = [1,3]*4
random.shuffle(seq_2)
sequence = seq_1 + seq_2
return sequence
def tcp_send_received(data, seq_log, text_widget):
text_widget.config(state=tk.NORMAL) # Make the widget editable
text_widget.insert(tk.END, "Starting actions for " + clicked_button_label +"!\n")
text_widget.config(state=tk.DISABLED) # Make the widget read-only
# start_t = time.time()
try:
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((host, port))
#client_socket.send(len_trial.encode('utf-8'))
print(f"Connected to server: {host}:{port}")
client_socket.send(data.encode('utf-8'))
except Exception as e:
print(f"An error occurred: {e}")
buffer = ""
data_str = []
received_data = []
tcp_start = time.time()
try:
while time.time() - tcp_start < 600:
data_recv = client_socket.recv(1024)
if not data_recv:
break
buffer += data_recv.decode('utf-8')
# print(buffer)
if "ff" in buffer:
data_split = buffer.split(",")
for item in data_split:
if item == "finished":
received_data.append(data_str)
data_str = []
else:
data_str.append(item)
# print(received_data)
process_and_save_data(received_data, seq_log)
break
except Exception as e:
print(f"Timeout within 5 mins with error: {e}")
# time_used = time.time() - start_t
# print("This block takes", time_used, "seconds!")
client_socket.close()
print("Block finished!")
text_widget.config(state=tk.NORMAL) # Make the widget editable
text_widget.insert(tk.END, clicked_button_label +" finished successfully!\n")
text_widget.config(state=tk.DISABLED) # Make the widget read-only
# text_widget.config(state=tk.NORMAL) # Make the widget editable
# text_widget.insert(tk.END, clicked_button_label +" finished using " + str(time_used), "seconds!\n")
# text_widget.config(state=tk.DISABLED) # Make the widget read-only
def get_current_date():
return datetime.datetime.now().strftime("%Y-%m-%d")
def get_current_time():
return datetime.datetime.now().strftime("%H:%M:%S")
def log_start_time(filename):
current_time = get_current_time()
column_names = ["Trial no.", "Operation time", "Color", "Trajectory", "T/F"]
#print(current_time, column_names)
with open(filename, 'a', newline='') as csvfile:
csv_writer = csv.writer(csvfile)
csv_writer.writerow(['Experiment block start time', current_time])
csv_writer.writerow(column_names)
print("start time logged")
def process_and_save_data(received_data, seq_log):
data_filename = f"data_{get_current_date()}.csv"
# Check if the file exists to avoid permission issues
if not os.path.exists(data_filename):
with open(data_filename, 'w', newline='') as csvfile:
pass # Just create the file
log_start_time(data_filename)
# Assuming the data format is ['name', 'value', 'finished']
for i in range(len(received_data)):
name, value = received_data[i]
color, traj, TF = seq_log[i]
# Convert value to float and divide by 1000
value = float(value) / 1000
data_to_csv=[name,value,color,traj,TF]
#print(data_to_csv)
with open(data_filename, 'a', newline='') as csvfile:
csv_writer = csv.writer(csvfile)
csv_writer.writerow(data_to_csv)
print("data logged")
def seq_radom(num_block, wait_time, text_widget):
seq = gen_seq(num_block)
len_trial = len(seq)
half_trial = int(len_trial/2)
seq_up = seq[0 : half_trial]
seq_up.reverse()
seq_bottom = seq[half_trial : len_trial+1]
seq_bottom.reverse()
custom_print(seq_up, text_widget)
custom_print(seq_bottom, text_widget)
text_widget.config(state=tk.NORMAL) # Make the widget editable
text_widget.insert(tk.END, "Please assemble the cubes based on this placement\n", "yellow")
text_widget.config(state=tk.DISABLED) # Make the widget read-only
log = []
seq_log =[]
bits_list = []
for num in seq:
color = color_map[num]
trajectoryTF = trajectory_map[num]
log.append(color)
if color == "Green":
bits_list.append('z' if trajectoryTF else 'a')
log.append('direct'if trajectoryTF else 'indirect')
else:
bits_list.append('a' if trajectoryTF else 'z')
log.append('indirect'if trajectoryTF else 'direct')
log.append(trajectoryTF)
seq_log.append(log)
log = []
bits = ','.join(bits_list)
data_send = str(len_trial) + "," + bits + "," + str(wait_time)
return data_send, seq_log
def on_button_click(num_block, wait_time, text_widget, button_label, start_button):
global clicked_button_label
clicked_button_label = button_label
text_widget.config(state=tk.NORMAL) # Make the widget editable
# text_widget.delete(1.0, tk.END) # Clear the widget
text_widget.insert(tk.END, "\n")
text_widget.insert(tk.END, "You have selected " + clicked_button_label + " to play!\n")
text_widget.config(state=tk.DISABLED) # Make the widget read-only
data_send, seq_log = seq_radom(num_block, wait_time, text_widget)
text_widget.config(state=tk.NORMAL) # Make the widget editable
text_widget.insert(tk.END, "Press start when you are ready!\n", "yellow")
text_widget.see(tk.END) # Scroll to the bottom
text_widget.config(state=tk.DISABLED) # Make the widget read-only
def start_button_action():
tcp_send_received(data_send, seq_log, text_widget)
start_button.config(text=f"Start {button_label}", command=start_button_action)
start_button.pack(pady=5)
def main():
global start_button
# Create the main window
app = tk.Tk()
app.title("Cobot Malfunction Experiment GUI")
# Create a label to display messages
label = tk.Label(app, text="Choose which block you want to run!")
label.pack(pady=10)
# Create a scrolled text widget for displaying output
text_widget = scrolledtext.ScrolledText(app, wrap=tk.WORD, width=60, height=20)
text_widget.pack(pady=10)
text_widget.tag_configure("green", foreground="white", background="green")
text_widget.tag_configure("red", foreground="white", background="red")
text_widget.tag_configure("yellow", foreground="black", background="yellow")
text_widget.config(state=tk.DISABLED) # Make the widget read-only
text_widget.config(state=tk.NORMAL) # Make the widget editable
text_widget.insert(tk.END, "Please select one block to begin with\n")
text_widget.config(state=tk.DISABLED) # Make the widget read-only
# Create the start button but don't pack it yet
start_button = tk.Button(app, text="")
# Create and place buttons
for params in button_params:
button = tk.Button(app, text=params['text'], command=lambda p=params:on_button_click(p['num_block'], p['wait_time'], text_widget, p['text'], start_button))
button.pack(pady=5)
# Run the application
app.mainloop()
#input("When you are ready placed the cubes, press ENTER")
if __name__ == "__main__":
main()