-
Notifications
You must be signed in to change notification settings - Fork 145
/
minimalmodbus.py
4048 lines (3348 loc) · 131 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 2023 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."""
__author__ = "Jonas Berg"
__license__ = "Apache License, Version 2.0"
__url__ = "https://github.com/pyhys/minimalmodbus"
__version__ = "2.1.1"
import sys
if sys.version_info < (3, 8, 0):
raise ImportError(
"Your Python version is too old for this version of MinimalModbus"
)
import binascii
import enum
import os
import struct
import time
from typing import Any, Dict, List, Optional, Type, Union
import serial
_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
_BROADCAST_DELAY: float = 0.2 # seconds
_BITS_PER_BYTE = 8
_ASCII_HEADER = b":"
_ASCII_FOOTER = b"\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
_SLAVEADDRESS_BROADCAST = 0
# Several instrument instances can share the same serialport
_serialports: Dict[str, serial.Serial] = {} # Key: port name, value: port instance
_latest_read_times: Dict[str, float] = {} # Key: port name, value: timestamp
# ############### #
# Named constants #
# ############### #
MODE_RTU: str = "rtu"
"""Use Modbus RTU communication."""
MODE_ASCII: str = "ascii"
"""Use Modbus ASCII communication."""
BYTEORDER_BIG: int = 0
"""Use big endian byteorder."""
BYTEORDER_LITTLE: int = 1
"""Use little endian byteorder."""
BYTEORDER_BIG_SWAP: int = 2
"""Use big endian byteorder, with swap."""
BYTEORDER_LITTLE_SWAP: int = 3
"""Use litte endian byteorder, with swap."""
@enum.unique
class _Payloadformat(enum.Enum):
BIT = enum.auto()
BITS = enum.auto()
FLOAT = enum.auto()
LONG = enum.auto()
REGISTER = enum.auto()
REGISTERS = enum.auto()
STRING = enum.auto()
# ######################## #
# 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: The serial port name, for example ``/dev/ttyUSB0`` (Linux),
``/dev/tty.usbserial`` (OS X) or ``COM4`` (Windows).
It is also possible to pass in an already opened ``serial.Serial``
object (new in version 2.1).
* slaveaddress: Slave address in the range 0 to 247.
Address 0 is for broadcast, and 248-255 are reserved.
* mode: Mode selection. Can be :data:`minimalmodbus.MODE_RTU` or
:data:`minimalmodbus.MODE_ASCII`.
* close_port_after_each_call: If the serial port should be closed after
each call to the instrument.
* debug: Set this to :const:`True` to print the communication details
"""
def __init__(
self,
port: Union[str, serial.Serial],
slaveaddress: int,
mode: str = MODE_RTU,
close_port_after_each_call: bool = False,
debug: bool = False,
) -> None:
"""Initialize instrument and open corresponding serial port."""
self.address = slaveaddress
"""Slave address (int). Most often set by the constructor (see the class
documentation).
Slave address 0 is for broadcasting to all slaves (no responses are sent). It is
only possible to write infomation (not read) via broadcast. A long delay is
added after each transmission to allow the slowest slaves to digest the
information.
New in version 2.0: Support for broadcast
"""
self.mode = mode
"""Slave mode (str), can be :data:`minimalmodbus.MODE_RTU` or
:data:`minimalmodbus.MODE_ASCII`. Most often set by the constructor (see the
class documentation). Defaults to RTU.
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: Optional[serial.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 (use PARITY_xxx constants): Parity. See the pySerial module.
- Defaults to :const:`serial.PARITY_NONE`.
- bytesize (int): Bytesize in bits.
- Defaults to 8.
- stopbits (use STOPBITS_xxx constants): Number of stopbits. See pySerial.
- Defaults to :const:`serial.STOPBITS_ONE`.
- 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 _is_serial_object(port):
self.serial = port # type: ignore
elif isinstance(port, str) and (
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,
)
elif isinstance(port, str):
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.serial is None or not _is_serial_object(self.serial):
raise MasterReportedException("Failed to initialise serial port")
if not self.serial.is_open:
raise MasterReportedException("Failed to open serial port")
if self.close_port_after_each_call:
self._print_debug("Closing serial port {}".format(port))
self.serial.close()
self._latest_roundtrip_time: Optional[float] = None
def __repr__(self) -> str:
"""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,
)
@property
def roundtrip_time(self) -> Optional[float]:
"""Latest measured round-trip time, in seconds. Read only.
Note that the value is ``None`` if no data is available.
The round-trip time is the time from minimalmodbus sends request data,
to the time it receives response data from the instrument.
It is basically the time spent waiting on external communication.
Note that mimimalmodbus also sleeps (not included in the round trip time),
for example to fulfill the inter-message time interval or to give
slaves time to process broadcasted information.
New in version 2.0
"""
return self._latest_roundtrip_time
def _print_debug(self, text: str) -> None:
if self.debug:
print("MinimalModbus debug mode. " + text)
# ################################# #
# Methods for talking to the slave #
# ################################# #
def read_bit(self, registeraddress: int, functioncode: int = 2) -> int:
"""Read one bit from the slave (instrument).
This is for a bit that has its individual address in the instrument.
Args:
* registeraddress: The slave register address.
* functioncode Modbus function code. Can be 1 or 2.
Returns:
The bit value 0 or 1.
Raises:
TypeError, ValueError, ModbusException,
serial.SerialException (inherited from IOError)
"""
_check_functioncode(functioncode, [1, 2])
return int(
self._generic_command(
functioncode,
registeraddress,
number_of_bits=1,
payloadformat=_Payloadformat.BIT,
)
)
def write_bit(
self, registeraddress: int, value: int, functioncode: int = 5
) -> None:
"""Write one bit to the slave (instrument).
This is for a bit that has its individual address in the instrument.
Args:
* registeraddress: The slave register address.
* value: 0 or 1, or True or False
* functioncode: Modbus function code. Can be 5 or 15.
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: int, number_of_bits: int, functioncode: int = 2
) -> List[int]:
"""Read multiple bits from the slave (instrument).
This is for bits that have individual addresses in the instrument.
Args:
* registeraddress: The slave register start address.
* number_of_bits: Number of bits to read
* functioncode: Modbus function code. Can be 1 or 2.
Returns:
A list of bit values 0 or 1. 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",
)
returnvalue = self._generic_command(
functioncode,
registeraddress,
number_of_bits=number_of_bits,
payloadformat=_Payloadformat.BITS,
)
# Make sure that we really return a list of integers
assert isinstance(returnvalue, list)
return [int(x) for x in returnvalue]
def write_bits(self, registeraddress: int, values: List[int]) -> None:
"""Write multiple bits to the slave (instrument).
This is for bits that have individual addresses in the instrument.
Uses Modbus functioncode 15.
Args:
* registeraddress: The slave register start address.
* values: List of 0 or 1, or True or False. The first
value in the list is for the bit at the given address.
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: int,
number_of_decimals: int = 0,
functioncode: int = 3,
signed: bool = False,
) -> Union[int, float]:
"""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: The slave register address.
* number_of_decimals: The number of decimals for content conversion.
* functioncode: Modbus function code. Can be 3 or 4.
* signed: 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")
returnvalue = self._generic_command(
functioncode,
registeraddress,
number_of_decimals=number_of_decimals,
number_of_registers=1,
signed=signed,
payloadformat=_Payloadformat.REGISTER,
)
if int(returnvalue) == returnvalue:
return int(returnvalue)
return float(returnvalue)
def write_register(
self,
registeraddress: int,
value: Union[int, float],
number_of_decimals: int = 0,
functioncode: int = 16,
signed: bool = False,
) -> None:
"""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: The slave register address.
* value (int or float): The value to store in the slave register (might be
scaled before sending).
* number_of_decimals: The number of decimals for content conversion.
* functioncode: Modbus function code. Can be 6 or 16.
* signed: 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).
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: int,
functioncode: int = 3,
signed: bool = False,
byteorder: int = BYTEORDER_BIG,
number_of_registers: int = 2,
) -> int:
"""Read a long integer (32 or 64 bits) from the slave.
Long integers (32 bits = 4 bytes or 64 bits = 8 bytes) are stored in
two or four consecutive 16-bit registers in the slave respectively.
Args:
* registeraddress: The slave register start address.
* functioncode: Modbus function code. Can be 3 or 4.
* signed: Whether the data should be interpreted as unsigned or signed.
* byteorder: How multi-register data should be interpreted.
Use the BYTEORDER_xxx constants. Defaults to
:data:`minimalmodbus.BYTEORDER_BIG`.
* number_of_registers: The number of registers allocated for the long.
Can be 2 or 4. (New in version 2.1)
======================= ============== =============== =====================
``number_of_registers`` ``signed`` Slave data type Range
======================= ============== =============== =====================
2 :const:`False` Unsigned INT32 0 to 4294967295
2 :const:`True` INT32 -2147483648 to 2147483647
4 :const:`False` Unsigned INT64 0 to approx 1.8E19
4 :const:`True` INT64 Approx -9.2E18 to 9.2E18
======================= ============== =============== =====================
Returns:
The numerical value.
Raises:
TypeError, ValueError, ModbusException,
serial.SerialException (inherited from IOError)
"""
_check_functioncode(functioncode, [3, 4])
_check_bool(signed, description="signed")
_check_int(
number_of_registers,
minvalue=2,
maxvalue=4,
description="number of registers",
)
return int(
self._generic_command(
functioncode,
registeraddress,
number_of_registers=number_of_registers,
signed=signed,
byteorder=byteorder,
payloadformat=_Payloadformat.LONG,
)
)
def write_long(
self,
registeraddress: int,
value: int,
signed: bool = False,
byteorder: int = BYTEORDER_BIG,
number_of_registers: int = 2,
) -> None:
"""Write a long integer (32 or 64 bits) to the slave.
Long integers (32 bits = 4 bytes or 64 bits = 8 bytes) are stored in
two or four consecutive 16-bit registers in the slave respectively.
Uses Modbus function code 16.
For discussion on number of bits, number of registers and the range,
see :meth:`.read_long`.
Args:
* registeraddress: The slave register start address.
* value: The value to store in the slave.
* signed: Whether the data should be interpreted as unsigned or signed.
* byteorder: How multi-register data should be interpreted.
Use the BYTEORDER_xxx constants. Defaults to
:data:`minimalmodbus.BYTEORDER_BIG`.
* number_of_registers: The number of registers allocated for the long.
Can be 2 or 4. (New in version 2.1)
Raises:
TypeError, ValueError, ModbusException,
serial.SerialException (inherited from IOError)
"""
MAX_VALUE_LONG = 4294967295 # Unsigned INT32
MIN_VALUE_LONG = -2147483648 # INT32
MAX_VALUE_LONG_LONG = 18446744073709551615 # Unsigned INT64
MIN_VALUE_LONG_LONG = -9223372036854775808 # INT64
_check_int(
number_of_registers,
minvalue=2,
maxvalue=4,
description="number of registers",
)
if number_of_registers == 2:
_check_int(
value,
minvalue=MIN_VALUE_LONG,
maxvalue=MAX_VALUE_LONG,
description="input value",
)
elif number_of_registers == 4:
_check_int(
value,
minvalue=MIN_VALUE_LONG_LONG,
maxvalue=MAX_VALUE_LONG_LONG,
description="input value",
)
_check_bool(signed, description="signed")
self._generic_command(
16,
registeraddress,
value,
number_of_registers=number_of_registers,
signed=signed,
byteorder=byteorder,
payloadformat=_Payloadformat.LONG,
)
def read_float(
self,
registeraddress: int,
functioncode: int = 3,
number_of_registers: int = 2,
byteorder: int = BYTEORDER_BIG,
) -> float:
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 : The slave register start address.
* functioncode: Modbus function code. Can be 3 or 4.
* number_of_registers: The number of registers allocated for the float.
Can be 2 or 4.
* byteorder: How multi-register data should be interpreted.
Use the BYTEORDER_xxx constants. Defaults to
:data:`minimalmodbus.BYTEORDER_BIG`.
.. note:: The parameter number_of_registers was named numberOfRegisters
before MinimalModbus 1.0
=============================== ================= =========== =================
Type of floating point 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.
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 float(
self._generic_command(
functioncode,
registeraddress,
number_of_registers=number_of_registers,
byteorder=byteorder,
payloadformat=_Payloadformat.FLOAT,
)
)
def write_float(
self,
registeraddress: int,
value: Union[int, float],
number_of_registers: int = 2,
byteorder: int = BYTEORDER_BIG,
) -> None:
"""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: The slave register start address.
* value (float or int): The value to store in the slave
* number_of_registers: The number of registers allocated for the float.
Can be 2 or 4.
* byteorder: How multi-register data should be interpreted.
Use the BYTEORDER_xxx constants. Defaults to
:data:`minimalmodbus.BYTEORDER_BIG`.
.. note:: The parameter number_of_registers was named numberOfRegisters
before MinimalModbus 1.0
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: int, number_of_registers: int = 16, functioncode: int = 3
) -> str:
"""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: The slave register start address.
* number_of_registers: The number of registers allocated for the string.
* functioncode: Modbus function code. Can be 3 or 4.
.. note:: The parameter number_of_registers was named numberOfRegisters
before MinimalModbus 1.0
Returns:
The string.
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 str(
self._generic_command(
functioncode,
registeraddress,
number_of_registers=number_of_registers,
payloadformat=_Payloadformat.STRING,
)
)
def write_string(
self, registeraddress: int, textstring: str, number_of_registers: int = 16
) -> None:
"""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: The slave register start address.
* textstring: The string to store in the slave, must be ASCII.
* number_of_registers: 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: int, number_of_registers: int, functioncode: int = 3
) -> List[int]:
"""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: The slave register start address.
* number_of_registers: The number of registers to read, max 125 registers.
* functioncode: 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. 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",
)
returnvalue = self._generic_command(
functioncode,
registeraddress,
number_of_registers=number_of_registers,
payloadformat=_Payloadformat.REGISTERS,
)
# Make sure that we really return a list of integers
assert isinstance(returnvalue, list)
return [int(x) for x in returnvalue]
def write_registers(self, registeraddress: int, values: List[int]) -> None:
"""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: The slave register start address.
* values: 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.
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: int,
registeraddress: int,
value: Union[None, str, int, float, List[int]] = None,
number_of_decimals: int = 0,
number_of_registers: int = 0,
number_of_bits: int = 0,
signed: bool = False,
byteorder: int = BYTEORDER_BIG,
payloadformat: _Payloadformat = _Payloadformat.REGISTER,
) -> Any:
"""Perform generic command for reading and writing registers and bits.