forked from andreww5au/teljoy
/
controller.py
executable file
·1357 lines (1038 loc) · 42.7 KB
/
controller.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/local/bin/python2.7
# coding=latin1
# Copyright © Bit Plantation Pty Ltd (ACN 152 088 634). All Rights Reserved.
# This file is internal, confidential source code and is protected by
# trade secret and copyright laws.
import select, struct, time, math, heapq, sys
import usb1, libusb1
from twisted.internet import defer
from twisted.python import failure
module_version = (0, 7, 1)
# These are workarounds for omissions or bugs in python-libusb1; the author
# of the library has been notified about them:
class _patched_Poller(object):
def __init__(self, poller):
self._poller = poller
def register(self, fd, event_flags):
self._poller.register(fd, event_flags)
def unregister(self, fd):
self._poller.unregister(fd)
def poll(self, timeout_in_seconds):
if timeout_in_seconds is not None:
self._poller.poll(int(math.ceil(timeout_in_seconds * 1000)))
else:
self._poller.poll(None)
assert getattr(usb1.USBTransfer, "getUserData") is not None, \
"A newer version of the python-libusb1 library is required."
TC_ISSUE_STATE_COMMAND = 0x00
TC_GET_VERSION = 0x01
TC_MC_CONFIGURE = 0x02
TC_GPIO_CONFIGURE = 0x03
TC_SAFETY_CONFIGURE = 0x04
TC_WRITE_OUTPUTS = 0x05
TC_ENQUEUE = 0x06
TC_GET_COUNTERS = 0x07
TC_GET_DEBUG_REGISTERS = 0x08
TC_SET_GUIDER_VALUES = 0x09
TC_GET_GUIDER_RESULT = 0x0a
TC_GET_EXCEPTION_DETAILS_LENGTH = 0x0b
TC_GET_EXCEPTION_DETAILS = 0x0c
TC_GET_EXCEPTION = 0x0d
TC_CLEAR_EXCEPTION = 0x0e
TC_STATE_COMMAND_SHUTDOWN = 0x01
TC_STATE_COMMAND_RESET_IO = 0x02
TC_STATE_COMMAND_ENABLE_GUIDER = 0x03
TC_STATE_COMMAND_DISABLE_GUIDER = 0x04
TC_STATE_COMMAND_FORCE_INTERRUPT = 0x05
TC_STATE_COMMAND_HARDWARE_RESET = 0x06
TC_STATE_COMMAND_FORCE_HARDWARE_RESET = 0x07
TC_STATE_IDLE = 0x00
TC_STATE_RUNNING = 0x01
TC_STATE_STOPPING = 0x02
TC_STATE_EXCEPTION = 0x03
TC_EXCEPTION_NONE = 0x00000000
TC_EXCEPTION_QUEUE_UNDERFLOW = 0x00000001
TC_EXCEPTION_QUEUE_NONSEQUENTIAL_FRAME_NUMBER = 0x00000002
TC_EXCEPTION_ACCELERATION_LIMIT_EXCEEDED = 0x00000003
TC_EXCEPTION_VELOCITY_LIMIT_EXCEEDED = 0x00000004
TC_EXCEPTION_DIRECTION_CHANGE_AT_NONZERO_VELOCITY = 0x00000005
TC_EXCEPTION_SHUTDOWN_REQUESTED = 0x00000006
TC_EXCEPTION_INVALID_CONFIGURATION = 0x00000007
TC_EXCEPTION_INTERNAL_UNDERRUN = 0x00000008
TC_EXCEPTION_INTERNAL_ERROR = 0x00000009
TC_EXCEPTION_MCA_POSITIVE_LIMITED = 0x0000000a
TC_EXCEPTION_MCA_NEGATIVE_LIMITED = 0x0000000b
TC_EXCEPTION_MCB_POSITIVE_LIMITED = 0x0000000c
TC_EXCEPTION_MCB_NEGATIVE_LIMITED = 0x0000000d
TC_EXCEPTION_QUEUE_INTERRUPT_UNEXPECTED = 0x0000000e
TC_EXCEPTION_INVALID_FPGA_EXCEPTION_BITMAP = 0x0000000f
TC_EXCEPTION_IO_SUPPLY_ERROR = 0x00000010
TC_EXCEPTION_STEP_COMPUTATION_OVERFLOW = 0x00000011
TC_EXCEPTION_SHUTDOWN_INPUT_TRIGGERED = 0x00000012
TC_EXCEPTION_UNEXPECTED_FPGA_RESET = 0x00000013
TC_EXCEPTION_FPGA_READBACK_ERROR = 0x00000014
TC_EXCEPTION_UNEXPECTED_STEPPER_STOP = 0x00000015
TC_EXCEPTION_CLEARING_EXCEPTION_FAILED = 0x00000016
clearable_exceptions = [ \
TC_EXCEPTION_QUEUE_UNDERFLOW,
TC_EXCEPTION_SHUTDOWN_REQUESTED,
TC_EXCEPTION_MCA_POSITIVE_LIMITED,
TC_EXCEPTION_MCA_NEGATIVE_LIMITED,
TC_EXCEPTION_MCB_POSITIVE_LIMITED,
TC_EXCEPTION_MCB_NEGATIVE_LIMITED,
TC_EXCEPTION_SHUTDOWN_INPUT_TRIGGERED]
TC_DETAIL_KIND_AXIS_TRACE = 0x00000001
TC_DETAIL_KIND_FPGA_ERRORS = 0x00000002
PIN_GPIO_0 = 0
PIN_GPIO_1 = 1
PIN_GPIO_2 = 2
PIN_GPIO_3 = 3
PIN_GPIO_4 = 4
PIN_GPIO_5 = 5
PIN_GPIO_6 = 6
PIN_GPIO_7 = 7
PIN_GPIO_8 = 8
PIN_GPIO_9 = 9
PIN_GPIO_10 = 10
PIN_GPIO_11 = 11
PIN_GPIO_12 = 12
PIN_GPIO_13 = 13
PIN_GPIO_14 = 14
PIN_GPIO_15 = 15
PIN_GPIO_16 = 16
PIN_GPIO_17 = 17
PIN_GPIO_18 = 18
PIN_GPIO_19 = 19
PIN_GPIO_20 = 20
PIN_GPIO_21 = 21
PIN_GPIO_22 = 22
PIN_GPIO_23 = 23
PIN_GPIO_24 = 24
PIN_GPIO_25 = 25
PIN_GPIO_26 = 26
PIN_GPIO_27 = 27
PIN_GPIO_28 = 28
PIN_GPIO_29 = 29
PIN_GPIO_30 = 30
PIN_GPIO_31 = 31
PIN_GPIO_32 = 32
PIN_GPIO_33 = 33
PIN_GPIO_34 = 34
PIN_GPIO_35 = 35
PIN_GPIO_36 = 36
PIN_GPIO_37 = 37
PIN_GPIO_38 = 38
PIN_GPIO_39 = 39
PIN_GPIO_40 = 40
PIN_GPIO_41 = 41
PIN_GPIO_42 = 42
PIN_GPIO_43 = 43
PIN_GPIO_44 = 44
PIN_GPIO_45 = 45
PIN_GPIO_46 = 46
PIN_GPIO_47 = 47
PIN_MCA_SP = 48
PIN_MCA_SN = 49
PIN_MCA_DP = 50
PIN_MCA_DN = 51
PIN_MCA_OP = 52
PIN_MCA_ON = 53
PIN_MCB_SP = 54
PIN_MCB_SN = 55
PIN_MCB_DP = 56
PIN_MCB_DN = 57
PIN_MCB_OP = 58
PIN_MCB_ON = 59
PIN_MCA_QA = 60
PIN_MCA_QB = 61
PIN_MCB_QA = 62
PIN_MCB_QB = 63
TC_MC_UNUSED_INPUT = 0xff
MC_PIN_FLAG_INVERT_MCA_SP = (1 << 0)
MC_PIN_FLAG_INVERT_MCA_SN = (1 << 1)
MC_PIN_FLAG_INVERT_MCA_DP = (1 << 2)
MC_PIN_FLAG_INVERT_MCA_DN = (1 << 3)
MC_PIN_FLAG_INVERT_MCA_OP = (1 << 4)
MC_PIN_FLAG_INVERT_MCA_ON = (1 << 5)
MC_PIN_FLAG_INVERT_MCB_SP = (1 << 6)
MC_PIN_FLAG_INVERT_MCB_SN = (1 << 7)
MC_PIN_FLAG_INVERT_MCB_DP = (1 << 8)
MC_PIN_FLAG_INVERT_MCB_DN = (1 << 9)
MC_PIN_FLAG_INVERT_MCB_OP = (1 << 10)
MC_PIN_FLAG_INVERT_MCB_ON = (1 << 11)
MC_PIN_FLAG_MCA_O_FUNCTION_LOW = (0 << 12)
MC_PIN_FLAG_MCA_O_FUNCTION_HIGH = (1 << 12)
MC_PIN_FLAG_MCA_O_FUNCTION_RUNNING = (2 << 12)
MC_PIN_FLAG_MCA_O_FUNCTION_FRAME_CLOCK = (3 << 12)
MC_PIN_FLAG_MCB_O_FUNCTION_LOW = (0 << 14)
MC_PIN_FLAG_MCB_O_FUNCTION_HIGH = (1 << 14)
MC_PIN_FLAG_MCB_O_FUNCTION_RUNNING = (2 << 14)
MC_PIN_FLAG_MCB_O_FUNCTION_FRAME_CLOCK = (3 << 14)
GUIDER_RUN_AT_NEXT_AVAILABLE_FRAME = 1
GUIDER_RUN_AT_FRAME = 2
GUIDER_RUN_AT_NOT_BEFORE_FRAME = 3
fpga_control_bit_descriptions = [ \
"CONTROL_BIT_ENABLE_MC", \
"CONTROL_BIT_ENABLE_IO", \
"CONTROL_BIT_ERRORS_PENDING", \
"CONTROL_BIT_INPUTS_CHANGED", \
"CONTROL_BIT_SLOTS_EMPTY", \
"CONTROL_BIT_SLOTS_EMPTIED", \
"CONTROL_BIT_INDICATOR_BITS_CHANGED", \
"CONTROL_BIT_ERRORS_CHANGED", \
"CONTROL_BIT_POWERED_ON", \
"CONTROL_BIT_IO_READY", \
"CONTROL_BIT_CONFIGURED"]
fpga_error_bit_descriptions = [ \
"ERROR_BIT_MCA_S_CONFIGURATION", \
"ERROR_BIT_MCA_D_CONFIGURATION", \
"ERROR_BIT_MCA_O_CONFIGURATION", \
"ERROR_BIT_MCB_S_CONFIGURATION", \
"ERROR_BIT_MCB_D_CONFIGURATION", \
"ERROR_BIT_MCB_O_CONFIGURATION", \
"ERROR_BIT_MCA_Q_CONFIGURATION", \
"ERROR_BIT_MCB_Q_CONFIGURATION", \
"ERROR_BIT_MC_SYNCHRONISATION_LOSS", \
"ERROR_BIT_MCA_SLOTS_OVERUN", \
"ERROR_BIT_MCA_SLOTS_UNDERRUN", \
"ERROR_BIT_MCB_SLOTS_OVERUN", \
"ERROR_BIT_MCB_SLOTS_UNDERRUN", \
"ERROR_BIT_IO_SUPPLY_ERROR", \
"ERROR_BIT_REGISTERS_MISO_UNDERRUN", \
"ERROR_BIT_IO_SPI_OVERRUN", \
"ERROR_BIT_MCA_POSITIVE_LIMITED", \
"ERROR_BIT_MCA_NEGATIVE_LIMITED", \
"ERROR_BIT_MCB_POSITIVE_LIMITED", \
"ERROR_BIT_MCB_NEGATIVE_LIMITED", \
"ERROR_BIT_ISOLATOR_ERROR", \
"ERROR_BIT_CONFIGURATION_LOCK_ERROR", \
"ERROR_BIT_SHUTDOWN_INPUT_TRIGGERED", \
"ERROR_BIT_SHUTDOWN_TIMEOUT_EXCEEDED", \
"ERROR_BIT_ERROR_CLEARING_ERROR", \
"ERROR_BIT_LAST"]
exception_descriptions = [ \
"TC_EXCEPTION_NONE", \
"TC_EXCEPTION_QUEUE_UNDERFLOW", \
"TC_EXCEPTION_QUEUE_NONSEQUENTIAL_FRAME_NUMBER", \
"TC_EXCEPTION_ACCELERATION_LIMIT_EXCEEDED", \
"TC_EXCEPTION_VELOCITY_LIMIT_EXCEEDED", \
"TC_EXCEPTION_DIRECTION_CHANGE_AT_NONZERO_VELOCITY", \
"TC_EXCEPTION_SHUTDOWN_REQUESTED", \
"TC_EXCEPTION_INVALID_CONFIGURATION", \
"TC_EXCEPTION_INTERNAL_UNDERRUN", \
"TC_EXCEPTION_INTERNAL_ERROR", \
"TC_EXCEPTION_MCA_POSITIVE_LIMITED", \
"TC_EXCEPTION_MCA_NEGATIVE_LIMITED", \
"TC_EXCEPTION_MCB_POSITIVE_LIMITED", \
"TC_EXCEPTION_MCB_NEGATIVE_LIMITED", \
"TC_EXCEPTION_QUEUE_INTERRUPT_UNEXPECTED", \
"TC_EXCEPTION_INVALID_FPGA_EXCEPTION_BITMAP", \
"TC_EXCEPTION_IO_SUPPLY_ERROR", \
"TC_EXCEPTION_STEP_COMPUTATION_OVERFLOW", \
"TC_EXCEPTION_SHUTDOWN_INPUT_TRIGGERED", \
"TC_EXCEPTION_UNEXPECTED_FPGA_RESET", \
"TC_EXCEPTION_FPGA_READBACK_ERROR", \
"TC_EXCEPTION_UNEXPECTED_STEPPER_STOP", \
"TC_EXCEPTION_CLEARING_EXCEPTION_FAILED"]
CONTROLLER_PIN_INPUT = 0
CONTROLLER_PIN_OUTPUT = 1
CONTROLLER_PIN_FUNCTION_GPIO = 0
CONTROLLER_PIN_FUNCTION_SPECIAL = 1
class ControllerPin(object):
def __init__(self, number):
self.number = number
self.direction = CONTROLLER_PIN_INPUT
self.function = CONTROLLER_PIN_FUNCTION_GPIO
self.invert_input = False
self.report_input = False
class ControllerException(Exception):
pass
class ControllerUsageException(Exception):
pass
class ControllerVersionException(Exception):
pass
class ControllerConfigurationException(ControllerException):
pass
class ControllerNotConnectedException(ControllerException):
pass
class MultipleControllersConnectedException(ControllerException):
pass
class InterruptTransferFailedException(ControllerException):
pass
class ControllerConfiguration(object):
def __init__(self, controller):
self._controller = controller
self.mc_prefill_frames = 8
self.mc_pin_flags = 0
self.mc_a_shutdown_acceleration = 0
self.mc_b_shutdown_acceleration = 0
self.mc_a_acceleration_limit = 500
self.mc_b_acceleration_limit = 500
self.mc_a_velocity_limit = 7600
self.mc_b_velocity_limit = 7600
self.mc_frame_period = 1200000
self.mc_pulse_width = 120
self.mc_pulse_minimum_off_time = None
self.mc_a_positive_limit_input = None
self.mc_a_negative_limit_input = None
self.mc_b_positive_limit_input = None
self.mc_b_negative_limit_input = None
self.mc_a_positive_guider_input = None
self.mc_a_negative_guider_input = None
self.mc_b_positive_guider_input = None
self.mc_b_negative_guider_input = None
self.mc_guider_counter_divider = 12000
self.mc_guider_a_numerator = 1
self.mc_guider_a_denominator = 10
self.mc_guider_a_limit = 20
self.mc_guider_b_numerator = 1
self.mc_guider_b_denominator = 10
self.mc_guider_b_limit = 20
self.shutdown_0_input = None
self.shutdown_1_input = None
self.shutdown_2_input = None
self.shutdown_3_input = None
self.pins = []
for i in range(64):
self.pins.append(ControllerPin(i))
def _validate(self):
if self.mc_prefill_frames < 2:
raise ControllerConfigurationException( \
"The mc_prefill_frames property can not be less than two.")
if self.mc_a_shutdown_acceleration < 1:
raise ControllerConfigurationException( \
"The mc_a_shutdown_acceleration property must be greater than zero.")
if self.mc_b_shutdown_acceleration < 1:
raise ControllerConfigurationException( \
"The mc_b_shutdown_acceleration property must be greater than zero.")
if self.mc_frame_period < self._controller.clock_frequency / 100:
raise ControllerConfigurationException( \
"The mc_frame_period property must be set to give a frame of at least 10 " \
"milliseconds.")
if self.mc_pulse_width < 1:
raise ControllerConfigurationException( \
"The mc_pulse_width property must not be less than one.")
if self.mc_pulse_minimum_off_time is None:
raise ControllerConfigurationException( \
"The mc_pulse_minimum_off_time must be specified.")
a_full_frame_cycles = (self.mc_pulse_width + self.mc_pulse_minimum_off_time) * \
self.mc_a_velocity_limit
b_full_frame_cycles = (self.mc_pulse_width + self.mc_pulse_minimum_off_time) * \
self.mc_b_velocity_limit
if a_full_frame_cycles > self.mc_frame_period or \
b_full_frame_cycles > self.mc_frame_period:
raise ControllerConfigurationException( \
"The minimum off time (mc_pulse_minimum_off_time) will be violated at " \
"the currently configured velocity limits. Reduce the maximum velocity " \
"or adjust the pulse on or off times.")
def encode_gpio(self):
self._validate()
direction = 0L
function = 0L
invert_input = 0L
report_input = 0L
for i in range(64):
if self.pins[i].direction == CONTROLLER_PIN_OUTPUT:
direction |= (1L << i)
if self.pins[i].function == CONTROLLER_PIN_FUNCTION_SPECIAL:
function |= (1L << i)
if self.pins[i].invert_input:
invert_input |= (1L << i)
if self.pins[i].report_input:
report_input |= (1L << i)
return struct.pack("<QQQQ", \
direction, \
function, \
invert_input, \
report_input)
def encode_safety(self):
self._validate()
return struct.pack("<BBBB", \
self._encode_input(self.shutdown_0_input),
self._encode_input(self.shutdown_1_input),
self._encode_input(self.shutdown_2_input),
self._encode_input(self.shutdown_3_input))
def _encode_input(self, value):
if value is None:
return TC_MC_UNUSED_INPUT
elif 0 <= value <= 64:
return value
else:
raise ControllerConfigurationException( \
"An invalid input was specified.")
def encode_mc(self):
self._validate()
return struct.pack("<HHHHHHHHLLBBBBBBBBLHHHHHH", \
self.mc_prefill_frames, \
self.mc_pin_flags, \
self.mc_a_shutdown_acceleration, \
self.mc_b_shutdown_acceleration, \
self.mc_a_acceleration_limit, \
self.mc_b_acceleration_limit, \
self.mc_a_velocity_limit, \
self.mc_b_velocity_limit, \
self.mc_frame_period, \
self.mc_pulse_width, \
self._encode_input(self.mc_a_positive_limit_input), \
self._encode_input(self.mc_a_negative_limit_input), \
self._encode_input(self.mc_b_positive_limit_input), \
self._encode_input(self.mc_b_negative_limit_input), \
self._encode_input(self.mc_a_positive_guider_input), \
self._encode_input(self.mc_a_negative_guider_input), \
self._encode_input(self.mc_b_positive_guider_input), \
self._encode_input(self.mc_b_negative_guider_input), \
self.mc_guider_counter_divider, \
self.mc_guider_a_numerator, \
self.mc_guider_a_denominator, \
self.mc_guider_a_limit, \
self.mc_guider_b_numerator, \
self.mc_guider_b_denominator, \
self.mc_guider_b_limit)
class UsbTransferError(object):
def __init__(self, command, status):
self.command = command
self.status = status
def __repr__(self):
return "<UsbTransferError %s (%s), command %s>" % \
(libusb1.libusb_transfer_status(self.status), self.status, self.command)
class EnqueueDetails(object):
def __init__(self, controller):
self.last_transmitted_frame = controller._last_transmitted_frame
self.last_enqueued_frame = controller._last_enqueued_frame
self.last_dequeued_frame = controller._last_dequeued_frame
self.frames_in_queue = \
(self.last_transmitted_frame - self.last_dequeued_frame) % 0x100000000L
self.frames_queue_capacity = controller.mc_frames_capacity
class ExceptionDetails(object):
def __init__(self, exception, properties):
self.exception = exception
self.properties = properties
def __repr__(self):
if 0 <= self.exception <= len(exception_descriptions):
description = exception_descriptions[self.exception]
else:
description = "(Unknown Exception Code %s)" % self.exception
return "<ExceptionDetails %s %s>" % (description, self.properties)
class StateDetails(object):
def __init__(self, controller, state, exception):
self.state = state
self.exception = exception
def __repr__(self):
if self.state == TC_STATE_EXCEPTION:
return "<StateDetails %s (%s)>" % \
(self.state_description, self.exception_description)
else:
return "<StateDetails %s>" % self.state_description
@property
def state_description(self):
if self.state == TC_STATE_IDLE:
return "TC_STATE_IDLE"
elif self.state == TC_STATE_RUNNING:
return "TC_STATE_RUNNING"
elif self.state == TC_STATE_STOPPING:
return "TC_STATE_STOPPING"
elif self.state == TC_STATE_EXCEPTION:
return "TC_STATE_EXCEPTION"
else:
return "(Unknown State Code)"
@property
def exception_description(self):
if 0 <= self.exception <= len(exception_descriptions):
return exception_descriptions[self.exception]
else:
return "(Unknown Exception Code)"
class CounterDetails(object):
pass
class GuiderResult(object):
pass
class ControllerTimer(object):
def __init__(self, controller, expiry_time, callback):
self._controller = controller
self._expiry_time = expiry_time
self._callback = callback
self._cancelled = False
def __cmp__(self, rhs):
return cmp(self._expiry_time, rhs._expiry_time)
class Controller(object):
def __init__(self, driver):
# Keep a reference to the driver:
self._driver = driver
# Open and set the USB configuration of the controller:
self._context = usb1.LibUSBContext()
self._device_handle = self._find_and_open_device()
self._device = self._device_handle.getDevice()
self._configuration = self._device[0]
self._interface = self._configuration[0]
self._setting = self._interface[0]
self._device_handle.setConfiguration( \
self._configuration.getConfigurationValue())
self._device_handle.claimInterface(0)
# Initialise state:
self._last_transmitted_frame = 0xffffffffL
self._last_enqueued_frame = 0xffffffffL
self._last_dequeued_frame = 0xffffffffL
self._enqueue_in_progress = False
self._last_inputs = 0L
self._last_outputs = 0L
self._last_state = None
self._last_state_details = None
self._last_state_callback = None
self._running = True
self._run_failure = None
self._timers_heap = []
self._driver_initialised = False
def _find_and_open_device(self):
device_handles = []
vendor_id = 0x1bad
product_id = 0xbeef
# Build a list of the connected controllers:
for device_handle in self._context.getDeviceList():
if device_handle.getVendorID() == vendor_id and \
device_handle.getProductID() == product_id:
device_handles.append(device_handle)
break
# Complain if we don't have exactly one:
if len(device_handles) == 0:
raise ControllerNotConnectedException( \
"No controllers were found.")
elif len(device_handles) > 1:
raise MultipleControllersConnectedException( \
"More than one controller was found, and using multiple " \
"controllers is not currently supported.")
# Open and return it:
return device_handle.open()
def _close(self):
self._device_handle.close()
self._device_handle = None
self._context.exit()
def _control_write(self, command, data = ""):
d = defer.Deferred()
transfer = self._device_handle.getTransfer()
transfer.setControl( \
libusb1.LIBUSB_TYPE_VENDOR | \
libusb1.LIBUSB_ENDPOINT_OUT | \
libusb1.LIBUSB_RECIPIENT_DEVICE, \
command, 0, 0, data, self._complete_control_write, (d, command))
transfer.submit()
return d
def _complete_control_write(self, transfer):
deferred, command = transfer.getUserData()
status = transfer.getStatus()
if status == libusb1.LIBUSB_TRANSFER_COMPLETED:
written = transfer.getActualLength()
transfer.close()
deferred.callback(written)
else:
transfer.close()
deferred.errback(UsbTransferError(command, status))
def _control_read(self, command, data_length = 0):
d = defer.Deferred()
transfer = self._device_handle.getTransfer()
transfer.setControl( \
libusb1.LIBUSB_TYPE_VENDOR | \
libusb1.LIBUSB_ENDPOINT_IN | \
libusb1.LIBUSB_RECIPIENT_DEVICE, \
command, 0, 0, data_length, self._complete_control_read, (d, command))
transfer.submit()
return d
def _complete_control_read(self, transfer):
deferred, command = transfer.getUserData()
status = transfer.getStatus()
if status == libusb1.LIBUSB_TRANSFER_COMPLETED:
read = transfer.getBuffer()
transfer.close()
deferred.callback(read)
else:
transfer.close()
deferred.errback(UsbTransferError(command, status))
def _initiate_interrupt_read(self):
transfer = self._device_handle.getTransfer()
transfer.setInterrupt(
0x81, 24, self._complete_interrupt_read)
transfer.submit()
def _complete_interrupt_read(self, transfer):
try:
if transfer.getStatus() == libusb1.LIBUSB_TRANSFER_COMPLETED:
buffer = transfer.getBuffer()
changed, state, flags, exception, inputs, \
last_enqueued_frame, last_dequeued_frame = \
struct.unpack("<BBHLQLL", buffer)
self._last_enqueued_frame = last_enqueued_frame
self._last_dequeued_frame = last_dequeued_frame
if self._last_inputs != inputs:
self._last_inputs = inputs
if self._driver_initialised:
self._driver.inputs_changed(inputs)
if self._last_state != state:
self._last_state = state
self._last_state_details = StateDetails(self, state, exception)
if self._last_state_callback is not None:
callback = self._last_state_callback
self._last_state_callback = None
callback()
if self._driver_initialised:
self._driver.state_changed(self._last_state_details)
self._initiate_interrupt_read()
if not self._enqueue_in_progress:
self._call_enqueue_available()
else:
if self._running:
self.stop(failure.Failure(InterruptTransferFailedException( \
"The USB interrupt transfer to the controller failed.", transfer.getStatus())))
self._driver.runtime_error(failure.Failure(InterruptTransferFailedException( \
"The USB interrupt transfer to the controller failed.", transfer.getStatus())))
finally:
transfer.close()
def shutdown(self):
"""Raises a controller exception that causes the controller to start a ramped shutdown.
After running this command, the exception state will be reported with the
controller.TC_EXCEPTION_SHUTDOWN_REQUESTED exception. To use the controller again
a queue reset must be issued.
The returned deferred completes when the command has been issued; the shutdown exception
may be delivered before or after the deferred callbacks are run.
"""
d = self._control_write(TC_ISSUE_STATE_COMMAND, \
struct.pack("<L", TC_STATE_COMMAND_SHUTDOWN))
d.addCallback(self._state_command_completed)
return d
def hardware_reset(self):
"""Forces the controller to do a hardware reset.
This command will only work from TC_STATE_IDLE or TC_STATE_EXCEPTION.
Unless an error occurs the hardware will be reset before the request returns.
"""
d = self._control_write(TC_ISSUE_STATE_COMMAND, \
struct.pack("<L", TC_STATE_COMMAND_HARDWARE_RESET))
d.addCallback(self._state_command_completed)
return d
def force_hardware_reset(self):
"""Forces the controller to do a hardware reset, regardless of the control state.
This command will work in any state, and will reset the hardware even if
motor control is active. It should only be used for manual resets.
Unless an error occurs the hardware will be reset before the request returns.
"""
d = self._control_write(TC_ISSUE_STATE_COMMAND, \
struct.pack("<L", TC_STATE_COMMAND_FORCE_HARDWARE_RESET))
d.addCallback(self._state_command_completed)
return d
def clear_exception(self, exception):
"""Clears the specified controller exception. The exception must be the current reported exception.
Once the command returns the next exception should be available through the (synchronous) get
exception control request.
The returned deferred completes when the command has been issued; a state change exception to
idle may be delivered before or after the deferred callbacks are run.
"""
d = self._control_write(TC_CLEAR_EXCEPTION, \
struct.pack("<L", exception))
d.addCallback(self._state_command_completed)
return d
def _clear_exception_completed(self, bytes_written):
return None
def enable_guider(self):
"""Starts adding guider steps to the motor control frames.
The returned deferred completes when the command has been successfully issued.
"""
d = self._control_write(TC_ISSUE_STATE_COMMAND, \
struct.pack("<L", TC_STATE_COMMAND_ENABLE_GUIDER))
d.addCallback(self._state_command_completed)
return d
def disable_guider(self):
"""Stops adding guider steps to the motor control frames.
The returned deferred completes when the command has been successfully issued.
"""
d = self._control_write(TC_ISSUE_STATE_COMMAND, \
struct.pack("<L", TC_STATE_COMMAND_DISABLE_GUIDER))
d.addCallback(self._state_command_completed)
return d
def _state_command_completed(self, bytes_written):
return None
def configure(self, configuration):
"""Writes a configuration to the controller.
The returned deferred completes when the configuration has been
successfully written.
"""
d = self._control_write(TC_MC_CONFIGURE, \
configuration.encode_mc())
d.addCallback(self._configure_mc_completed, configuration)
return d
def _configure_mc_completed(self, bytes_written, configuration):
d = self._control_write(TC_GPIO_CONFIGURE, \
configuration.encode_gpio())
d.addCallback(self._configure_gpio_completed, configuration)
return d
def _configure_gpio_completed(self, bytes_written, configuration):
d = self._control_write(TC_SAFETY_CONFIGURE, \
configuration.encode_safety())
d.addCallback(self._configure_safety_completed, configuration)
return d
def _configure_safety_completed(self, bytes_written, configuration):
return configuration
def _handle_initialise_error(self, failure):
self.stop(failure)
self._driver.initialisation_error(failure)
def _initialise_internals(self):
d = self._control_read(TC_GET_VERSION, 16)
d.addCallback(self._initialise_internals_handle_version)
d.addErrback(self._handle_initialise_error)
def _initialise_internals_handle_version(self, buffer):
mcu_minor, mcu_major, fpga_minor, fpga_major, \
self.clock_frequency, self.mc_frames_capacity, reserved = \
struct.unpack("<HHHHLHH", buffer)
self.mcu_version = (mcu_major, mcu_minor)
self.fpga_version = (fpga_major, fpga_minor)
if self.mcu_version != self.fpga_version:
raise ControllerVersionException("The version of the firmware in the " \
"MCU (Version %s.%s) does not match the version of the firmware in " \
"the FPGA (Version %s.%s)." % (mcu_major, mcu_minor, fpga_major, fpga_minor))
if module_version[:2] != self.mcu_version:
raise ControllerVersionException("The version of this Python module " \
"(Version %s.%s.%s) does not match the version of the firmware in " \
"the MCU (Version %s.%s)." % \
(module_version[0], module_version[1], module_version[2], fpga_major, fpga_minor))
expected_version = self._driver.get_expected_controller_version()
if len(expected_version) != 3:
raise ControllerVersionException("This version of the controller " \
"library requires a three element version number tuple from your driver " \
"(version %s.%s.%s). Update the \"get_expected_controller_version\" " \
"method in your driver class, and then carefully check any " \
"release notes for this module and thoroughly test the new version." %
(module_version[0], module_version[1], module_version[2]))
if expected_version != module_version:
raise ControllerVersionException("Your code is expecting version " \
"%s.%s.%s of the controller module, but the controller module is " \
"version %s.%s.%s. Update the \"get_expected_controller_version\" " \
"method in your driver class, and then carefully check any " \
"release notes for this module and thoroughly test the new version." %
(expected_version[0], expected_version[1], expected_version[2], \
module_version[0], module_version[1], module_version[2]))
# Force an interrupt so that the driver can be provided with it:
d = self._control_write(TC_ISSUE_STATE_COMMAND, \
struct.pack("<L", TC_STATE_COMMAND_FORCE_INTERRUPT))
d.addCallback(self._initialise_force_interrupt_completed)
d.addErrback(self._handle_initialise_error)
def _initialise_force_interrupt_completed(self, bytes_written):
if self._last_state_details is not None:
self._initialise_start_driver_initialise()
else:
self._last_state_callback = self._initialise_start_driver_initialise
def _initialise_start_driver_initialise(self):
if self._last_state == TC_STATE_RUNNING:
d = self.shutdown()
d.addCallback(self._initialise_wait_for_stop)
d.addErrback(self._handle_initialise_error)
elif self._last_state_details.state == TC_STATE_STOPPING:
self._initialise_wait_for_stop()
else:
self._initialise_call_driver_initialise()
def _initialise_wait_for_stop(self, _ = None):
# Wait for the state to change to an exception:
if self._last_state != TC_STATE_EXCEPTION:
self._last_state_callback = self._initialise_wait_for_stop
else:
self._initialise_call_driver_initialise()
def _initialise_call_driver_initialise(self):
d = self._driver.initialise(self._last_state_details)
if not isinstance(d, defer.Deferred):
raise ControllerUsageException("The driver initialise method must return a deferred.")
d.addCallback(self._driver_initialise_completed)
d.addErrback(self._handle_initialise_error)
def _driver_initialise_completed(self, _):
self._driver_initialised = True
# Give the driver the most recent status and inputs:
self._driver.state_changed(self._last_state_details)
self._driver.inputs_changed(self._last_inputs)
def add_timer(self, seconds, callback):
"""Schedules a (once off) call to the callback function.
The returned handle can be passed to cancel_timer to cancel the callback before
it has occurred."""
timer = ControllerTimer(self, time.time() + seconds, callback)
heapq.heappush(self._timers_heap, timer)
return timer
def cancel_timer(self, timer):
"""Cancels a callback."""
timer._cancelled = True
def _run_timer_callbacks(self):
now = time.time()
while len(self._timers_heap) >= 1:
timer = self._timers_heap[0]
if now > timer._expiry_time:
heapq.heappop(self._timers_heap)
if not timer._cancelled:
timer._callback()
else:
break
def run(self, system_poller):
"""Runs the event loop, after calling the driver initialisation method.
Driver event handlers and timers are handled by the event loop. Optionally, a
user supplied poller can be passed in. The poller must implement the interface
described in the python-libusb1 library."""
poller = usb1.USBPoller(self._context, system_poller)
self._initiate_interrupt_read()
self._initialise_internals()
self._running = True
while self._running:
if len(self._timers_heap) >= 1:
# There are timers to eventually call:
next_timer = self._timers_heap[0]
next_timer_time = next_timer._expiry_time - time.time()
if next_timer_time < 0.0: next_timer_time = 0.0
poller.poll(next_timer_time)
self._run_timer_callbacks()
else:
# No timers, just wait for file events:
poller.poll()
self._close()