/
schunk.py
1128 lines (900 loc) · 36 KB
/
schunk.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
# -*- coding: utf-8 -*-
# Copyright (c) 2014-2015 Matthias Geier
#
# 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.
"""Schunk Motion Protocol for Python.
See http://schunk.rtfd.org/
Example
-------
::
import schunk
import serial
mod = schunk.Module(schunk.SerialConnection(
0x0B, serial.Serial, port=0, baudrate=9600, timeout=1))
mod.move_pos(42)
"""
__version__ = "0.2.2"
import struct
import contextlib
import functools
class Module:
"""A Schunk module.
For further documentation see the __init__() docstring (which is
also used in the Sphinx documentation (http://schunk.rtfd.org/).
"""
def __init__(self, connection):
"""Create an object for controlling a Schunk module.
Parameters
----------
connection
Something that has an ``open()`` method which returns a
coroutine. This coroutine must accept a bytes object and
send it to a Schunk module, read the response (taking D-Len
into account) and yield the response (and further messages)
as a bytearray.
:class:`SerialConnection` happens to do exactly that.
"""
self._connection = connection
self._config = _Config(self)
def reference(self):
"""2.1.1 CMD REFERENCE (0x92).
A reference movement is completed.
"""
self._send(0x92, expected=b'OK')
def move_pos(self, position, velocity=None, acceleration=None,
current=None, jerk=None):
"""2.1.3 MOVE POS (0xB0).
Parameters
----------
position : float
Absolute position.
velocity, acceleration, current, jerk : float, optional
If one of them is not specified, all following arguments
must not be specified either.
Returns
-------
float
Estimated time to reach `position`.
If the time cannot be estimated, 0.0 is returned.
See Also
--------
move_pos_blocking, move_pos_rel
set_target_vel, set_target_acc, set_target_cur, set_target_jerk
"""
return self._move_pos_helper(0xB0, position, velocity,
acceleration, current, jerk)
def move_pos_blocking(self, position, velocity=None, acceleration=None,
current=None, jerk=None):
"""Move to position and wait until position is reached.
.. note:: *Impulse messages* must be activated for this to work,
see :meth:`toggle_impulse_message` and
:attr:`communication_mode`.
This applies to all ``*_blocking()`` methods.
Returns
-------
float
The final position.
See Also
--------
move_pos
"""
return self._move_pos_helper(0xB0, position, velocity,
acceleration, current, jerk,
blocking=True)
def move_pos_rel(self, position, velocity=None, acceleration=None,
current=None, jerk=None):
"""2.1.4 MOVE POS REL (0xB8).
Parameters
----------
position : float
Relative position.
velocity, acceleration, current, jerk : float, optional
If one of them is not specified, the following must not be
specified either.
Returns
-------
float
Estimated time to reach `position`.
If the time cannot be estimated, 0.0 is returned.
See Also
--------
move_pos_rel_blocking, move_pos
set_target_vel, set_target_acc, set_target_cur, set_target_jerk
"""
return self._move_pos_helper(0xB8, position, velocity,
acceleration, current, jerk)
def move_pos_rel_blocking(self, position, velocity=None, acceleration=None,
current=None, jerk=None):
"""Move to relative position and wait until position is reached.
Returns
-------
float
The actual relative motion.
See Also
--------
move_pos_rel
"""
return self._move_pos_helper(0xB8, position, velocity,
acceleration, current, jerk,
blocking=True)
def move_pos_time(self, position, velocity=None, acceleration=None,
current=None, time=None):
"""2.1.5 MOVE POS TIME (0xB1).
See Also
--------
move_pos_time_blocking, move_pos, set_target_time
"""
return self._move_pos_helper(0xB1, position, velocity,
acceleration, current, time)
def move_pos_time_blocking(self, position, velocity=None,
acceleration=None, current=None, time=None):
"""Move to position and wait until position is reached.
Returns
-------
float
The final position.
See Also
--------
move_pos_time
"""
return self._move_pos_helper(0xB1, position, velocity,
acceleration, current, time,
blocking=True)
def move_pos_time_rel(self, position, velocity=None, acceleration=None,
current=None, time=None):
"""2.1.6 MOVE POS TIME REL (0xB9).
See Also
--------
move_pos_time_rel_blocking, move_pos_rel, set_target_time
"""
return self._move_pos_helper(0xB9, position, velocity,
acceleration, current, time)
def move_pos_time_rel_blocking(self, position, velocity=None,
acceleration=None, current=None, time=None):
"""Move to position and wait until position is reached.
Returns
-------
float
The actual relative motion.
See Also
--------
move_pos_time_rel
"""
return self._move_pos_helper(0xB9, position, velocity,
acceleration, current, time,
blocking=True)
def set_target_vel(self, velocity):
"""2.1.14 SET TARGET VEL (0xA0).
Initially, the target velocity is set to 10% of the maximum.
"""
self._send(0xA0, struct.pack('<f', velocity), expected=b'OK')
def set_target_acc(self, acceleration):
"""2.1.15 SET TARGET ACC (0xA1).
Initially, the target acceleration is set to 10% of the maximum.
"""
self._send(0xA1, struct.pack('<f', acceleration), expected=b'OK')
def set_target_jerk(self, jerk):
"""2.1.16 SET TARGET JERK (0xA2).
Initially, the target jerk is set to 50% of the maximum.
"""
self._send(0xA2, struct.pack('<f', jerk), expected=b'OK')
def set_target_cur(self, current):
"""2.1.17 SET TARGET CUR (0xA3).
Initially, the target current is set to the nominal current.
"""
self._send(0xA3, struct.pack('<f', current), expected=b'OK')
def set_target_time(self, time):
"""2.1.18 SET TARGET TIME (0xA4)."""
self._send(0xA4, struct.pack('<f', time), expected=b'OK')
def stop(self):
"""2.1.19 CMD STOP (0x91)."""
self._send(0x91, expected=b'OK')
# Not implemented (see warnings in Schunk manual):
# 2.1.20 CMD EMERGENCY STOP (0x90)
def toggle_impulse_message(self):
"""2.2.6 CMD TOGGLE IMPULSE MESSAGE (0xE7).
.. note:: *Impulse messages* must be switched on for
``*_blocking()``, e.g. :meth:`move_pos_blocking`.
Returns
-------
bool
``True`` if impulse messages were switched on, ``False`` if
they were switched off.
"""
response = self._send(0xE7)
if response == b'ON':
return True
elif response == b'OFF':
return False
else:
raise SchunkError("Unexpected response: {}".format(response))
@property
def config(self):
"""2.3.1 SET CONFIG (0x81) / 2.3.2 GET CONFIG (0x80).
The `config` object has several attributes which can be queried
and changed.
Except where otherwise noted, the new settings are immediately
stored in the EEPROM but are only applied after the module has
been restarted.
Some options are read-only, some can only be set as "Profi"
user. See :meth:`change_user`.
Attributes
----------
module_type : bytes
firmware_version : int
protocol_version : int
hardware_version : int
firmware_date : bytes
eeprom : bytes
All configuration data is read/written in one process.
Depending on the type of user certain data might not be
written. After successful writing of the data, the module is
rebooted.
.. note:: This command should not be used with one's own
applications, as the structure of the data to be
received/sent is not known.
module_id : int (1..255)
group_id : int (1..255)
serial_baudrate : int (1200, 2400, 4800, 9600, 19200, 38400)
can_baudrate : int (50, 100, 125, 250, 500, 800, 1000)
communication_mode : int
See :const:`communication_modes`.
unit_system : int
See :const:`unit_systems`.
soft_high : float
The transferred value is not written to the EEPROM. The
settings are applied immediately.
soft_low : float
The transferred value is not written to the EEPROM. The
settings are applied immediately.
gear_ratio : float
The Gear Ratio 1 is changed (the command has no use with an
integer unit system). The transferred value is written to
the EEPROM and applied immediately.
max_velocity : float
max_acceleration : float
max_current : float
nom_current : float
max_jerk : float
offset_phase_a : int
offset_phase_b : int
data_crc : int
A CRC16 over all variable and not module specified
paramenters (like serial number, current offset).
reference_offset : float
serial_number : int
order_number : int
"""
return self._config
def get_state(self):
"""2.5.1 GET STATE (0x95).
Return the module status and other information.
The time parameter (to get state repeatedly) is disabled
(because impulse messages are not supported).
The mode parameter is always set to request everything
(position, velocity and current).
Returns
-------
position, velocity, current : float
Dito.
status : dict
See :func:`decode_status`.
error_code : int
See :const:`error_codes` for a mapping to strings.
"""
data = struct.pack('<fB', 0.0, 0x01 | 0x02 | 0x04)
pos, vel, cur, status, error = self._send(0x95, data, '<3fBB')
return pos, vel, cur, decode_status(status), error
def reboot(self):
"""2.5.2 CMD REBOOT (0xE0)."""
self._send(0xE0, expected=b'OK')
def change_user(self, password=None):
"""2.5.6 CHANGE USER (0xE3).
If no password is specified - or if the password is wrong - the
user is changed to "User".
The default password for "Profi" is "Schunk", but don't tell
anyone!
After a reboot, the default user is "User".
"""
if password is None:
data = b''
elif isinstance(password, str):
data = password.encode()
else:
data = password
ok, user = self._send(0xE3, data, '2sB')
if ok != b'OK':
raise SchunkError("Error changing user")
return {0x00: "User",
0x01: "Diag",
0x02: "Profi",
0x03: "Advanced"}[user]
def check_mc_pc_communication(self):
"""2.5.7 CHECK MC PC COMMUNICATION (0xE4).
Returns
-------
bool
``True`` on success.
"""
response = self._send(0xE4, fmt=_test_format_string)
if response != _test_values:
raise SchunkError("Wrong response: {}".format(response))
return True
def check_pc_mc_communication(self):
"""2.5.8 CHECK PC MC COMMUNICATION (0xE5).
Returns
-------
bool
``True`` on success.
"""
data = struct.pack(_test_format_string, *_test_values)
self._send(0xE5, data, expected=b'OK\x00')
return True
def ack(self):
"""2.8.1.4 CMD ACK (0x8B).
Acknowledgement of a pending error message.
"""
self._send(0x8B, expected=b'OK')
def get_detailed_error_info(self):
"""2.8.1.5 GET DETAILED ERROR INFO (0x96).
Returns
-------
command : {"ERROR", "WARNING", "INFO"}
error_code : int
See :const:`error_codes` for a mapping to strings.
data : float
The value can be interpreted by the Schunk Service.
Raises
------
SchunkError
If no error is active, or no detailed information is
available, the command is raising an exception saying:
``INFO FAILED (0x05)``.
"""
command, error_code, data = self._send(0x96, fmt='<BBf')
command = {0x88: "ERROR", 0x89: "WARNING", 0x8A: "INFO"}[command]
return command, error_code, data
def wait_until_position_reached(self):
"""Repeatedly check the state until the position is reached.
This should only be used if impulse messages are disabled (see
:meth:`toggle_impulse_message`).
"""
gen = self._connection.open()
try:
while True:
# 2.5.1 GET STATE (0x95)
response = gen.send(_data_frame(0x95, b'\x00\x00\x00\x00\x01'))
if response[1] == 0x94:
# 2.2.3 CMD POS REACHED (0x94) is ignored
response = gen.send(None)
position, status, error = _check_response(
response, 0x95, '<fBB')
if status & 0x80: # position reached
return position
except (KeyboardInterrupt, SystemExit):
gen.close()
gen = self._connection.open()
# 2.1.19 CMD STOP (0x91)
gen.send(b'\x01\x91')
# response message is ignored
raise
finally:
gen.close()
def _send(self, command, data=b'', fmt=None, expected=None):
"""Send message, receive response.
If the expected number of bytes doesn't match, an error is
raised.
If expected is a string, it is used as format strings to decode
the received bytes.
If expected is a bytes object, it is compared to the received
data. If they are equal, the function returns, if not, an error
is raised.
"""
with contextlib.closing(self._connection.open()) as gen:
response = gen.send(_data_frame(command, data))
if response[1] == 0x94:
# 2.2.3 CMD POS REACHED (0x94) is ignored
response = gen.send(None)
return _check_response(response, command, fmt, expected)
def _move_pos_helper(self, command, *args, **kwargs):
"""Move to the given position.
If blocking=False, the movement is started and the estimated
time is immediately returned.
If the time cannot be estimated, 0.0 is returned.
If blocking=True, the final position (or the actual relative
movement) is returned when the movement is finished.
Use command=0xB0 for absolute and command=0xB8 for relative
positions. For the "time" variants, use command=0xB1 and
command=0xB9, respectively.
Trailing None arguments are removed, None arguments between
other arguments are not allowed.
At least one argument (position) has to be specified.
"""
n = len(args)
while n > 1 and args[n - 1] is None:
n -= 1
data = struct.pack('<{}f'.format(n), *args[:n])
# Work-around since Python 2 doesn't support keyword-only args:
blocking = kwargs.pop('blocking', False)
assert not kwargs
gen = self._connection.open()
try:
response = gen.send(_data_frame(command, data))
if response[1] == 0x94:
# 2.2.3 CMD POS REACHED (0x94) is ignored
response = gen.send(None)
response = _check_response(response, command)
if response == b'OK':
est_time = 0.0
elif len(response) == 4:
est_time, = struct.unpack_from('<f', response)
else:
raise SchunkError("Unexpected reponse: {}".format(response))
if not blocking:
return est_time
else:
# 2.2.3 CMD POS REACHED (0x94)
position, = _check_response(next(gen), 0x94, '<f')
return position
except (KeyboardInterrupt, SystemExit):
gen.close()
gen = self._connection.open()
# 2.1.19 CMD STOP (0x91)
gen.send(b'\x01\x91')
# response message is ignored
raise
finally:
gen.close()
def _data_frame(command, data=b''):
"""Create a bytearray of D-Len, command code and binary data."""
frame = bytearray()
frame.append(len(data) + 1) # command byte is counted!
frame.append(command)
frame.extend(data)
return frame
def _check_response(response, command, fmt=None, expected=None):
"""Check if the response has the correct format/content."""
if len(response) < 2:
raise SchunkError("Not enough data in response")
dlen = response[0]
cmd_code = response[1]
if dlen != len(response) - 1:
raise SchunkError("D-Len mismatch in response")
if dlen == 2:
error = response[2]
error_prefix = {
0x88: "CMD ERROR: ",
0x89: "CMD WARNING: ",
0x8A: "CMD INFO: ",
command: "",
}.get(cmd_code, "Command code 0x{:02X}: ".format(cmd_code))
error_string = "{} (0x{:02X})".format(
error_codes.get(error, "UNKNOWN"), error)
raise SchunkError(error_prefix + error_string)
if cmd_code != command:
raise SchunkError(
"Unexpected command code in response: {}".format(hex(cmd_code)))
del response[:2] # remove D-Len and command code
if expected is not None:
if fmt is not None:
raise TypeError("At least one of {fmt, expected} must be None")
if response != expected:
err = "Unexpected response: {} instead of {}"
raise SchunkError(err.format(response, expected))
if fmt is not None:
size = struct.calcsize(fmt)
if len(response) != size:
err = "Unexpected payload size in reponse: {} instead of {}"
raise SchunkError(err.format(len(response), size))
response = struct.unpack_from(fmt, response)
return response
class SchunkError(Exception):
"""This exception is raised on all kinds of errors."""
pass
class _Config:
"""Helper class for the Module.config property."""
_params = {
'module_id': (b'\x01', 'B'),
'group_id': (b'\x02', 'B'),
'serial_baudrate': (b'\x03', 'H'),
'can_baudrate': (b'\x04', 'H'),
'communication_mode': (b'\x05', 'B'),
'unit_system': (b'\x06', 'B'),
'soft_high': (b'\x07', 'f'),
'soft_low': (b'\x08', 'f'),
'max_velocity': (b'\x09', 'f'),
'max_acceleration': (b'\x0A', 'f'),
'max_current': (b'\x0B', 'f'),
'nom_current': (b'\x0C', 'f'),
'max_jerk': (b'\x0D', 'f'),
'offset_phase_a': (b'\x0E', 'H'),
'offset_phase_b': (b'\x0F', 'H'),
'data_crc': (b'\x13', 'H'),
'reference_offset': (b'\x14', 'f'),
'serial_number': (b'\x15', 'I'),
'order_number': (b'\x16', 'I'),
'gear_ratio': (b'\x18', 'f'),
'eeprom': (b'\xFE', None),
'module_type': (None, '8s4x2x2x2x21x5x'),
# 'order_number' is already available
'firmware_version': (None, '8x4xH2x2x21x5x'),
'protocol_version': (None, '8x4x2xH2x21x5x'),
'hardware_version': (None, '8x4x2x2xH21x5x'),
'firmware_date': (None, '8x4x2x2x2x21s5x'),
# Note: There are 5 more bytes which the Schunk manual doesn't mention.
# The meaning of these mysterious bytes is not known.
'_internal': (None, '8x4x2x2x2x21x5s'),
}
def __init__(self, module):
# Avoid __setattr__:
vars(self)['_module'] = module
def _getAttributeNames(self):
"""Return all possible attributes.
This is useful for auto-completion (e.g. IPython).
"""
return self._params
def __getattr__(self, name):
"""2.3.2 GET CONFIG (0x80)."""
try:
cmd_byte, format_string = self._params[name]
except KeyError:
raise AttributeError("Invalid parameter: {}".format(name))
if cmd_byte is None:
result, = self._module._send(0x80, fmt=format_string)
firstbyte = None
elif format_string is None:
result = self._module._send(0x80, cmd_byte)
firstbyte = result[0:1]
result = result[1:]
else:
firstbyte, result = self._module._send(0x80, cmd_byte,
'<s' + format_string)
if firstbyte != cmd_byte:
raise SchunkError("Unexpected subcommand: {}".format(firstbyte))
return result
def __setattr__(self, name, value):
"""2.3.1 SET CONFIG (0x81)."""
try:
cmd_byte, format_string = self._params[name]
except KeyError:
raise AttributeError("Invalid parameter: {}".format(name))
if cmd_byte is None:
raise AttributeError("{} is read-only".format(name))
if format_string is not None:
value = struct.pack('<' + format_string, value)
result, = self._module._send(0x81, cmd_byte + value, '3s')
if result != b'OK' + cmd_byte:
raise SchunkError("Error setting {}".format(name))
def coroutine(func):
"""Decorator for generator functions that calls next() initially."""
@functools.wraps(func)
def start(*args, **kwargs):
gen = func(*args, **kwargs)
next(gen)
return gen
return start
class SerialConnection:
"""A serial connection.
For further documentation see the __init__() docstring.
"""
def __init__(self, id, serialmanager, *args, **kwargs):
"""Prepare a serial connection.
This can be used to initialize a :class:`Module`.
The connection is opened with :meth:`open`.
Parameters
----------
id : int
Module ID of the Schunk device.
serialmanager
A callable (to be called with ``*args`` and ``**kwargs``)
that must return a context manager which in turn must have
``read()`` and ``write()`` methods (and it should close the
connection automatically in the end).
This is typically ``serial.Serial`` from PySerial_, but
anything with a similar API can be used.
.. _PySerial: http://pyserial.sf.net/
.. note:: there should be a timeout, otherwise you may have
to wait forever for the functions to return if
there is an error.
On the other hand, receiving multiple responses
only works if there is no timeout in between.
Multiple responses are needed for the blocking
movement commands, e.g.
:meth:`Module.move_pos_blocking`.
*args, **kwargs
All further arguments are forwarded to `serialmanager`.
See Also
--------
Module
Examples
--------
Using PySerial_:
>>> import serial
>>> conn = SerialConnection(0x0B, serial.Serial, port=0,
... baudrate=9600, timeout=1)
"""
self._id = id
self._serialmanager = serialmanager
self._serial_args = args
self._serial_kwargs = kwargs
@coroutine
def open(self):
"""Open a serial connection.
A coroutine (a.k.a. generator object) is returned which can be
used to send and receive one or more data frames.
Calling ``.send(data)`` on this coroutine creates a serial frame
around `data`, sends it to the module and waits for a response.
`data` must have at least two bytes, D-Len and command code.
The (optional) rest are parameters.
2 Group/ID bytes are added in the beginning and 2 CRC bytes in
the end. The first byte is always 0x05 (= message from master
to module), the second byte holds the module ID.
When receiving a response, the 2 CRC bytes are checked (and
removed), as well as the 2 Group/ID bytes.
The connection is kept open and the coroutine can be invoked
repeatedly to receive further data frames.
Use ``.send(None)`` or the built-in ``next()`` function to
receive a data frame without sending anything.
When the desired number of frames has been received, the
connection has to be closed with the generator's ``close()``
method.
Yields
------
bytes
Response data received from the module, including D-Len and
command code.
If the first byte indicates an error (0x03), the
response is returned normally and the error has to be
handled in the calling function. Error responses always have
a D-Len of 2, i.e. they have 3 bytes: D-Len, command code
and error code.
See Also
--------
crc16
"""
response = None
with self._serialmanager(*self._serial_args,
**self._serial_kwargs) as serial:
serial.flushInput()
while True:
next_msg = yield response
if next_msg is not None:
frame = bytearray()
frame.append(0x05)
frame.append(self._id)
frame.extend(next_msg)
frame.extend(crc16(frame))
if serial.write(frame) != len(frame):
raise SchunkSerialError("Error sending data")
response = serial.read(3)
if len(response) < 3:
raise SchunkSerialError("Error reading response")
response = bytearray(response)
msg_type, module_id, dlen = response
if module_id != self._id:
raise SchunkSerialError("Module ID mismatch")
elif msg_type not in (0x03, 0x07):
raise SchunkSerialError(
"Unexpected message type in response: "
"0x{:02X}".format(msg_type))
crclen = 2
the_rest = serial.read(dlen + crclen)
if len(the_rest) < dlen + crclen:
raise SchunkSerialError("Not enough data in response")
response.extend(the_rest)
crc = response[-crclen:]
del response[-crclen:] # Remove CRC
if crc != crc16(response):
raise SchunkSerialError("CRC error in response")
del response[:2] # Remove first 2 bytes, leaving dlen intact
if msg_type == 0x03 and dlen != 2:
# This should never happen, but who knows ...
raise SchunkSerialError(
"Message type 0x03, D-Len {}, data: {}".format(
dlen, the_rest))
# Note: error checking (if dlen == 2) is not done here
class SchunkSerialError(SchunkError):
"""Exception class for errors related to serial connections.
It is derived from :exc:`SchunkError`, so it is normally
sufficient to check only for this::
try:
...
# Something that may throw SchunkError or SchunkSerialError
...
except SchunkError as e:
# Do something with e
...
"""
pass
def decode_status(status):
"""This is internally used in :meth:`Module.get_state`.
>>> status = decode_status(0x03)
>>> from pprint import pprint
>>> pprint(status) # to get pretty dict display
{'brake': False,
'error': False,
'move_end': False,
'moving': True,
'position_reached': False,
'program_mode': False,
'referenced': True,
'warning': False}
"""
statuses = ('referenced', 'moving', 'program_mode', 'warning', 'error',
'brake', 'move_end', 'position_reached')
return {name: bool(status & 1 << bit) for bit, name in enumerate(statuses)}
def crc16_increment(crc, data):
"""Incrementally calculate CRC16.
Implementation according to Schunk Motion Protocol documentation.
Parameters
----------
crc : int
Previous CRC16 (2 bytes)
data : int
Data to append (1 byte)
Returns
-------
int
New CRC16 (again 2 bytes) after appending `data`.
See Also
--------
crc16
"""
# Note: if data is in 0..255, data & 0x00FF doesn't do anything.
# But this is how it's done in the Schunk manual:
return ((crc & 0xFF00) >> 8) ^ _crc16_tbl[(crc & 0x00FF) ^ (data & 0x00FF)]
def crc16(data):
"""Calculate CRC16 for a sequence of bytes.
Parameters
----------
data : iterable of integers (0..255)
A sequece of bytes.
Returns
-------
bytes
CRC16 of `data` (2 bytes, little endian, a.k.a. '<H').
See Also
--------
crc16_increment
"""
crc = 0x0
for b in data:
crc = crc16_increment(crc, b)
return struct.pack('<H', crc)
# Table copied from the Schunk manual:
_crc16_tbl = [
0x0000, 0xC0C1, 0xC181, 0x0140, 0xC301, 0x03C0, 0x0280, 0xC241,
0xC601, 0x06C0, 0x0780, 0xC741, 0x0500, 0xC5C1, 0xC481, 0x0440,
0xCC01, 0x0CC0, 0x0D80, 0xCD41, 0x0F00, 0xCFC1, 0xCE81, 0x0E40,
0x0A00, 0xCAC1, 0xCB81, 0x0B40, 0xC901, 0x09C0, 0x0880, 0xC841,