This repository has been archived by the owner on Oct 16, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathepos.py
2144 lines (1908 loc) · 89.5 KB
/
epos.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/python
# -*- coding: utf-8 -*-
# The MIT License (MIT)
# Copyright (c) 2018 Bruno Tibério
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import canopen
import logging
import sys
class Epos:
channel = 'can0'
bustype = 'socketcan'
nodeID = 1
network = None
_connected = False
errorDetected = False
# List of motor types
motorType = {'DC motor': 1, 'Sinusoidal PM BL motor': 10,
'Trapezoidal PM BL motor': 11}
# If EDS file is present, this is not necessary, all codes can be gotten
# from object dictionary.
objectIndex = {'Device Type': 0x1000,
'Error Register': 0x1001,
'Error History': 0x1003,
'COB-ID SYNC Message': 0x1005,
'Device Name': 0x1008,
'Guard Time': 0x100C,
'Life Time Factor': 0x100D,
'Store Parameters': 0x1010,
'Restore Default Parameters': 0x1011,
'COB-ID Emergency Object': 0x1014,
'Consumer Heartbeat Time': 0x1016,
'Producer Heartbeat Time': 0x1017,
'Identity Object': 0x1018,
'Verify configuration': 0x1020,
'Server SDO 1 Parameter': 0x1200,
'Receive PDO 1 Parameter': 0x1400,
'Receive PDO 2 Parameter': 0x1401,
'Receive PDO 3 Parameter': 0x1402,
'Receive PDO 4 Parameter': 0x1403,
'Receive PDO 1 Mapping': 0x1600,
'Receive PDO 2 Mapping': 0x1601,
'Receive PDO 3 Mapping': 0x1602,
'Receive PDO 4 Mapping': 0x1603,
'Transmit PDO 1 Parameter': 0x1800,
'Transmit PDO 2 Parameter': 0x1801,
'Transmit PDO 3 Parameter': 0x1802,
'Transmit PDO 4 Parameter': 0x1803,
'Transmit PDO 1 Mapping': 0x1A00,
'Transmit PDO 2 Mapping': 0x1A01,
'Transmit PDO 3 Mapping': 0x1A02,
'Transmit PDO 4 Mapping': 0x1A03,
'Node ID': 0x2000,
'CAN Bitrate': 0x2001,
'RS232 Baudrate': 0x2002,
'Version Numbers': 0x2003,
'Serial Number': 0x2004,
'RS232 Frame Timeout': 0x2005,
'Miscellaneous Configuration': 0x2008,
'Internal Dip Switch State': 0x2009,
'Custom persistent memory': 0x200C,
'Internal DataRecorder Control': 0x2010,
'Internal DataRecorder Configuration': 0x2011,
'Internal DataRecorder Sampling Period': 0x2012,
'Internal DataRecorder Number of Preceding Samples': 0x2013,
'Internal DataRecorder Number of Sampling Variables': 0x2014,
'DataRecorder Index of Variables': 0x2015,
'Internal DataRecorder SubIndex of Variables': 0x2016,
'Internal DataRecorder Status': 0x2017,
'Internal DataRecorder Max Number of Samples': 0x2018,
'Internal DataRecorder Number of Recorded Samples': 0x2019,
'Internal DataRecorder Vector Start Offset': 0x201A,
'Encoder Counter': 0x2020,
'Encoder Counter at Index Pulse': 0x2021,
'Hallsensor Pattern': 0x2022,
'Internal Object Demand Rotor Angle': 0x2023,
'Internal System State': 0x2024,
'Internal Object Reserved': 0x2025,
'Internal Object ProcessMemory': 0x2026,
'Current Actual Value Averaged': 0x2027,
'Velocity Actual Value Averaged': 0x2028,
'Internal Object Actual Rotor Angle': 0x2029,
'Internal Object NTC Temperature Sensor Value': 0x202A,
'Internal Object Motor Phase Current U': 0x202B,
'Internal Object Motor Phase Current V': 0x202C,
'Internal Object Measured Angle Difference': 0x202D,
'Trajectory Profile Time': 0x202E,
'CurrentMode Setting Value': 0x2030,
'PositionMode Setting Value': 0x2062,
'VelocityMode Setting Value': 0x206B,
'Configuration Digital Inputs': 0x2070,
'Digital Input Funtionalities': 0x2071,
'Position Marker': 0x2074,
'Digital Output Funtionalities': 0x2078,
'Configuration Digital Outputs': 0x2079,
'Analog Inputs': 0x207C,
'Current Threshold for Homing Mode': 0x2080,
'Home Position': 0x2081,
'Following Error Actual Value': 0x20F4,
'Sensor Configuration': 0x2210,
'Digital Position Input': 0x2300,
'Internal Object Download Area': 0x2FFF,
'ControlWord': 0x6040,
'StatusWord': 0x6041,
'Modes of Operation': 0x6060,
'Modes of Operation Display': 0x6061,
'Position Demand Value': 0x6062,
'Position Actual Value': 0x6064,
'Max Following Error': 0x6065,
'Position Window': 0x6067,
'Position Window Time': 0x6068,
'Velocity Sensor Actual Value': 0x6069,
'Velocity Demand Value': 0x606B,
'Velocity Actual Value': 0x606C,
'Current Actual Value': 0x6078,
'Target Position': 0x607A,
'Home Offset': 0x607C,
'Software Position Limit': 0x607D,
'Max Profile Velocity': 0x607F,
'Profile Velocity': 0x6081,
'Profile Acceleration': 0x6083,
'Profile Deceleration': 0x6084,
'QuickStop Deceleration': 0x6085,
'Motion ProfileType': 0x6086,
'Position Notation Index': 0x6089,
'Position Dimension Index': 0x608A,
'Velocity Notation Index': 0x608B,
'Velocity Dimension Index': 0x608C,
'Acceleration Notation Index': 0x608D,
'Acceleration Dimension Index': 0x608E,
'Homing Method': 0x6098,
'Homing Speeds': 0x6099,
'Homing Acceleration': 0x609A,
'Current Control Parameter': 0x60F6,
'Speed Control Parameter': 0x60F9,
'Position Control Parameter': 0x60FB,
'TargetVelocity': 0x60FF,
'MotorType': 0x6402,
'Motor Data': 0x6410,
'Supported Drive Modes': 0x6502}
# CANopen defined error codes and Maxon codes also
errorIndex = {0x00000000: 'Error code: no error',
# 0x050x xxxx
0x05030000: 'Error code: toggle bit not alternated',
0x05040000: 'Error code: SDO protocol timeout',
0x05040001: 'Error code: Client/server command specifier not valid or unknown',
0x05040002: 'Error code: invalid block size',
0x05040003: 'Error code: invalid sequence number',
0x05040004: 'Error code: CRC error',
0x05040005: 'Error code: out of memory',
# 0x060x xxxx
0x06010000: 'Error code: Unsupported access to an object',
0x06010001: 'Error code: Attempt to read a write-only object',
0x06010002: 'Error code: Attempt to write a read-only object',
0x06020000: 'Error code: object does not exist',
0x06040041: 'Error code: object can not be mapped to the PDO',
0x06040042: 'Error code: the number and length of the objects to be mapped would exceed PDO length',
0x06040043: 'Error code: general parameter incompatibility',
0x06040047: 'Error code: general internal incompatibility in the device',
0x06060000: 'Error code: access failed due to an hardware error',
0x06070010: 'Error code: data type does not match, length of service parameter does not match',
0x06070012: 'Error code: data type does not match, length of service parameter too high',
0x06070013: 'Error code: data type does not match, length of service parameter too low',
0x06090011: 'Error code: subindex does not exist',
0x06090030: 'Error code: value range of parameter exceeded',
0x06090031: 'Error code: value of parameter written is too high',
0x06090032: 'Error code: value of parameter written is too low',
0x06090036: 'Error code: maximum value is less than minimum value',
0x060A0023: 'Error code: resource not available: SDO connection',
# 0x0800 xxxx
0x08000000: 'Error code: General error',
0x08000020: 'Error code: Data cannot be transferred or stored to the application',
0x08000021: 'Error code: Data cannot be transferred or stored to the application because of local control',
0x08000022: 'Error code: Wrong Device State. Data can not be transfered',
0x08000023: 'Error code: Object dictionary dynamic generation failed or no object dictionary present',
# Maxon defined error codes
0x0f00ffc0: 'Error code: wrong NMT state',
0x0f00ffbf: 'Error code: rs232 command illegal',
0x0f00ffbe: 'Error code: password incorrect',
0x0f00ffbc: 'Error code: device not in service mode',
0x0f00ffB9: 'Error code: error in Node-ID'
}
# dictionary describing opMode
opModes = {6: 'Homing Mode', 3: 'Profile Velocity Mode', 1: 'Profile Position Mode',
-1: 'Position Mode', -2: 'Velocity Mode', -3: 'Current Mode', -4: 'Diagnostic Mode',
-5: 'MasterEncoder Mode', -6: 'Step/Direction Mode'}
node = []
# dictionary object to describe state of EPOS device
state = {0: 'start', 1: 'not ready to switch on', 2: 'switch on disable',
3: 'ready to switch on', 4: 'switched on', 5: 'refresh',
6: 'measure init', 7: 'operation enable', 8: 'quick stop active',
9: 'fault reaction active (disabled)', 10: 'fault reaction active (enable)', 11: 'fault',
-1: 'Unknown'}
# dictionary describing emcy codes received on CANBus
emcy_descriptions = [
# Code Description
(0x0000, "Error Reset / No Error"),
(0x1000, "Generic Error"),
(0x2310, "Over Current Error"),
(0x3210, "Over Voltage Error"),
(0x3220, "Under Voltage"),
(0x4210, "Over Temperature"),
(0x5113, "Supply Voltage (+5V) too low"),
(0x6100, "Internal Software Error"),
(0x6320, "Software Parameter Error"),
(0x7320, "Sensor Position Error"),
(0x8110, "CAN Overrun Error (Objects lost)"),
(0x8111, "CAN Overrun Error"),
(0x8120, "CAN Passive Mode Error"),
(0x8130, "CAN Life Guard Error"),
(0x8150, "CAN Transmit COB-ID collision"),
(0x81FD, "CAN Bus Off"),
(0x81FE, "CAN Rx Queue Overrun"),
(0x81FF, "CAN Tx Queue Overrun"),
(0x8210, "CAN PDO length Error"),
(0x8611, "Following Error"),
(0x9000, "External Error"),
(0xF001, "Hall Sensor Error"),
(0xFF02, "Index Processing Error"),
(0xFF03, "Encoder Resolution Error"),
(0xFF04, "Hall Sensor not found Error"),
(0xFF06, "Negative Limit Error"),
(0xFF07, "Positive Limit Error"),
(0xFF08, "Hall Angle detection Error"),
(0xFF09, "Software Position Limit Error"),
(0xFF0A, "Position Sensor Breach"),
(0xFF0B, "System Overloaded")
]
def __init__(self, _network=None, debug=False):
# check if network is passed over or create a new one
if not _network:
self.network = canopen.Network()
else:
self.network = _network
self.logger = logging.getLogger('EPOS')
if debug:
self.logger.setLevel(logging.DEBUG)
else:
self.logger.setLevel(logging.INFO)
def begin(self, nodeID, _channel='can0', _bustype='socketcan', object_dictionary=None):
""" Initialize Epos device
Configure and setup Epos device.
Args:
nodeID: Node ID of the device.
_channel (optional): Port used for communication. Default can0
_bustype (optional): Port type used. Default socketcan.
object_dictionary (optional): Name of EDS file, if any available.
Return:
bool: A boolean if all went ok.
"""
try:
self.node = self.network.add_node(
nodeID, object_dictionary=object_dictionary)
# emcy messages handles
self.node.emcy.add_callback(self.emcy_error_print)
# in not connected?
if not self.network.bus:
# so try to connect
self.network.connect(channel=_channel, bustype=_bustype)
val, _ = self.read_statusword() # test if we really have response or is only connected to CAN bus
if val is None:
self._connected = False
except Exception as e:
self.log_info("Exception caught:{0}".format(str(e)))
self._connected = False
finally:
return self._connected
def disconnect(self):
self.network.disconnect()
return
def emcy_error_print(self, emcy_error):
"""Print any EMCY Error Received on CAN BUS
"""
if emcy_error.code is 0:
self.errorDetected = False
else:
for code, description in self.emcy_descriptions:
if emcy_error.code == code:
self.errorDetected = True
self.log_info("Got an EMCY message: Code: 0x{0:04X} {1}".format(code, description))
return
# if no description was found, print generic info
self.errorDetected = True
self.log_info('Got an EMCY message: {0}'.format(emcy_error))
return
# --------------------------------------------------------------
# Basic set of functions
# --------------------------------------------------------------
def log_info(self, message=None):
""" Log a message
A wrap around logging.
The log message will have the following structure\:
[class name \: function name ] message
Args:
message: a string with the message.
"""
if message is None:
# do nothing
return
self.logger.info('[{0}:{1}] {2}'.format(
self.__class__.__name__,
sys._getframe(1).f_code.co_name,
message))
return
def log_debug(self, message=None):
""" Log a message with debug level
A wrap around logging.
The log message will have the following structure\:
[class name \: function name ] message
the function name will be the caller function retrieved automatically
by using sys._getframe(1).f_code.co_name
Args:
message: a string with the message.
"""
if message is None:
# do nothing
return
self.logger.debug('[{0}:{1}] {2}'.format(
self.__class__.__name__,
sys._getframe(1).f_code.co_name,
message))
return
def read_object(self, index, subindex):
"""Reads an object
Request a read from dictionary object referenced by index and subindex.
Args:
index: reference of dictionary object index
subindex: reference of dictionary object subindex
Returns:
bytes: message returned by EPOS or empty if unsuccessful
"""
if self._connected:
try:
return self.node.sdo.upload(index, subindex)
except Exception as e:
self.log_info('Exception caught:{0}'.format(str(e)))
return None
else:
self.log_info(' Error: {0} is not connected'.format(
self.__class__.__name__))
return None
def write_object(self, index, subindex, data):
"""Write an object
Request a write to dictionary object referenced by index and subindex.
Args:
index: reference of dictionary object index
subindex: reference of dictionary object subindex
data: data to be stored
Returns:
bool: boolean if all went ok or not
"""
if self._connected:
try:
self.node.sdo.download(index, subindex, data)
return True
except canopen.SdoAbortedError as e:
text = "Code 0x{:08X}".format(e.code)
if e.code in self.errorIndex:
text = text + ", " + self.errorIndex[e.code]
self.log_info('SdoAbortedError: ' + text)
return False
except canopen.SdoCommunicationError:
self.log_info('SdoAbortedError: Timeout or unexpected response')
return False
else:
self.log_info(' Error: {0} is not connected'.format(
self.__class__.__name__))
return False
# --------------------------------------------------------------------------
# High level functions
# --------------------------------------------------------------------------
def read_statusword(self):
"""Read StatusWord
Request current statusword from device.
Returns:
tuple: A tuple containing:
:statusword: the current statusword or None if any error.
:ok: A boolean if all went ok.
"""
index = self.objectIndex['StatusWord']
subindex = 0
statusword = self.read_object(index, subindex)
# failed to request?
if not statusword:
self.log_info('Error trying to read {0} statusword'.format(
self.__class__.__name__))
return statusword, False
# return statusword as an int type
statusword = int.from_bytes(statusword, 'little')
return statusword, True
def read_controlword(self):
"""Read ControlWord
Request current controlword from device.
Returns:
tuple: A tuple containing:
:controlword: the current controlword or None if any error.
:ok: A boolean if all went ok.
"""
index = self.objectIndex['ControlWord']
subindex = 0
controlword = self.read_object(index, subindex)
# failed to request?
if not controlword:
self.log_info('Error trying to read {0} controlword'.format(
self.__class__.__name__))
return controlword, False
# return controlword as an int type
controlword = int.from_bytes(controlword, 'little')
return controlword, True
def write_controlword(self, controlword):
"""Send controlword to device
Args:
controlword: word to be sent.
Returns:
bool: a boolean if all went ok.
"""
# sending new controlword
self.log_debug(
'Sending controlword Hex={0:#06X} Bin={0:#018b}'.format(controlword))
controlword = controlword.to_bytes(2, 'little')
return self.write_object(0x6040, 0, controlword)
def check_state(self):
"""Check current state of Epos
Ask the StatusWord of EPOS and parse it to return the current state of EPOS.
+----------------------------------+-----+---------------------+
| State | ID | Statusword [binary] |
+==================================+=====+=====================+
| Start | 0 | x0xx xxx0 x000 0000|
+----------------------------------+-----+---------------------+
| Not Ready to Switch On | 1 | x0xx xxx1 x000 0000|
+----------------------------------+-----+---------------------+
| Switch on disabled | 2 | x0xx xxx1 x100 0000|
+----------------------------------+-----+---------------------+
| ready to switch on | 3 | x0xx xxx1 x010 0001|
+----------------------------------+-----+---------------------+
| switched on | 4 | x0xx xxx1 x010 0011|
+----------------------------------+-----+---------------------+
| refresh | 5 | x1xx xxx1 x010 0011|
+----------------------------------+-----+---------------------+
| measure init | 6 | x1xx xxx1 x011 0011|
+----------------------------------+-----+---------------------+
| operation enable | 7 | x0xx xxx1 x011 0111|
+----------------------------------+-----+---------------------+
| quick stop active | 8 | x0xx xxx1 x001 0111|
+----------------------------------+-----+---------------------+
| fault reaction active (disabled) | 9 | x0xx xxx1 x000 1111|
+----------------------------------+-----+---------------------+
| fault reaction active (enabled) | 10 | x0xx xxx1 x001 1111|
+----------------------------------+-----+---------------------+
| Fault | 11 | x0xx xxx1 x000 1000|
+----------------------------------+-----+---------------------+
see section 8.1.1 of firmware manual for more details.
Returns:
int: numeric identification of the state or -1 in case of fail.
"""
statusword, ok = self.read_statusword()
if not ok:
self.log_info('Failed to request StatusWord')
return -1
else:
# state 'start' (0)
# statusWord == x0xx xxx0 x000 0000
bitmask = 0b0100000101111111
if bitmask & statusword == 0:
return 0
# state 'not ready to switch on' (1)
# statusWord == x0xx xxx1 x000 0000
bitmask = 0b0100000101111111
if bitmask & statusword == 256:
return 1
# state 'switch on disabled' (2)
# statusWord == x0xx xxx1 x100 0000
bitmask = 0b0100000101111111
if bitmask & statusword == 320:
return 2
# state 'ready to switch on' (3)
# statusWord == x0xx xxx1 x010 0001
bitmask = 0b0100000101111111
if bitmask & statusword == 289:
return 3
# state 'switched on' (4)
# statusWord == x0xx xxx1 x010 0011
bitmask = 0b0000000101111111
if bitmask & statusword == 291:
return 4
# state 'refresh' (5)
# statusWord == x1xx xxx1 x010 0011
bitmask = 0b0100000101111111
if bitmask & statusword == 16675:
return 5
# state 'measure init' (6)
# statusWord == x1xx xxx1 x011 0011
bitmask = 0b0100000101111111
if bitmask & statusword == 16691:
return 6
# state 'operation enable' (7)
# statusWord == x0xx xxx1 x011 0111
bitmask = 0b0100000101111111
if bitmask & statusword == 311:
return 7
# state 'Quick Stop Active' (8)
# statusWord == x0xx xxx1 x001 0111
bitmask = 0b0100000101111111
if bitmask & statusword == 279:
return 8
# state 'fault reaction active (disabled)' (9)
# statusWord == x0xx xxx1 x000 1111
bitmask = 0b0100000101111111
if bitmask & statusword == 271:
return 9
# state 'fault reaction active (enabled)' (10)
# statusWord == x0xx xxx1 x001 1111
bitmask = 0b0100000101111111
if bitmask & statusword == 287:
return 10
# state 'fault' (11)
# statusWord == x0xx xxx1 x000 1000
bitmask = 0b0100000101111111
if bitmask & statusword == 264:
return 11
# in case of unknown state or fail
# in case of unknown state or fail
self.log_info('Error: Unknown state. Statusword is Bin={0:#018b}'.format(
int.from_bytes(statusword, 'little'))
)
return -1
def print_state(self):
ID = self.check_state()
if ID is -1:
print('[{0}:{1}] Error: Unknown state\n'.format(
self.__class__.__name__,
sys._getframe().f_code.co_name))
else:
print('[{0}:{1}] Current state [ID]:{2} [{3}]\n'.format(
self.__class__.__name__,
sys._getframe().f_code.co_name,
self.state[ID],
ID))
return
def print_statusword(self):
statusword, ok = self.read_statusword()
if not ok:
print('[{0}:{1}] Failed to retreive statusword\n'.format(
self.__class__.__name__,
sys._getframe().f_code.co_name))
return
else:
print("[{0}:{1}] The statusword is Hex={2:#06X} Bin={2:#018b}\n".format(
self.__class__.__name__,
sys._getframe().f_code.co_name,
statusword))
print('Bit 15: position referenced to home position: {0}'.format(
(statusword & (1 << 15)) >> 15))
print('Bit 14: refresh cycle of power stage: {0}'.format(
(statusword & (1 << 14)) >> 14))
print('Bit 13: OpMode specific, some error: [Following|Homing] {0}'.format(
(statusword & (1 << 13)) >> 13))
print('Bit 12: OpMode specific: [Set-point ack|Speed|Homing attained] {0}'.format(
(statusword & (1 << 12)) >> 12))
print('Bit 11: Internal limit active: {0}'.format(
(statusword & (1 << 11)) >> 11))
print('Bit 10: Target reached: {0}'.format(
(statusword & (1 << 10)) >> 10))
print('Bit 09: Remote (NMT Slave State Operational): {0}'.format(
(statusword & (1 << 9)) >> 9))
print('Bit 08: Offset current measured: {0}'.format(
(statusword & (1 << 8)) >> 8))
print('Bit 07: not used (Warning): {0}'.format(
(statusword & (1 << 7)) >> 7))
print('Bit 06: Switch on disable: {0}'.format(
(statusword & (1 << 6)) >> 6))
print('Bit 05: Quick stop: {0}'.format(
(statusword & (1 << 5)) >> 5))
print('Bit 04: Voltage enabled (power stage on): {0}'.format(
(statusword & (1 << 4)) >> 4))
print('Bit 03: Fault: {0}'.format(
(statusword & (1 << 3)) >> 3))
print('Bit 02: Operation enable: {0}'.format(
(statusword & (1 << 2)) >> 2))
print('Bit 01: Switched on: {0}'.format(
(statusword & (1 << 1)) >> 1))
print('Bit 00: Ready to switch on: {0}'.format(
statusword & 1))
return
def print_controlword(self, controlword=None):
"""Print the meaning of controlword
Check the meaning of current controlword of device or check the meaning of your own controlword.
Useful to check your own controlword before actually sending it to device.
Args:
controlword (optional): If None, request the controlword of device.
"""
if not controlword:
controlword, ok = self.read_controlword()
if not ok:
print('[{0}:{1}] Failed to retrieve controlword\n'.format(
self.__class__.__name__,
sys._getframe().f_code.co_name))
return
print("[{0}:{1}] The controlword is Hex={2:#06X} Bin={2:#018b}\n".format(
self.__class__.__name__,
sys._getframe().f_code.co_name,
controlword))
# Bit 15 to 11 not used, 10 to 9 reserved
print('Bit 08: Halt: {0}'.format(
(controlword & (1 << 8)) >> 8))
print('Bit 07: Fault reset: {0}'.format(
(controlword & (1 << 7)) >> 7))
print('Bit 06: Operation mode specific:[Abs=0|rel=1] {0}'.format(
(controlword & (1 << 6)) >> 6))
print('Bit 05: Operation mode specific:[Change set immediately] {0}'.format(
(controlword & (1 << 5)) >> 5))
print('Bit 04: Operation mode specific:[New set-point|reserved|Homing operation start] {0}'.format(
(controlword & (1 << 4)) >> 4))
print('Bit 03: Enable operation: {0}'.format(
(controlword & (1 << 3)) >> 3))
print('Bit 02: Quick stop: {0}'.format(
(controlword & (1 << 2)) >> 2))
print('Bit 01: Enable voltage: {0}'.format(
(controlword & (1 << 1)) >> 1))
print('Bit 00: Switch on: {0}'.format(
controlword & 1))
return
def read_position_mode_setting(self):
"""Reads the set desired Position
Ask Epos device for demand position object. If a correct
request is made, the position is placed in answer. If
not, an answer will be empty
Returns:
tuple: A tuple containing:
:position: the demanded position value.
:ok: A boolean if all requests went ok or not.
"""
index = self.objectIndex['PositionMode Setting Value']
subindex = 0
position = self.read_object(index, subindex)
# failed to request?
if not position:
self.log_info("Error trying to read EPOS PositionMode Setting Value")
return position, False
# return value as signed int
position = int.from_bytes(position, 'little', signed=True)
return position, True
def set_position_mode_setting(self, position):
"""Sets the desired Position
Ask Epos device to define position mode setting object.
Returns:
bool: A boolean if all requests went ok or not.
"""
index = self.objectIndex['PositionMode Setting Value']
subindex = 0
if position < -2 ** 31 or position > 2 ** 31 - 1:
self.log_info("Position out of range")
return False
# change to bytes as an int32 value
position = position.to_bytes(4, 'little', signed=True)
return self.write_object(index, subindex, position)
def read_velocity_mode_setting(self):
"""Reads the set desired velocity
Asks EPOS for the desired velocity value in velocity control mode
Returns:
tuple: A tuple containing:
:velocity: Value set or None if any error.
:ok: A boolean if successful or not.
"""
index = self.objectIndex['VelocityMode Setting Value']
subindex = 0
velocity = self.read_object(index, subindex)
# failed to request?
if not velocity:
self.log_info("Error trying to read EPOS VelocityMode Setting Value")
return velocity, False
# return value as signed int
velocity = int.from_bytes(velocity, 'little', signed=True)
return velocity, True
def set_velocity_mode_setting(self, velocity):
"""Set desired velocity
Set the value for desired velocity in velocity control mode.
Args:
velocity: value to be set.
Returns:
bool: a boolean if successful or not.
"""
index = self.objectIndex['VelocityMode Setting Value']
subindex = 0
if velocity < -2 ** 31 or velocity > 2 ** 31 - 1:
self.log_info("Velocity out of range")
return False
# change to bytes as an int32 value
velocity = velocity.to_bytes(4, 'little', signed=True)
return self.write_object(index, subindex, velocity)
def read_current_mode_setting(self):
"""Read current value set
Asks EPOS for the current value set in current control mode.
Returns:
tuple: A tuple containing:
:current: value set.
:ok: a boolean if successful or not.
"""
index = self.objectIndex['CurrentMode Setting Value']
subindex = 0
current = self.read_object(index, subindex)
# failed to request
if not current:
self.log_info("Error trying to read EPOS CurrentMode Setting Value")
return current, False
# return value as signed int
current = int.from_bytes(current, 'little', signed=True)
return current, True
def set_current_mode_setting(self, current):
"""Set desired current
Set the value for desired current in current control mode
Args:
current: the value to be set [mA]
Returns:
bool: a boolean if successful or not
"""
index = self.objectIndex['CurrentMode Setting Value']
subindex = 0
if current < -2 ** 15 or current > 2 ** 15 - 1:
self.log_info("Current out of range")
return False
# change to bytes as an int16 value
current = current.to_bytes(2, 'little', signed=True)
return self.write_object(index, subindex, current)
def read_op_mode(self):
"""Read current operation mode
Returns:
tuple: A tuple containing:
:op_mode: current op_mode or None if request fails
:ok: A boolean if successful or not
"""
index = self.objectIndex['Modes of Operation']
subindex = 0
op_mode = self.read_object(index, subindex)
# failed to request
if not op_mode:
self.log_info("Error trying to read EPOS Operation Mode")
return op_mode, False
# change to int value
op_mode = int.from_bytes(op_mode, 'little', signed=True)
return op_mode, True
def set_op_mode(self, op_mode):
"""Set Operation mode
Sets the operation mode of Epos. OpMode is described as:
+--------+-----------------------+
| OpMode | Description |
+========+=======================+
| 6 | Homing Mode |
+--------+-----------------------+
| 3 | Profile Velocity Mode |
+--------+-----------------------+
| 1 | Profile Position Mode |
+--------+-----------------------+
| -1 | Position Mode |
+--------+-----------------------+
| -2 | Velocity Mode |
+--------+-----------------------+
| -3 | Current Mode |
+--------+-----------------------+
| -4 | Diagnostic Mode |
+--------+-----------------------+
| -5 | MasterEncoder Mode |
+--------+-----------------------+
| -6 | Step/Direction Mode |
+--------+-----------------------+
Args:
op_mode: the desired opMode.
Returns:
bool: A boolean if all requests went ok or not.
"""
index = self.objectIndex['Modes of Operation']
subindex = 0
if not op_mode in self.opModes:
self.log_info("Unknown Operation Mode: {0}".format(op_mode))
return False
op_mode = op_mode.to_bytes(1, 'little', signed=True)
return self.write_object(index, subindex, op_mode)
def print_op_mode(self):
"""Print current operation mode
"""
op_mode, ok = self.read_op_mode()
if not ok:
print('Failed to request current operation mode')
return
if not (op_mode in self.opModes):
self.log_info("Unknown Operation Mode: {0}".format(op_mode))
return
else:
print('Current operation mode is \"{}\"'.format(
self.opModes[op_mode]))
return
def change_state(self, new_state):
"""Change EPOS state
Change Epos state using controlWord object
To change Epos state, a write to controlWord object is made.
The bit change in controlWord is made as shown in the following table:
+-------------------+--------------------------------+
| State | LowByte of Controlword [binary]|
+===================+================================+
| shutdown | 0xxx x110 |
+-------------------+--------------------------------+
| switch on | 0xxx x111 |
+-------------------+--------------------------------+
| disable voltage | 0xxx xx0x |
+-------------------+--------------------------------+
| quick stop | 0xxx x01x |
+-------------------+--------------------------------+
| disable operation | 0xxx 0111 |
+-------------------+--------------------------------+
| enable operation | 0xxx 1111 |
+-------------------+--------------------------------+
| fault reset | 1xxx xxxx |
+-------------------+--------------------------------+
see section 8.1.3 of firmware for more information
Args:
new_state: string with state witch user want to switch.
Returns:
bool: boolean if all went ok and no error was received.
"""
state_order = ['shutdown', 'switch on', 'disable voltage', 'quick stop',
'disable operation', 'enable operation', 'fault reset']
if not (new_state in state_order):
self.log_info("Unknown state: {0}".format(new_state))
return False
else:
controlword, Ok = self.read_controlword()
if not Ok:
self.log_info("Failed to retrieve controlword")
return False
# shutdown 0xxx x110
if new_state == 'shutdown':
# clear bits
mask = ~ (1 << 7 | 1 << 0)
controlword = controlword & mask
# set bits
mask = (1 << 2 | 1 << 1)
controlword = controlword | mask
return self.write_controlword(controlword)
# switch on 0xxx x111
if new_state == 'switch on':
# clear bits
mask = ~ (1 << 7)
controlword = controlword & mask
# set bits
mask = (1 << 2 | 1 << 1 | 1 << 0)
controlword = controlword | mask
return self.write_controlword(controlword)
# disable voltage 0xxx xx0x
if new_state == 'switch on':
# clear bits
mask = ~ (1 << 7 | 1 << 1)
controlword = controlword & mask
return self.write_controlword(controlword)
# quick stop 0xxx x01x
if new_state == 'quick stop':
# clear bits
mask = ~ (1 << 7 | 1 << 2)
controlword = controlword & mask
# set bits
mask = (1 << 1)
controlword = controlword | mask
return self.write_controlword(controlword)
# disable operation 0xxx 0111
if new_state == 'disable operation':
# clear bits
mask = ~ (1 << 7 | 1 << 3)
controlword = controlword & mask
# set bits
mask = (1 << 2 | 1 << 1 | 1 << 0)
controlword = controlword | mask
return self.write_controlword(controlword)
# enable operation 0xxx 1111
if new_state == 'enable operation':
# clear bits
mask = ~ (1 << 7)
controlword = controlword & mask
# set bits
mask = (1 << 3 | 1 << 2 | 1 << 1 | 1 << 0)
controlword = controlword | mask
return self.write_controlword(controlword)
# fault reset 1xxx xxxx
if new_state == 'fault reset':