-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.py
718 lines (624 loc) · 32.7 KB
/
main.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
"""
Script to control the ergocycle through a graphical user interface.
python -m PyQt5.uic.pyuic -x ergocycle_gui.ui -o ergocycle_gui.py
"""
import numpy as np
import os
import sys
import time
from PyQt5 import QtWidgets, QtCore, QtGui
from ergocycleS2M.gui.ergocycle_gui import Ui_MainWindow
from ergocycleS2M.motor_control.enums import (
ControlMode,
DirectionMode,
)
from ergocycleS2M.motor_control.motor import MotorController
# from ergocycleS2M.motor_control.phantom import Phantom
from ergocycleS2M.gui.gui_enums import (
GUIControlMode,
StopwatchStates,
TrainingMode,
)
from ergocycleS2M.gui.gui_utils import (
PlotWidget,
)
class ErgocycleApplication(QtWidgets.QMainWindow):
def __init__(self, odrive_motor):
super(ErgocycleApplication, self).__init__(parent=None)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.motor = odrive_motor
self.motor.zero_position_calibration()
# Plot
self._gui_control_mode = GUIControlMode.POWER
self.plot_power = PlotWidget(self, name="Power", y_label="Power (W)", color="g", show_x_axis=False)
self.ui.power_horizontalLayout.insertWidget(0, self.plot_power)
self.plot_power.getAxis("bottom").setStyle(tickLength=0)
self.plot_cadence = PlotWidget(self, name="Cadence", y_label="Cadence (rpm)", color="r", show_x_axis=False)
self.ui.cadence_horizontalLayout.insertWidget(0, self.plot_cadence)
self.plot_cadence.getAxis("bottom").setStyle(tickLength=0)
self.plot_torque = PlotWidget(self, name="Torque", y_label="Torque (N.m)", color="b")
self.ui.torque_horizontalLayout.insertWidget(0, self.plot_torque)
# Thread for the watchdog, data saving and control
# There is only one thread to control the order of execution of the different tasks since there is only one
# process. Otherwise, the watchdog risks to not be fed in time.
self.motor_thread = MotorDisplayThread(self.ui, odrive_motor)
self.motor_thread.plot_update_signal.connect(self._plot_update)
self.motor_thread.start()
# Colors
self._color_red = QtGui.QColor(255, 150, 150)
self._color_green = QtGui.QColor(150, 255, 150)
self._color_blue = QtGui.QColor(180, 180, 255)
self._color_default = self.ui.angle_reset_pushButton.palette().color(
self.ui.angle_reset_pushButton.backgroundRole()
)
self._color_grey = QtGui.QColor(220, 220, 220)
self.ui.power_label.setStyleSheet(f"background-color: {self._color_grey.name()}")
self.ui.cadence_label.setStyleSheet(f"background-color: {self._color_grey.name()}")
self.ui.torque_label.setStyleSheet(f"background-color: {self._color_grey.name()}")
# Security
self.ui.emergency_pushButton.clicked.connect(self.emergency_stop)
# Modes
# Training mode
self.ui.training_comboBox.addItems([TrainingMode.CONCENTRIC.value, TrainingMode.ECCENTRIC.value])
self.ui.training_comboBox.setCurrentIndex(0)
self.ui.training_comboBox.activated.connect(self._update_instruction_display_on_training_mode_change)
# Control mode
self._update_instruction_display_on_training_mode_change()
self.ui.control_comboBox.activated.connect(self._update_instruction_display_on_control_mode_change)
# Direction of rotation
self.ui.direction_comboBox.addItems([DirectionMode.FORWARD.value, DirectionMode.REVERSE.value])
self.ui.direction_comboBox.setCurrentIndex(0)
self.ui.direction_comboBox.activated.connect(self._set_instruction_to_0)
# Command
self._angle_reset_once = False
self.ui.angle_reset_pushButton.clicked.connect(self._angle_reset)
self.ui.start_update_pushButton.clicked.connect(self._control_update)
self.ui.stop_pushButton.clicked.connect(self._control_stop)
self.ui.stop_pushButton.setEnabled(False)
self.ui.angle_reset_pushButton.setStyleSheet(f"background-color: {self._color_blue.name()}")
# Saving
self.ui.save_lineEdit.textChanged.connect(self._check_text)
self.ui.save_st_pushButton.clicked.connect(self._save_start_stop)
self.ui.save_st_pushButton.setStyleSheet(f"background-color: {self._color_green.name()}")
# Comments
self.ui.comments_save_pushButton.clicked.connect(self._comments_save)
self.ui.comments_save_pushButton.setEnabled(False)
self.ui.comments_lineEdit.setEnabled(False)
# Stopwatch
self._stopwatch_display()
self.ui.stopwatch_start_stop_pushButton.clicked.connect(self._stopwatch_start_stop)
self.ui.stopwatch_lap_reset_pushButton.clicked.connect(self._stopwatch_lap_reset)
self.ui.stopwatch_lcdNumber.setDigitCount(8)
self.ui.lap_lcdNumber.setDigitCount(5)
# Style
self.ui.start_update_pushButton.setStyleSheet(f"background-color: {self._color_green.name()};")
self.ui.errors_label.setStyleSheet(f"font-weight: bold; color: red;")
self.ui.emergency_pushButton.setStyleSheet(f"background-color: red; color: white;")
def emergency_stop(self):
"""
Emergency stop. Stop the motor and close the GUI.
"""
self.motor_thread.run = False
self.close()
def closeEvent(self, event):
"""
Stop the motor on close.
"""
self.motor_thread.run = False
event.accept()
def _check_text(self, text):
"""
Check if the text is correct for a file name.
"""
new_text = ""
for char in text:
if char.isalnum() or char in ("_", "-"):
new_text += char
if new_text != text:
cursor_pos = self.ui.save_lineEdit.cursorPosition()
self.ui.save_lineEdit.setText(new_text)
self.ui.save_lineEdit.setCursorPosition(cursor_pos - 1)
def _update_instruction_display_on_training_mode_change(self):
"""
Update the display accordingly to the training mode.
"""
self._set_instruction_to_0()
training_mode = self.ui.training_comboBox.currentText()
index = self.ui.control_comboBox.currentIndex()
# If there was no precedent index, set the GUIControlMode to POWER.
if index == -1:
index = 0
self.ui.control_comboBox.clear()
if training_mode == TrainingMode.CONCENTRIC.value:
self.ui.control_comboBox.addItems(
[
GUIControlMode.POWER.value,
GUIControlMode.CADENCE.value,
GUIControlMode.LINEAR.value,
GUIControlMode.TORQUE.value,
]
)
self.ui.direction_comboBox.setCurrentText(DirectionMode.FORWARD.value)
elif training_mode == TrainingMode.ECCENTRIC.value:
self.ui.control_comboBox.addItems([GUIControlMode.POWER.value, GUIControlMode.CADENCE.value])
self.ui.direction_comboBox.setCurrentText(DirectionMode.REVERSE.value)
# If the GUIControlMode corresponding to the precedent index was LINEAR or TORQUE, set the GUIControlMode to
# POWER.
if index >= 2:
index = 0
else:
raise NotImplementedError(f"{training_mode} training has not been implemented yet.")
self.ui.control_comboBox.setCurrentIndex(index)
self._update_instruction_display_on_control_mode_change()
def _update_instruction_display_on_control_mode_change(self):
"""
Update the display accordingly to the control mode.
"""
self._set_instruction_to_0()
power_step = 10
vel_step = 10
vel_ramp = 30
torque_step = 1
torque_ramp = 5
linear_step = 0.1
control_mode = self.ui.control_comboBox.currentText()
if control_mode == GUIControlMode.POWER.value:
self.ui.instruction_spinBox.setRange(0, self.motor.hardware_and_security["power_lim"])
self.ui.instruction_spinBox.setSingleStep(power_step)
self.ui.instruction_label.setText("Power instruction")
self.ui.units_label.setText("W")
training_mode = self.ui.training_comboBox.currentText()
if training_mode == TrainingMode.CONCENTRIC.value:
self.ui.acceleration_spinBox.setRange(0, int(self.motor.hardware_and_security["torque_ramp_rate_lim"]))
self.ui.acceleration_spinBox.setSingleStep(torque_step)
self.ui.acceleration_spinBox.setValue(torque_ramp)
self.ui.ramp_label.setText("Torque ramp")
self.ui.acceleration_units_label.setText("N.m/s")
elif training_mode == TrainingMode.ECCENTRIC.value:
self.ui.acceleration_spinBox.setRange(0, int(self.motor.hardware_and_security["pedals_accel_lim"]) - 1)
self.ui.acceleration_spinBox.setSingleStep(vel_step)
self.ui.acceleration_spinBox.setValue(vel_ramp)
self.ui.ramp_label.setText("Cadence ramp")
self.ui.acceleration_units_label.setText("rpm/s")
else:
raise NotImplementedError(f"{training_mode} training has not been implemented yet.")
elif control_mode == GUIControlMode.LINEAR.value:
self.ui.instruction_spinBox.setRange(0, 1.0)
self.ui.acceleration_spinBox.setRange(0, int(self.motor.hardware_and_security["torque_ramp_rate_lim"]))
self.ui.instruction_spinBox.setSingleStep(linear_step)
self.ui.acceleration_spinBox.setSingleStep(torque_step)
self.ui.acceleration_spinBox.setValue(torque_ramp)
self.ui.instruction_label.setText("Linear coefficient")
self.ui.units_label.setText("N.m/rpm")
self.ui.ramp_label.setText("Torque ramp")
self.ui.acceleration_units_label.setText("N.m/s")
elif control_mode == GUIControlMode.CADENCE.value:
self.ui.instruction_spinBox.setRange(0, self.motor.hardware_and_security["pedals_vel_limit"] - 1)
self.ui.acceleration_spinBox.setRange(0, self.motor.hardware_and_security["pedals_accel_lim"] - 1)
self.ui.instruction_spinBox.setSingleStep(vel_step)
self.ui.acceleration_spinBox.setSingleStep(vel_step)
self.ui.acceleration_spinBox.setValue(vel_ramp)
self.ui.instruction_label.setText("Cadence instruction")
self.ui.units_label.setText("rpm")
self.ui.ramp_label.setText("Cadence ramp")
self.ui.acceleration_units_label.setText("rpm/s")
elif control_mode == GUIControlMode.TORQUE.value:
self.ui.instruction_spinBox.setRange(0, int(self.motor.hardware_and_security["torque_lim"] - 1))
self.ui.acceleration_spinBox.setRange(0, int(self.motor.hardware_and_security["torque_ramp_rate_lim"]))
self.ui.instruction_spinBox.setSingleStep(torque_step)
self.ui.acceleration_spinBox.setSingleStep(torque_step)
self.ui.acceleration_spinBox.setValue(torque_ramp)
self.ui.instruction_label.setText("Torque instruction")
self.ui.units_label.setText("N.m")
self.ui.ramp_label.setText("Torque ramp")
self.ui.acceleration_units_label.setText("N.m/s")
else:
raise NotImplementedError(f"{control_mode} control has not been implemented yet.")
def _set_instruction_to_0(self):
"""
Set the instruction to 0.
"""
self.ui.instruction_spinBox.setValue(0)
def _angle_reset(self):
"""
Reset the angle to 0.
"""
self.motor_thread.motor.zero_position_calibration()
self._angle_reset_once = True
self.ui.angle_reset_pushButton.setStyleSheet(f"background-color: {self._color_default.name()}")
def _control_update(self):
"""
Start or update the control depending on the control mode and the training mode.
"""
# If the motor is not started: change the display, get the control and training modes and set the direction.
if not self.motor_thread.motor_started:
if not self._angle_reset_once:
self._angle_reset()
self._control_display()
self._plot_add_instruction()
self.motor_thread.training_mode = self.ui.training_comboBox.currentText()
self.motor_thread.plot_start_time = time.time()
self.motor_thread.time_array = np.linspace(
-self.motor_thread.size_arrays / self.motor_thread.plot_frequency, 0, self.motor_thread.size_arrays
)
# Update instructions and the control depending on the control mode.
self.motor_thread.ramp_instruction = self.ui.acceleration_spinBox.value()
if self._gui_control_mode == GUIControlMode.POWER:
if self._training_mode == TrainingMode.CONCENTRIC.value:
self.motor_thread.spin_box = self.ui.instruction_spinBox.value()
self.motor_thread.instruction = self.motor.concentric_power_control(
self.motor_thread.spin_box, self.motor_thread.ramp_instruction
)
elif self._training_mode == TrainingMode.ECCENTRIC.value:
# In eccentric mode, the sign is inverted because the user's power is negative
self.motor_thread.spin_box = -self.ui.instruction_spinBox.value()
self.motor_thread.instruction = self.motor.eccentric_power_control(
self.motor_thread.spin_box, self.motor_thread.ramp_instruction
)
else:
raise NotImplementedError(f"{self._training_mode} training has not been implemented yet.")
elif self._gui_control_mode == GUIControlMode.LINEAR:
self.motor_thread.spin_box = self.ui.instruction_spinBox.value()
self.motor_thread.instruction = self.motor.linear_control(
self.motor_thread.spin_box, self.motor_thread.ramp_instruction
)
elif self._gui_control_mode == GUIControlMode.CADENCE:
self.motor_thread.instruction = self.motor.get_sign() * self.ui.instruction_spinBox.value()
self.motor_thread.spin_box = self.motor_thread.instruction
self.motor.cadence_control(self.motor_thread.spin_box, self.motor_thread.ramp_instruction)
elif self._gui_control_mode == GUIControlMode.TORQUE:
self.motor_thread.spin_box = self.motor.get_sign() * self.ui.instruction_spinBox.value()
self.motor_thread.instruction = self.motor.torque_control(
self.motor_thread.spin_box, self.motor_thread.ramp_instruction
)
else:
raise NotImplementedError(f"{self._gui_control_mode} control has not been implemented yet.")
def _control_stop(self):
"""
Start the stopping procedure and adapt the GUI accordingly.
"""
ramp_instruction = self.motor_thread.ramp_instruction
self._control_display()
self._plot_remove_instruction()
self.ui.start_update_pushButton.setEnabled(False)
self.motor_thread.instruction = 0.0
self.motor_thread.spin_box = 0.0
self.motor_thread.ramp_instruction = 0.0
# If the motor is based on cadence control, the ramp is in rpm/s. It can be given to motor.stopping(),
# else it won't be used. Either way it is protected by the min() function.
self.motor_thread.stopping = True
self.motor_thread.stopping_ramp_instruction = ramp_instruction
def _control_display(self):
"""
Change the display when starting or stopping the motor.
If starting the motor get the control and training modes and set the direction.
"""
self.motor_thread.motor_started = not self.motor_thread.motor_started
self.ui.training_comboBox.setEnabled(not self.motor_thread.motor_started)
self.ui.control_comboBox.setEnabled(not self.motor_thread.motor_started)
self.ui.direction_comboBox.setEnabled(not self.motor_thread.motor_started)
self.ui.stop_pushButton.setEnabled(self.motor_thread.motor_started)
if self.motor_thread.motor_started:
self._gui_control_mode = self.ui.control_comboBox.currentText()
self._training_mode = self.ui.training_comboBox.currentText()
self.motor.set_direction(self.ui.direction_comboBox.currentText())
self.ui.start_update_pushButton.setText("Update")
self.ui.start_update_pushButton.setStyleSheet(f"background-color: {self._color_blue.name()};")
self.ui.stop_pushButton.setStyleSheet(f"background-color: {self._color_red.name()};")
self.motor_thread.motor_started = True
else:
self.ui.start_update_pushButton.setText("Start")
self.ui.start_update_pushButton.setStyleSheet(f"background-color: {self._color_green.name()};")
self.ui.stop_pushButton.setStyleSheet(f"background-color: {self._color_default.name()};")
self.motor_thread.motor_started = False
def _save_start_stop(self):
"""
Start or stop saving the data to a file.
"""
# Choosing the file name at the beginning of the saving.
self.motor_thread.file_name = self.ui.save_lineEdit.text()
ext = ".bio"
if os.path.isfile(f"{self.motor_thread.file_name}{ext}"):
# File already exists, add a suffix to the filename
i = 1
while os.path.isfile(f"{self.motor_thread.file_name}_{i}{ext}"):
i += 1
self.motor_thread.file_name = f"{self.motor_thread.file_name}_{i}"
self.motor_thread.saving = not self.motor_thread.saving
self.ui.save_lineEdit.setEnabled(not self.motor_thread.saving)
self.ui.comments_save_pushButton.setEnabled(self.motor_thread.saving)
self.ui.comments_lineEdit.setEnabled(self.motor_thread.saving)
if self.motor_thread.saving:
self.ui.save_st_pushButton.setText("Stop saving")
self.ui.save_st_pushButton.setStyleSheet(f"background-color: {self._color_red.name()}")
self.ui.comments_save_pushButton.setStyleSheet(f"background-color: {self._color_green.name()}")
else:
self.ui.save_st_pushButton.setText("Start saving")
self.ui.save_st_pushButton.setStyleSheet(f"background-color: {self._color_green.name()}")
self.ui.comments_save_pushButton.setStyleSheet(f"background-color: {self._color_default.name()}")
def _comments_save(self):
"""
Indicates that the comment needs to be saved and clear the comment line edit.
"""
self.motor_thread.comment_to_save = True
self.motor_thread.comment = self.ui.comments_lineEdit.text()
self.ui.comments_lineEdit.setText("")
def _stopwatch_start_stop(self):
"""
Start, stop or pause the stopwatch.
"""
if self.motor_thread.stopwatch_state == StopwatchStates.PAUSED:
self.motor_thread.stopwatch_state = StopwatchStates.RUNNING
self.motor_thread.stopwatch_start_time += time.time() - self.motor_thread.stopwatch_pause_time
self.motor_thread.stopwatch_lap_time += time.time() - self.motor_thread.stopwatch_pause_time
elif self.motor_thread.stopwatch_state == StopwatchStates.RUNNING:
self.motor_thread.stopwatch_state = StopwatchStates.PAUSED
self.motor_thread.stopwatch_pause_time = time.time()
elif self.motor_thread.stopwatch_state == StopwatchStates.STOPPED:
self.motor_thread.stopwatch_state = StopwatchStates.RUNNING
self.motor_thread.stopwatch_start_time = time.time()
self.motor_thread.stopwatch_lap_time = time.time()
self._stopwatch_display()
def _stopwatch_lap_reset(self):
"""
Reset the stopwatch if it is paused, otherwise, save the lap time.
"""
if self.motor_thread.stopwatch_state == StopwatchStates.RUNNING:
self.motor_thread.stopwatch_lap_time = time.time()
elif self.motor_thread.stopwatch_state == StopwatchStates.PAUSED:
self.motor_thread.stopwatch_state = StopwatchStates.STOPPED
self._stopwatch_display()
def _stopwatch_display(self):
"""
Update the stopwatch display accordingly to the stopwatch state.
"""
if self.motor_thread.stopwatch_state == StopwatchStates.PAUSED:
self.ui.stopwatch_lap_reset_pushButton.setText("Reset")
self.ui.stopwatch_start_stop_pushButton.setText("Start")
self.ui.stopwatch_start_stop_pushButton.setStyleSheet(f"background-color: {self._color_green.name()}")
elif self.motor_thread.stopwatch_state == StopwatchStates.RUNNING:
self.ui.stopwatch_lap_reset_pushButton.setEnabled(True)
self.ui.stopwatch_lap_reset_pushButton.setText("Lap")
self.ui.stopwatch_start_stop_pushButton.setText("Stop")
self.ui.stopwatch_lap_reset_pushButton.setStyleSheet(f"background-color: {self._color_blue.name()}")
self.ui.stopwatch_start_stop_pushButton.setStyleSheet(f"background-color: {self._color_red.name()}")
elif self.motor_thread.stopwatch_state == StopwatchStates.STOPPED:
self.ui.stopwatch_lap_reset_pushButton.setEnabled(False)
self.ui.stopwatch_lap_reset_pushButton.setText("Lap")
self.ui.stopwatch_start_stop_pushButton.setText("Start")
self.ui.stopwatch_lap_reset_pushButton.setStyleSheet(f"background-color: {self._color_default.name()}")
self.ui.stopwatch_start_stop_pushButton.setStyleSheet(f"background-color: {self._color_green.name()}")
def _plot_add_instruction(self):
"""
Add an instruction to the plot.
"""
if self._gui_control_mode == GUIControlMode.POWER:
self.plot_power.add_instruction()
elif self._gui_control_mode == GUIControlMode.CADENCE:
self.plot_cadence.add_instruction()
elif self._gui_control_mode == GUIControlMode.TORQUE:
self.plot_torque.add_instruction()
def _plot_remove_instruction(self):
"""
Remove the instruction from the plot.
"""
if self._gui_control_mode == GUIControlMode.POWER:
self.plot_power.remove_instruction()
elif self._gui_control_mode == GUIControlMode.CADENCE:
self.plot_cadence.remove_instruction()
elif self._gui_control_mode == GUIControlMode.TORQUE:
self.plot_torque.remove_instruction()
def _plot_update(self):
"""
Update the plot with the new data.
"""
power_spin_box_array = None
cadence_spin_box_array = None
torque_spin_box_array = None
if self._gui_control_mode == GUIControlMode.POWER:
power_spin_box_array = self.motor_thread.spin_box_array
elif self._gui_control_mode == GUIControlMode.CADENCE:
cadence_spin_box_array = self.motor_thread.spin_box_array
elif self._gui_control_mode == GUIControlMode.TORQUE:
torque_spin_box_array = self.motor_thread.spin_box_array
self.plot_power.update_plot(
self.motor_thread.time_array,
self.motor_thread.power_array,
power_spin_box_array,
)
self.plot_cadence.update_plot(
self.motor_thread.time_array,
self.motor_thread.cadence_array,
cadence_spin_box_array,
)
self.plot_torque.update_plot(
self.motor_thread.time_array,
self.motor_thread.torque_array,
torque_spin_box_array,
)
class MotorDisplayThread(QtCore.QThread):
"""
Thread that controls the motor. It is separated from the GUI thread to avoid freezing the GUI when the motor is
running.
"""
plot_update_signal = QtCore.pyqtSignal(name="plot_update_signal")
def __init__(self, ui: Ui_MainWindow, odrive_motor):
super(MotorDisplayThread, self).__init__(parent=None)
self.ui = ui
self.motor = odrive_motor
# Security
self.run = True
# Control
self.motor_started = False
# Saving
self.instruction = 0.0
self.ramp_instruction = 0.0
self.spin_box = 0.0
self.training_mode = self.ui.training_comboBox.currentText()
# Comments
self.comment_to_save = False
self.comment = ""
# Stopwatch
self.stopwatch_start_time = 0.0
self.stopwatch_pause_time = 0.0
self.stopwatch_lap_time = 0.0
self.stopwatch_state = StopwatchStates.STOPPED
self.stopwatch = 0.0
self.lap = 0.0
# Data
self._display_frequency = 4 # Hz
self._save_frequency = 5 # Hz
# Plot
self.plot_start_time = 0.0
self.plot_frequency = 2 # Hz
self.size_arrays = 10 * self.plot_frequency # 10 seconds
self.time_array = np.linspace(-self.size_arrays / self.plot_frequency, 0, self.size_arrays)
self.cadence_array = np.zeros(self.size_arrays)
self.torque_array = np.zeros(self.size_arrays)
self.power_array = np.zeros(self.size_arrays)
self.spin_box_array = None
# Watchdog
self.watchdog_prev = time.time()
self.dt = []
# Saving
self.saving = False
self.file_name = ""
# Stopping
self.stopping = False
self.stopping_ramp_instruction = 30.0
def watchdog_feed(self):
"""
Feed the watchdog of the motor.
"""
t = time.time()
self.dt.append(t - self.watchdog_prev)
self.watchdog_prev = t
self.motor.watchdog_feed()
def run(self):
"""
Main loop of the thread. It is called when the thread is started. It is stopped when the thread is stopped.
It updates the command and the display, saves the data and feeds the watchdog.
"""
t_plot_precedent = t_display_precedent = time.time()
self.plot_start_time = time.time()
date_time = QtCore.QDateTime()
while self.run:
self.watchdog_feed()
if self.saving:
# Save data
if self.comment_to_save:
comment = self.comment
self.comment_to_save = False
else:
comment = ""
self.motor.minimal_save_data_to_file(
self.file_name,
spin_box=self.spin_box,
instruction=self.instruction,
ramp_instruction=self.ramp_instruction,
comment=comment,
stopwatch=self.stopwatch,
lap=self.lap,
training_mode=self.training_mode,
)
self.watchdog_feed()
# Date
current_time = date_time.currentDateTime().toString("yyyy-MM-dd hh:mm:ss")
self.ui.date_label.setText(current_time)
# Stopwatch
if self.stopwatch_state == StopwatchStates.RUNNING:
self.stopwatch = time.time() - self.stopwatch_start_time
self.lap = time.time() - self.stopwatch_lap_time
elif self.stopwatch_state == StopwatchStates.PAUSED:
self.stopwatch = self.stopwatch_pause_time - self.stopwatch_start_time
self.lap = self.stopwatch_pause_time - self.stopwatch_lap_time
elif self.stopwatch_state == StopwatchStates.STOPPED:
self.stopwatch = 0.0
self.lap = 0.0
minutes = int(self.stopwatch // 60) # get the integer part of the quotient
seconds = int(self.stopwatch % 60) # get the integer part of the remainder
milliseconds = int((self.stopwatch - int(self.stopwatch)) * 100) # get the milliseconds component
self.ui.stopwatch_lcdNumber.display(f"{minutes:02d}:{seconds:02d}.{milliseconds:02d}")
minutes = int(self.lap // 60) # get the integer part of the quotient
seconds = int(self.lap % 60) # get the integer part of the remainder
self.ui.lap_lcdNumber.display(f"{minutes:02d}:{seconds:02d}")
self.watchdog_feed()
# Display data
t_since_precedent_display = time.time() - t_display_precedent
if t_since_precedent_display > 1 / self._display_frequency:
self.ui.current_power_display.setText(f"{self.motor.get_user_power():.0f} W")
self.ui.average_power_display.setText(f"{np.mean(self.power_array):.0f} W")
self.ui.current_cadence_display.setText(f"{self.motor.get_cadence():.0f} rpm")
self.ui.average_cadence_display.setText(f"{np.mean(self.cadence_array):.0f} rpm")
self.ui.current_torque_display.setText(f"{self.motor.get_user_torque():.0f} N.m")
self.ui.average_torque_display.setText(f"{np.mean(self.torque_array):.0f} N.m")
self.ui.turns_display.setText(f"{self.motor.get_turns():.0f} tr")
self.ui.angle_display.setText(f"{self.motor.get_angle():.0f} °")
t_display_precedent = time.time()
self.ui.errors_label.setText(self.motor.get_errors())
self.watchdog_feed()
if not self.stopping:
# Adapt the control of the motor accordingly to the current cadence and torque
control_mode = self.motor.get_control_mode()
# If the motor is in torque control, the torque input needs to be updated in function of the cadence
# because of the resisting torque.
# Furthermore, it allows to stop the pedals by reducing the torque if the user has stopped.
if control_mode == ControlMode.TORQUE_CONTROL:
self.instruction = self.motor.torque_control(self.spin_box, self.ramp_instruction)
# The concentric power control mode is based on the torque control mode, but the torque input is calculated
# from the current cadence (torque_input = f(power / cadence, resiting torque)).
elif control_mode == ControlMode.CONCENTRIC_POWER_CONTROL:
self.instruction = self.motor.concentric_power_control(self.spin_box, self.ramp_instruction)
# The linear control mode is based on the torque control mode, but the torque input is calculated from the
# current cadence (torque_input = linear_coeff * cadence and resiting torque).
elif control_mode == ControlMode.LINEAR_CONTROL:
self.instruction = self.motor.linear_control(self.spin_box, self.ramp_instruction)
# The concentric power control mode is based on the cadence control mode, but the cadence input is
# calculated from the current torque (cadence_input = f(power / torque, resiting torque)).
elif control_mode == ControlMode.ECCENTRIC_POWER_CONTROL:
self.instruction = self.motor.eccentric_power_control(self.spin_box, self.ramp_instruction)
else:
self.motor.stopping(cadence_ramp_rate=self.stopping_ramp_instruction)
if abs(self.motor.get_cadence()) < 10.0:
self.stopping = not self.motor.stopped()
self.ui.start_update_pushButton.setEnabled(True)
self.watchdog_feed()
# Plot data
t_since_precedent_plot = time.time() - t_plot_precedent
if t_since_precedent_plot > 1 / self.plot_frequency:
self.time_array = np.roll(self.time_array, -1)
self.time_array[-1] = time.time() - self.plot_start_time
self.cadence_array = np.roll(self.cadence_array, -1)
self.cadence_array[-1] = cadence = self.motor.get_cadence()
self.torque_array = np.roll(self.torque_array, -1)
self.torque_array[-1] = torque = self.motor.get_user_torque()
self.power_array = np.roll(self.power_array, -1)
self.power_array[-1] = self.motor.compute_user_power(torque, cadence)
if self.motor_started:
if self.spin_box_array is None:
self.spin_box_array = np.zeros(self.size_arrays)
self.spin_box_array = np.roll(self.spin_box_array, -1)
self.spin_box_array[-1] = self.spin_box
else:
self.spin_box_array = None
self.plot_update_signal.emit()
t_plot_precedent = time.time()
def main():
"""
Main function to run the application.
"""
motor = MotorController(enable_watchdog=True, external_watchdog=True)
app = QtWidgets.QApplication(sys.argv)
gui = ErgocycleApplication(motor)
gui.show()
gui.motor.config_watchdog(True, 0.3)
app.exec()
app.run = False
dt = np.asarray(gui.motor_thread.dt)
import matplotlib.pyplot as plt
plt.plot(dt)
plt.show()
print(np.mean(dt), np.max(dt))
if __name__ == "__main__":
main()