forked from pyhys/minimalmodbus
-
Notifications
You must be signed in to change notification settings - Fork 0
/
minimalmodbus.py
4028 lines (3248 loc) · 129 KB
/
minimalmodbus.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 2019 Jonas Berg
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""MinimalModbus: A Python driver for Modbus RTU/ASCII via serial port (via USB, RS485 or RS232)."""
__author__ = "Jonas Berg"
__license__ = "Apache License, Version 2.0"
__status__ = "Production"
__url__ = "https://github.com/pyhys/minimalmodbus"
__version__ = "1.0.3a1"
import os
import struct
import sys
import time
import serial
if sys.version > "3":
import binascii
# Allow long also in Python3
# http://python3porting.com/noconv.html
if sys.version > "3":
long = int
_NUMBER_OF_BYTES_BEFORE_REGISTERDATA = 1 # Within the payload
_NUMBER_OF_BYTES_PER_REGISTER = 2
_MAX_NUMBER_OF_REGISTERS_TO_WRITE = 123
_MAX_NUMBER_OF_REGISTERS_TO_READ = 125
_MAX_NUMBER_OF_BITS_TO_WRITE = 1968 # 0x7B0
_MAX_NUMBER_OF_BITS_TO_READ = 2000 # 0x7D0
_MAX_NUMBER_OF_DECIMALS = 10 # Some instrument might store 0.00000154 Ampere as 154 etc
_MAX_BYTEORDER_VALUE = 3
_SECONDS_TO_MILLISECONDS = 1000
_BITS_PER_BYTE = 8
_ASCII_HEADER = ":"
_ASCII_FOOTER = "\r\n"
_BYTEPOSITION_FOR_ASCII_HEADER = 0 # Relative to plain response
_BYTEPOSITION_FOR_SLAVEADDRESS = 0 # Relative to (stripped) response
_BYTEPOSITION_FOR_FUNCTIONCODE = 1 # Relative to (stripped) response
_BYTEPOSITION_FOR_SLAVE_ERROR_CODE = 2 # Relative to (stripped) response
_BITNUMBER_FUNCTIONCODE_ERRORINDICATION = 7
# Several instrument instances can share the same serialport
_serialports = {} # Key: port name (str), value: port instance
_latest_read_times = {} # Key: port name (str), value: timestamp (float)
# ############### #
# Named constants #
# ############### #
MODE_RTU = "rtu"
MODE_ASCII = "ascii"
BYTEORDER_BIG = 0
BYTEORDER_LITTLE = 1
BYTEORDER_BIG_SWAP = 2
BYTEORDER_LITTLE_SWAP = 3
# Replace with enum when Python3 only
_PAYLOADFORMAT_BIT = "bit"
_PAYLOADFORMAT_BITS = "bits"
_PAYLOADFORMAT_FLOAT = "float"
_PAYLOADFORMAT_LONG = "long"
_PAYLOADFORMAT_REGISTER = "register"
_PAYLOADFORMAT_REGISTERS = "registers"
_PAYLOADFORMAT_STRING = "string"
_ALL_PAYLOADFORMATS = [
_PAYLOADFORMAT_BIT,
_PAYLOADFORMAT_BITS,
_PAYLOADFORMAT_FLOAT,
_PAYLOADFORMAT_LONG,
_PAYLOADFORMAT_REGISTER,
_PAYLOADFORMAT_REGISTERS,
_PAYLOADFORMAT_STRING,
]
# ######################## #
# Modbus instrument object #
# ######################## #
class Instrument:
"""Instrument class for talking to instruments (slaves).
Uses the Modbus RTU or ASCII protocols (via RS485 or RS232).
Args:
* port (str): The serial port name, for example ``/dev/ttyUSB0`` (Linux),
``/dev/tty.usbserial`` (OS X) or ``COM4`` (Windows).
* slaveaddress (int): Slave address in the range 1 to 247 (use decimal numbers,
not hex). Address 0 is for broadcast, and 248-255 are reserved.
* mode (str): Mode selection. Can be MODE_RTU or MODE_ASCII.
* close_port_after_each_call (bool): If the serial port should be closed after
each call to the instrument.
* debug (bool): Set this to :const:`True` to print the communication details
"""
def __init__(
self,
port,
slaveaddress,
mode=MODE_RTU,
close_port_after_each_call=False,
debug=False,
):
"""Initialize instrument and open corresponding serial port."""
self.address = slaveaddress
"""Slave address (int). Most often set by the constructor
(see the class documentation). """
self.mode = mode
"""Slave mode (str), can be MODE_RTU or MODE_ASCII.
Most often set by the constructor (see the class documentation).
Changing this will not affect how other instruments use the same serial port.
New in version 0.6.
"""
self.precalculate_read_size = True
"""If this is :const:`False`, the serial port reads until timeout
instead of just reading a specific number of bytes. Defaults to :const:`True`.
Changing this will not affect how other instruments use the same serial port.
New in version 0.5.
"""
self.debug = debug
"""Set this to :const:`True` to print the communication details.
Defaults to :const:`False`.
Most often set by the constructor (see the class documentation).
Changing this will not affect how other instruments use the same serial port.
"""
self.clear_buffers_before_each_transaction = True
"""If this is :const:`True`, the serial port read and write buffers are
cleared before each request to the instrument, to avoid cumulative byte
sync errors across multiple messages. Defaults to :const:`True`.
Changing this will not affect how other instruments use the same serial port.
New in version 1.0.
"""
self.close_port_after_each_call = close_port_after_each_call
"""If this is :const:`True`, the serial port will be closed after each
call. Defaults to :const:`False`.
Changing this will not affect how other instruments use the same serial port.
Most often set by the constructor (see the class documentation).
"""
self.handle_local_echo = False
"""Set to to :const:`True` if your RS-485 adaptor has local echo enabled.
Then the transmitted message will immeadiately appear at the receive
line of the RS-485 adaptor. MinimalModbus will then read and discard
this data, before reading the data from the slave.
Defaults to :const:`False`.
Changing this will not affect how other instruments use the same serial port.
New in version 0.7.
"""
self.serial = None
"""The serial port object as defined by the pySerial module. Created by the constructor.
Attributes that could be changed after initialisation:
- port (str): Serial port name.
- Most often set by the constructor (see the class documentation).
- baudrate (int): Baudrate in Baud.
- Defaults to 19200.
- parity (probably int): Parity. See the pySerial module for documentation.
- Defaults to serial.PARITY_NONE.
- bytesize (int): Bytesize in bits.
- Defaults to 8.
- stopbits (int): The number of stopbits.
- Defaults to 1.
- timeout (float): Read timeout value in seconds.
- Defaults to 0.05 s.
- write_timeout (float): Write timeout value in seconds.
- Defaults to 2.0 s.
"""
if port not in _serialports or not _serialports[port]:
self._print_debug("Create serial port {}".format(port))
self.serial = _serialports[port] = serial.Serial(
port=port,
baudrate=19200,
parity=serial.PARITY_NONE,
bytesize=8,
stopbits=1,
timeout=0.05,
write_timeout=2.0,
)
else:
self._print_debug("Serial port {} already exists".format(port))
self.serial = _serialports[port]
if (self.serial.port is None) or (not self.serial.is_open):
self._print_debug("Serial port {} is closed. Opening.".format(port))
self.serial.open()
if self.close_port_after_each_call:
self._print_debug("Closing serial port {}".format(port))
self.serial.close()
def __repr__(self):
"""Give string representation of the :class:`.Instrument` object."""
template = (
"{}.{}<id=0x{:x}, address={}, mode={}, close_port_after_each_call={}, "
+ "precalculate_read_size={}, clear_buffers_before_each_transaction={}, "
+ "handle_local_echo={}, debug={}, serial={}>"
)
return template.format(
self.__module__,
self.__class__.__name__,
id(self),
self.address,
self.mode,
self.close_port_after_each_call,
self.precalculate_read_size,
self.clear_buffers_before_each_transaction,
self.handle_local_echo,
self.debug,
self.serial,
)
def _print_debug(self, text):
if self.debug:
_print_out("MinimalModbus debug mode. " + text)
# ################################# #
# Methods for talking to the slave #
# ################################# #
def read_bit(self, registeraddress, functioncode=2):
"""Read one bit from the slave (instrument).
This is for a bit that has its individual address in the instrument.
Args:
* registeraddress (int): The slave register address (use decimal numbers, not hex).
* functioncode (int): Modbus function code. Can be 1 or 2.
Returns:
The bit value 0 or 1 (int).
Raises:
TypeError, ValueError, ModbusException,
serial.SerialException (inherited from IOError)
"""
_check_functioncode(functioncode, [1, 2])
return self._generic_command(
functioncode,
registeraddress,
number_of_bits=1,
payloadformat=_PAYLOADFORMAT_BIT,
)
def write_bit(self, registeraddress, value, functioncode=5):
"""Write one bit to the slave (instrument).
This is for a bit that has its individual address in the instrument.
Args:
* registeraddress (int): The slave register address (use decimal numbers, not hex).
* value (int or bool): 0 or 1, or True or False
* functioncode (int): Modbus function code. Can be 5 or 15.
Returns:
None
Raises:
TypeError, ValueError, ModbusException,
serial.SerialException (inherited from IOError)
"""
_check_functioncode(functioncode, [5, 15])
_check_int(value, minvalue=0, maxvalue=1, description="input value")
self._generic_command(
functioncode,
registeraddress,
value,
number_of_bits=1,
payloadformat=_PAYLOADFORMAT_BIT,
)
def read_bits(self, registeraddress, number_of_bits, functioncode=2):
"""Read multiple bits from the slave (instrument).
This is for bits that have individual addresses in the instrument.
Args:
* registeraddress (int): The slave register start address (use decimal
numbers, not hex).
* number_of_bits (int): Number of bits to read
* functioncode (int): Modbus function code. Can be 1 or 2.
Returns:
A list of bit values 0 or 1 (int). The first value in the list is for
the bit at the given address.
Raises:
TypeError, ValueError, ModbusException,
serial.SerialException (inherited from IOError)
"""
_check_functioncode(functioncode, [1, 2])
_check_int(
number_of_bits,
minvalue=1,
maxvalue=_MAX_NUMBER_OF_BITS_TO_READ,
description="number of bits",
)
return self._generic_command(
functioncode,
registeraddress,
number_of_bits=number_of_bits,
payloadformat=_PAYLOADFORMAT_BITS,
)
def write_bits(self, registeraddress, values):
"""Write multiple bits to the slave (instrument).
This is for bits that have individual addresses in the instrument.
Uses Modbus functioncode 15.
Args:
* registeraddress (int): The slave register start address (use decimal
numbers, not hex).
* values (list of int or bool): 0 or 1, or True or False. The first
value in the list is for the bit at the given address.
Returns:
None
Raises:
TypeError, ValueError, ModbusException,
serial.SerialException (inherited from IOError)
"""
if not isinstance(values, list):
raise TypeError(
'The "values parameter" must be a list. Given: {0!r}'.format(values)
)
# Note: The content of the list is checked at content conversion.
_check_int(
len(values),
minvalue=1,
maxvalue=_MAX_NUMBER_OF_BITS_TO_WRITE,
description="length of input list",
)
self._generic_command(
15,
registeraddress,
values,
number_of_bits=len(values),
payloadformat=_PAYLOADFORMAT_BITS,
)
def read_register(
self, registeraddress, number_of_decimals=0, functioncode=3, signed=False
):
"""Read an integer from one 16-bit register in the slave, possibly scaling it.
The slave register can hold integer values in the range 0 to 65535
("Unsigned INT16").
Args:
* registeraddress (int): The slave register address (use decimal numbers, not hex).
* number_of_decimals (int): The number of decimals for content conversion.
* functioncode (int): Modbus function code. Can be 3 or 4.
* signed (bool): Whether the data should be interpreted as unsigned or signed.
.. note:: The parameter number_of_decimals was named numberOfDecimals
before MinimalModbus 1.0
If a value of 77.0 is stored internally in the slave register as 770,
then use ``number_of_decimals=1`` which will divide the received data by 10
before returning the value.
Similarly ``number_of_decimals=2`` will divide the received data by 100 before
returning the value.
Some manufacturers allow negative values for some registers. Instead of
an allowed integer range 0 to 65535, a range -32768 to 32767 is allowed.
This is implemented as any received value in the upper range (32768 to
65535) is interpreted as negative value (in the range -32768 to -1).
Use the parameter ``signed=True`` if reading from a register that can hold
negative values. Then upper range data will be automatically converted into
negative return values (two's complement).
============== ================== ================ ===============
``signed`` Data type in slave Alternative name Range
============== ================== ================ ===============
:const:`False` Unsigned INT16 Unsigned short 0 to 65535
:const:`True` INT16 Short -32768 to 32767
============== ================== ================ ===============
Returns:
The register data in numerical value (int or float).
Raises:
TypeError, ValueError, ModbusException,
serial.SerialException (inherited from IOError)
"""
_check_functioncode(functioncode, [3, 4])
_check_int(
number_of_decimals,
minvalue=0,
maxvalue=_MAX_NUMBER_OF_DECIMALS,
description="number of decimals",
)
_check_bool(signed, description="signed")
return self._generic_command(
functioncode,
registeraddress,
number_of_decimals=number_of_decimals,
number_of_registers=1,
signed=signed,
payloadformat=_PAYLOADFORMAT_REGISTER,
)
def write_register(
self,
registeraddress,
value,
number_of_decimals=0,
functioncode=16,
signed=False,
):
"""Write an integer to one 16-bit register in the slave, possibly scaling it.
The slave register can hold integer values in the range 0 to
65535 ("Unsigned INT16").
Args:
* registeraddress (int): The slave register address (use decimal
numbers, not hex).
* value (int or float): The value to store in the slave register (might be
scaled before sending).
* number_of_decimals (int): The number of decimals for content conversion.
* functioncode (int): Modbus function code. Can be 6 or 16.
* signed (bool): Whether the data should be interpreted as unsigned or signed.
.. note:: The parameter number_of_decimals was named numberOfDecimals
before MinimalModbus 1.0
To store for example ``value=77.0``, use ``number_of_decimals=1`` if the slave register
will hold it as 770 internally. This will multiply ``value`` by 10 before sending it
to the slave register.
Similarly ``number_of_decimals=2`` will multiply ``value`` by 100 before sending
it to the slave register.
As the largest number that can be written to a register is 0xFFFF = 65535,
the ``value`` and ``number_of_decimals`` should max be 65535 when combined.
So when using ``number_of_decimals=3`` the maximum ``value`` is 65.535.
For discussion on negative values, the range and on alternative names,
see :meth:`.read_register`.
Use the parameter ``signed=True`` if writing to a register that can hold
negative values. Then negative input will be automatically converted into
upper range data (two's complement).
Returns:
None
Raises:
TypeError, ValueError, ModbusException,
serial.SerialException (inherited from IOError)
"""
_check_functioncode(functioncode, [6, 16])
_check_int(
number_of_decimals,
minvalue=0,
maxvalue=_MAX_NUMBER_OF_DECIMALS,
description="number of decimals",
)
_check_bool(signed, description="signed")
_check_numerical(value, description="input value")
self._generic_command(
functioncode,
registeraddress,
value,
number_of_decimals=number_of_decimals,
number_of_registers=1,
signed=signed,
payloadformat=_PAYLOADFORMAT_REGISTER,
)
def read_long(
self, registeraddress, functioncode=3, signed=False, byteorder=BYTEORDER_BIG
):
"""Read a long integer (32 bits) from the slave.
Long integers (32 bits = 4 bytes) are stored in two consecutive 16-bit
registers in the slave.
Args:
* registeraddress (int): The slave register start address (use decimal numbers,
not hex).
* functioncode (int): Modbus function code. Can be 3 or 4.
* signed (bool): Whether the data should be interpreted as unsigned or signed.
* byteorder (int): How multi-register data should be interpreted.
Defaults to BYTEORDER_BIG.
============== ================== ================ ==========================
``signed`` Data type in slave Alternative name Range
============== ================== ================ ==========================
:const:`False` Unsigned INT32 Unsigned long 0 to 4294967295
:const:`True` INT32 Long -2147483648 to 2147483647
============== ================== ================ ==========================
Returns:
The numerical value (int).
Raises:
TypeError, ValueError, ModbusException,
serial.SerialException (inherited from IOError)
"""
_check_functioncode(functioncode, [3, 4])
_check_bool(signed, description="signed")
return self._generic_command(
functioncode,
registeraddress,
number_of_registers=2,
signed=signed,
byteorder=byteorder,
payloadformat=_PAYLOADFORMAT_LONG,
)
def write_long(self, registeraddress, value, signed=False, byteorder=BYTEORDER_BIG):
"""Write a long integer (32 bits) to the slave.
Long integers (32 bits = 4 bytes) are stored in two consecutive 16-bit
registers in the slave.
Uses Modbus function code 16.
For discussion on number of bits, number of registers, the range
and on alternative names, see :meth:`.read_long`.
Args:
* registeraddress (int): The slave register start address (use decimal
numbers, not hex).
* value (int or long): The value to store in the slave.
* signed (bool): Whether the data should be interpreted as unsigned or signed.
* byteorder (int): How multi-register data should be interpreted.
Defaults to BYTEORDER_BIG.
Returns:
None
Raises:
TypeError, ValueError, ModbusException,
serial.SerialException (inherited from IOError)
"""
MAX_VALUE_LONG = 4294967295 # Unsigned INT32
MIN_VALUE_LONG = -2147483648 # INT32
_check_int(
value,
minvalue=MIN_VALUE_LONG,
maxvalue=MAX_VALUE_LONG,
description="input value",
)
_check_bool(signed, description="signed")
self._generic_command(
16,
registeraddress,
value,
number_of_registers=2,
signed=signed,
byteorder=byteorder,
payloadformat=_PAYLOADFORMAT_LONG,
)
def read_float(
self,
registeraddress,
functioncode=3,
number_of_registers=2,
byteorder=BYTEORDER_BIG,
):
r"""Read a floating point number from the slave.
Floats are stored in two or more consecutive 16-bit registers in the slave.
The encoding is according to the standard IEEE 754.
There are differences in the byte order used by different manufacturers.
A floating point value of 1.0 is encoded (in single precision) as 3f800000
(hex). In this implementation the data will be sent as ``'\x3f\x80'``
and ``'\x00\x00'`` to two consecutetive registers by default. Make sure to test that
it makes sense for your instrument. If not, change the ``byteorder`` argument.
Args:
* registeraddress (int): The slave register start address (use decimal
numbers, not hex).
* functioncode (int): Modbus function code. Can be 3 or 4.
* number_of_registers (int): The number of registers allocated for the float.
Can be 2 or 4.
* byteorder (int): How multi-register data should be interpreted.
Defaults to BYTEORDER_BIG.
.. note:: The parameter number_of_registers was named numberOfRegisters
before MinimalModbus 1.0
====================================== ================= =========== =================
Type of floating point number in slave Size Registers Range
====================================== ================= =========== =================
Single precision (binary32) 32 bits (4 bytes) 2 registers 1.4E-45 to 3.4E38
Double precision (binary64) 64 bits (8 bytes) 4 registers 5E-324 to 1.8E308
====================================== ================= =========== =================
Returns:
The numerical value (float).
Raises:
TypeError, ValueError, ModbusException,
serial.SerialException (inherited from IOError)
"""
_check_functioncode(functioncode, [3, 4])
_check_int(
number_of_registers,
minvalue=2,
maxvalue=4,
description="number of registers",
)
return self._generic_command(
functioncode,
registeraddress,
number_of_registers=number_of_registers,
byteorder=byteorder,
payloadformat=_PAYLOADFORMAT_FLOAT,
)
def write_float(
self, registeraddress, value, number_of_registers=2, byteorder=BYTEORDER_BIG
):
"""Write a floating point number to the slave.
Floats are stored in two or more consecutive 16-bit registers in the slave.
Uses Modbus function code 16.
For discussion on precision, number of registers and on byte order,
see :meth:`.read_float`.
Args:
* registeraddress (int): The slave register start address (use decimal
numbers, not hex).
* value (float or int): The value to store in the slave
* number_of_registers (int): The number of registers allocated for the float.
Can be 2 or 4.
* byteorder (int): How multi-register data should be interpreted.
Defaults to BYTEORDER_BIG.
.. note:: The parameter number_of_registers was named numberOfRegisters
before MinimalModbus 1.0
Returns:
None
Raises:
TypeError, ValueError, ModbusException,
serial.SerialException (inherited from IOError)
"""
_check_numerical(value, description="input value")
_check_int(
number_of_registers,
minvalue=2,
maxvalue=4,
description="number of registers",
)
self._generic_command(
16,
registeraddress,
value,
number_of_registers=number_of_registers,
byteorder=byteorder,
payloadformat=_PAYLOADFORMAT_FLOAT,
)
def read_string(self, registeraddress, number_of_registers=16, functioncode=3):
"""Read an ASCII string from the slave.
Each 16-bit register in the slave are interpreted as two characters
(each 1 byte = 8 bits). For example 16 consecutive registers can hold 32
characters (32 bytes).
International characters (Unicode/UTF-8) are not supported.
Args:
* registeraddress (int): The slave register start address (use decimal
numbers, not hex).
* number_of_registers (int): The number of registers allocated for the string.
* functioncode (int): Modbus function code. Can be 3 or 4.
.. note:: The parameter number_of_registers was named numberOfRegisters
before MinimalModbus 1.0
Returns:
The string (str).
Raises:
TypeError, ValueError, ModbusException,
serial.SerialException (inherited from IOError)
"""
_check_functioncode(functioncode, [3, 4])
_check_int(
number_of_registers,
minvalue=1,
maxvalue=_MAX_NUMBER_OF_REGISTERS_TO_READ,
description="number of registers for read string",
)
return self._generic_command(
functioncode,
registeraddress,
number_of_registers=number_of_registers,
payloadformat=_PAYLOADFORMAT_STRING,
)
def write_string(self, registeraddress, textstring, number_of_registers=16):
"""Write an ASCII string to the slave.
Each 16-bit register in the slave are interpreted as two characters
(each 1 byte = 8 bits). For example 16 consecutive registers can hold 32
characters (32 bytes).
Uses Modbus function code 16.
International characters (Unicode/UTF-8) are not supported.
Args:
* registeraddress (int): The slave register start address (use decimal
numbers, not hex).
* textstring (str): The string to store in the slave, must be ASCII.
* number_of_registers (int): The number of registers allocated for the string.
.. note:: The parameter number_of_registers was named numberOfRegisters
before MinimalModbus 1.0
If the ``textstring`` is longer than the ``2*number_of_registers``, an error is raised.
Shorter strings are padded with spaces.
Returns:
None
Raises:
TypeError, ValueError, ModbusException,
serial.SerialException (inherited from IOError)
"""
_check_int(
number_of_registers,
minvalue=1,
maxvalue=_MAX_NUMBER_OF_REGISTERS_TO_WRITE,
description="number of registers for write string",
)
_check_string(
textstring,
"input string",
minlength=1,
maxlength=2 * number_of_registers,
force_ascii=True,
)
self._generic_command(
16,
registeraddress,
textstring,
number_of_registers=number_of_registers,
payloadformat=_PAYLOADFORMAT_STRING,
)
def read_registers(self, registeraddress, number_of_registers, functioncode=3):
"""Read integers from 16-bit registers in the slave.
The slave registers can hold integer values in the range 0 to
65535 ("Unsigned INT16").
Args:
* registeraddress (int): The slave register start address (use decimal
numbers, not hex).
* number_of_registers (int): The number of registers to read, max 125 registers.
* functioncode (int): Modbus function code. Can be 3 or 4.
.. note:: The parameter number_of_registers was named numberOfRegisters
before MinimalModbus 1.0
Any scaling of the register data, or converting it to negative number
(two's complement) must be done manually.
Returns:
The register data (a list of int). The first value in the list is for
the register at the given address.
Raises:
TypeError, ValueError, ModbusException,
serial.SerialException (inherited from IOError)
"""
_check_functioncode(functioncode, [3, 4])
_check_int(
number_of_registers,
minvalue=1,
maxvalue=_MAX_NUMBER_OF_REGISTERS_TO_READ,
description="number of registers",
)
return self._generic_command(
functioncode,
registeraddress,
number_of_registers=number_of_registers,
payloadformat=_PAYLOADFORMAT_REGISTERS,
)
def write_registers(self, registeraddress, values):
"""Write integers to 16-bit registers in the slave.
The slave register can hold integer values in the range 0 to
65535 ("Unsigned INT16").
Uses Modbus function code 16.
The number of registers that will be written is defined by the length of
the ``values`` list.
Args:
* registeraddress (int): The slave register start address (use decimal
numbers, not hex).
* values (list of int): The values to store in the slave registers,
max 123 values. The first value in the list is for the register
at the given address.
.. note:: The parameter number_of_registers was named numberOfRegisters
before MinimalModbus 1.0
Any scaling of the register data, or converting it to negative number
(two's complement) must be done manually.
Returns:
None
Raises:
TypeError, ValueError, ModbusException,
serial.SerialException (inherited from IOError)
"""
if not isinstance(values, list):
raise TypeError(
'The "values parameter" must be a list. Given: {0!r}'.format(values)
)
_check_int(
len(values),
minvalue=1,
maxvalue=_MAX_NUMBER_OF_REGISTERS_TO_WRITE,
description="length of input list",
)
# Note: The content of the list is checked at content conversion.
self._generic_command(
16,
registeraddress,
values,
number_of_registers=len(values),
payloadformat=_PAYLOADFORMAT_REGISTERS,
)
# ############### #
# Generic command #
# ############### #
def _generic_command(
self,
functioncode,
registeraddress,
value=None,
number_of_decimals=0,
number_of_registers=0,
number_of_bits=0,
signed=False,
byteorder=BYTEORDER_BIG,
payloadformat=None,
):
"""Perform generic command for reading and writing registers and bits.
Args:
* functioncode (int): Modbus function code.
* registeraddress (int): The register address (use decimal numbers, not hex).
* value (numerical or string or None or list of int): The value to store
in the register. Depends on payloadformat.
* number_of_decimals (int): The number of decimals for content conversion.
Only for a single register.
* number_of_registers (int): The number of registers to read/write.
Only certain values allowed, depends on payloadformat.
* number_of_bits (int):T he number of registers to read/write.
* signed (bool): Whether the data should be interpreted as unsigned or
signed. Only for a single register or for payloadformat='long'.
* byteorder (int): How multi-register data should be interpreted.
* payloadformat (None or string): Any of the _PAYLOADFORMAT_* values
If a value of 77.0 is stored internally in the slave register as 770,
then use ``number_of_decimals=1`` which will divide the received data
from the slave by 10 before returning the value. Similarly
``number_of_decimals=2`` will divide the received data by 100 before returning
the value. Same functionality is also used when writing data to the slave.
Returns:
The register data in numerical value (int or float), or the bit value 0 or
1 (int), or ``None``.
Raises:
TypeError, ValueError, ModbusException,
serial.SerialException (inherited from IOError)
"""
ALL_ALLOWED_FUNCTIONCODES = [1, 2, 3, 4, 5, 6, 15, 16]
ALLOWED_FUNCTIONCODES = {}
ALLOWED_FUNCTIONCODES[_PAYLOADFORMAT_BIT] = [1, 2, 5, 15]
ALLOWED_FUNCTIONCODES[_PAYLOADFORMAT_BITS] = [1, 2, 15]
ALLOWED_FUNCTIONCODES[_PAYLOADFORMAT_REGISTER] = [3, 4, 6, 16]
ALLOWED_FUNCTIONCODES[_PAYLOADFORMAT_FLOAT] = [3, 4, 16]
ALLOWED_FUNCTIONCODES[_PAYLOADFORMAT_STRING] = [3, 4, 16]
ALLOWED_FUNCTIONCODES[_PAYLOADFORMAT_LONG] = [3, 4, 16]
ALLOWED_FUNCTIONCODES[_PAYLOADFORMAT_REGISTERS] = [3, 4, 16]
# Check input values
_check_functioncode(functioncode, ALL_ALLOWED_FUNCTIONCODES)
_check_registeraddress(registeraddress)
_check_int(
number_of_decimals,
minvalue=0,
maxvalue=_MAX_NUMBER_OF_DECIMALS,
description="number of decimals",
)
_check_int(
number_of_registers,
minvalue=0,
maxvalue=max(
_MAX_NUMBER_OF_REGISTERS_TO_READ, _MAX_NUMBER_OF_REGISTERS_TO_WRITE
),
description="number of registers",
)
_check_int(
number_of_bits,
minvalue=0,
maxvalue=max(_MAX_NUMBER_OF_BITS_TO_READ, _MAX_NUMBER_OF_BITS_TO_WRITE),
description="number of bits",
)
_check_bool(signed, description="signed")
_check_int(
byteorder,
minvalue=0,
maxvalue=_MAX_BYTEORDER_VALUE,
description="byteorder",
)
if payloadformat not in _ALL_PAYLOADFORMATS:
if not isinstance(payloadformat, str):
raise TypeError(
"The payload format should be a string. Given: {!r}".format(
payloadformat
)
)
raise ValueError(
"Wrong payload format variable. Given: {!r}".format(payloadformat)