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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603
|
"""
.. note:: This section is based on `MODBUS Application Protocol Specification
V1.1b3`_
The Protocol Data Unit (PDU) is the request or response message and is
indepedent of the underlying communication layer. This module only implements
requests PDU's.
A request PDU contains two parts: a function code and request data. A response
PDU contains the function code from the request and response data. The general
structure is listed in table below:
+---------------+-----------------+
| **Field** | **Size** (bytes)|
+---------------+-----------------+
| Function code | 1 |
+---------------+-----------------+
| data | N |
+---------------+-----------------+
Below you see the request PDU with function code 1, requesting status of 3
coils, starting from coil 100.
..
Note: the backslash in the bytes below are escaped using an extra back
slash. Without escaping the bytes aren't printed correctly in the HTML
output of this docs.
To work with the bytes in Python you need to remove the escape sequences.
`b'\\x01\\x00d` -> `b\x01\x00d`
.. code-block:: python
>>> req_pdu = b'\\x01\x00d\\x00\\x03'
>>> function_code = req_pdu[:1]
>>> function_code
b'\\x01'
>>> starting_address = req_pdu[1:3]
>>> starting_address
b'\\x00d'
>>> quantity = req_pdu[3:]
>>> quantity
b'\\x00\\x03'
A response PDU could look like this::
>>> resp_pdu = b'\\x01\\x01\\x06'
>>> function_code = resp_pdu[:1]
>>> function_code
b'\\x01'
>>> byte_count = resp[1:2]
>>> byte_count
b'\\x01'
>>> coil_status = resp[2:]
'b\\x06'
"""
from __future__ import division
import struct
import math
try:
from inspect import getfullargspec
except ImportError:
# inspect.getfullargspec was introduced in Python 3.4.
# Earlier versions have inspect.getargspec.
from inspect import getargspec as getfullargspec
try:
from functools import reduce
except ImportError:
pass
from umodbus import conf, log
from umodbus.exceptions import (error_code_to_exception_map,
IllegalDataValueError, IllegalFunctionError,
IllegalDataAddressError)
from umodbus.utils import memoize, get_function_code_from_request_pdu
# Function related to data access.
READ_COILS = 1
READ_DISCRETE_INPUTS = 2
READ_HOLDING_REGISTERS = 3
READ_INPUT_REGISTERS = 4
WRITE_SINGLE_COIL = 5
WRITE_SINGLE_REGISTER = 6
WRITE_MULTIPLE_COILS = 15
WRITE_MULTIPLE_REGISTERS = 16
READ_FILE_RECORD = 20
WRITE_FILE_RECORD = 21
READ_WRITE_MULTIPLE_REGISTERS = 23
READ_FIFO_QUEUE = 24
# Diagnostic functions, only available when using serial line.
READ_EXCEPTION_STATUS = 7
DIAGNOSTICS = 8
GET_COMM_EVENT_COUNTER = 11
GET_COM_EVENT_LOG = 12
REPORT_SERVER_ID = 17
def pdu_to_function_code_or_raise_error(resp_pdu):
""" Parse response PDU and return of :class:`ModbusFunction` or
raise error.
:param resp_pdu: PDU of response.
:return: Subclass of :class:`ModbusFunction` matching the response.
:raises ModbusError: When response contains error code.
"""
function_code = struct.unpack('>B', resp_pdu[0:1])[0]
if function_code not in function_code_to_function_map.keys():
error_code = struct.unpack('>B', resp_pdu[1:2])[0]
raise error_code_to_exception_map[error_code]
return function_code
def create_function_from_response_pdu(resp_pdu, req_pdu=None):
""" Parse response PDU and return instance of :class:`ModbusFunction` or
raise error.
:param resp_pdu: PDU of response.
:param req_pdu: Request PDU, some functions require more info than in
response PDU in order to create instance. Default is None.
:return: Number or list with response data.
"""
function_code = pdu_to_function_code_or_raise_error(resp_pdu)
function = function_code_to_function_map[function_code]
if req_pdu is not None and \
'req_pdu' in getfullargspec(function.create_from_response_pdu).args: # NOQA
return function.create_from_response_pdu(resp_pdu, req_pdu)
return function.create_from_response_pdu(resp_pdu)
@memoize
def create_function_from_request_pdu(pdu):
""" Return function instance, based on request PDU.
:param pdu: Array of bytes.
:return: Instance of a function.
"""
function_code = get_function_code_from_request_pdu(pdu)
try:
function_class = function_code_to_function_map[function_code]
except KeyError:
raise IllegalFunctionError(function_code)
return function_class.create_from_request_pdu(pdu)
def expected_response_pdu_size_from_request_pdu(pdu):
""" Return number of bytes expected for response PDU, based on request PDU.
:param pdu: Array of bytes.
:return: number of bytes.
"""
return create_function_from_request_pdu(pdu).expected_response_pdu_size
class ModbusFunction(object):
function_code = None
class ReadCoils(ModbusFunction):
""" Implement Modbus function code 01.
"This function code is used to read from 1 to 2000 contiguous status of
coils in a remote device. The Request PDU specifies the starting
address, i.e. the address of the first coil specified, and the number
of coils. In the PDU Coils are addressed starting at zero. Therefore
coils numbered 1-16 are addressed as 0-15.
The coils in the response message are packed as one coil per bit of the
data field. Status is indicated as 1= ON and 0= OFF. The LSB of the
first data byte contains the output addressed in the query. The other
coils follow toward the high order end of this byte, and from low order
to high order in subsequent bytes.
If the returned output quantity is not a multiple of eight, the
remaining bits in the final data byte will be padded with zeros (toward
the high order end of the byte). The Byte Count field specifies the
quantity of complete bytes of data."
-- MODBUS Application Protocol Specification V1.1b3, chapter 6.1
The request PDU with function code 01 must be 5 bytes:
================ ===============
Field Length (bytes)
================ ===============
Function code 1
Starting address 2
Quantity 2
================ ===============
The PDU can unpacked to this:
..
Note: the backslash in the bytes below are escaped using an extra back
slash. Without escaping the bytes aren't printed correctly in the HTML
output of this docs.
To work with the bytes in Python you need to remove the escape sequences.
`b'\\x01\\x00d` -> `b\x01\x00d`
.. code-block:: python
>>> struct.unpack('>BHH', b'\\x01\\x00d\\x00\\x03')
(1, 100, 3)
The reponse PDU varies in length, depending on the request. Each 8 coils
require 1 byte. The amount of bytes needed represent status of the coils to
can be calculated with: bytes = ceil(quantity / 8). This response
contains ceil(3 / 8) = 1 byte to describe the status of the coils. The
structure of a compleet response PDU looks like this:
================ ===============
Field Length (bytes)
================ ===============
Function code 1
Byte count 1
Coil status n
================ ===============
Assume the status of 102 is 0, 101 is 1 and 100 is also 1. This is binary
011 which is decimal 3.
The PDU can packed like this::
>>> struct.pack('>BBB', function_code, byte_count, 3)
b'\\x01\\x01\\x03'
"""
function_code = READ_COILS
max_quantity = 2000
format_character = 'B'
data = None
starting_address = None
_quantity = None
@property
def quantity(self):
return self._quantity
@quantity.setter
def quantity(self, value):
""" Set number of coils to read. Quantity must be between 1 and 2000.
:param value: Quantity.
:raises: IllegalDataValueError.
"""
if not (1 <= value <= 2000):
raise IllegalDataValueError('Quantify field of request must be a '
'value between 0 and '
'{0}.'.format(2000))
self._quantity = value
@property
def request_pdu(self):
""" Build request PDU to read coils.
:return: Byte array of 5 bytes with PDU.
"""
if None in [self.starting_address, self.quantity]:
# TODO Raise proper exception.
raise Exception
return struct.pack('>BHH', self.function_code, self.starting_address,
self.quantity)
@classmethod
def create_from_request_pdu(cls, pdu):
""" Create instance from request PDU.
:param pdu: A request PDU.
:return: Instance of this class.
"""
_, starting_address, quantity = struct.unpack('>BHH', pdu)
instance = cls()
instance.starting_address = starting_address
instance.quantity = quantity
return instance
@property
def expected_response_pdu_size(self):
""" Return number of bytes expected for response PDU.
:return: number of bytes.
"""
return 2 + int(math.ceil(self.quantity / 8))
def create_response_pdu(self, data):
""" Create response pdu.
:param data: A list with 0's and/or 1's.
:return: Byte array of at least 3 bytes.
"""
log.debug('Create single bit response pdu {0}.'.format(data))
bytes_ = [data[i:i + 8] for i in range(0, len(data), 8)]
# Reduce each all bits per byte to a number. Byte
# [0, 0, 0, 0, 0, 1, 1, 1] is intepreted as binary en is decimal 3.
for index, byte in enumerate(bytes_):
bytes_[index] = \
reduce(lambda a, b: (a << 1) + b, list(reversed(byte)))
log.debug('Reduced single bit data to {0}.'.format(bytes_))
# The first 2 B's of the format encode the function code (1 byte) and
# the length (1 byte) of the following byte series. Followed by # a B
# for every byte in the series of bytes. 3 lead to the format '>BBB'
# and 257 lead to the format '>BBBB'.
fmt = '>BB' + self.format_character * len(bytes_)
return struct.pack(fmt, self.function_code, len(bytes_), *bytes_)
@classmethod
def create_from_response_pdu(cls, resp_pdu, req_pdu):
""" Create instance from response PDU.
Response PDU is required together with the quantity of coils read.
:param resp_pdu: Byte array with request PDU.
:param quantity: Number of coils read.
:return: Instance of :class:`ReadCoils`.
"""
read_coils = cls()
read_coils.quantity = struct.unpack('>H', req_pdu[-2:])[0]
byte_count = struct.unpack('>B', resp_pdu[1:2])[0]
fmt = '>' + ('B' * byte_count)
bytes_ = struct.unpack(fmt, resp_pdu[2:])
data = list()
for i, value in enumerate(bytes_):
padding = 8 if (read_coils.quantity - (8 * i)) // 8 > 0 \
else read_coils.quantity % 8
fmt = '{{0:0{padding}b}}'.format(padding=padding)
# Create binary representation of integer, convert it to a list
# and reverse the list.
data = data + [int(i) for i in fmt.format(value)][::-1]
read_coils.data = data
return read_coils
def execute(self, slave_id, route_map):
""" Execute the Modbus function registered for a route.
:param slave_id: Slave id.
:param route_map: Instance of modbus.route.Map.
:return: Result of call to endpoint.
"""
values = []
for address in range(self.starting_address,
self.starting_address + self.quantity):
endpoint = route_map.match(slave_id, self.function_code, address)
if endpoint is None:
raise IllegalDataAddressError()
values.append(endpoint(slave_id=slave_id, address=address,
function_code=self.function_code))
return values
class ReadDiscreteInputs(ModbusFunction):
""" Implement Modbus function code 02.
"This function code is used to read from 1 to 2000 contiguous status of
discrete inputs in a remote device. The Request PDU specifies the
starting address, i.e. the address of the first input specified, and
the number of inputs. In the PDU Discrete Inputs are addressed starting
at zero. Therefore Discrete inputs numbered 1-16 are addressed as
0-15.
The discrete inputs in the response message are packed as one input per
bit of the data field. Status is indicated as 1= ON; 0= OFF. The LSB
of the first data byte contains the input addressed in the query. The
other inputs follow toward the high order end of this byte, and from
low order to high order in subsequent bytes.
If the returned input quantity is not a multiple of eight, the
remaining bits in the final d ata byte will be padded with zeros
(toward the high order end of the byte). The Byte Count field specifies
the quantity of complete bytes of data."
-- MODBUS Application Protocol Specification V1.1b3, chapter 6.2
The request PDU with function code 02 must be 5 bytes:
================ ===============
Field Length (bytes)
================ ===============
Function code 1
Starting address 2
Quantity 2
================ ===============
The PDU can unpacked to this:
..
Note: the backslash in the bytes below are escaped using an extra back
slash. Without escaping the bytes aren't printed correctly in the HTML
output of this docs.
To work with the bytes in Python you need to remove the escape sequences.
`b'\\x01\\x00d` -> `b\x01\x00d`
.. code-block:: python
>>> struct.unpack('>BHH', b'\\x02\\x00d\\x00\\x03')
(2, 100, 3)
The reponse PDU varies in length, depending on the request. 8 inputs
require 1 byte. The amount of bytes needed represent status of the inputs
to can be calculated with: bytes = ceil(quantity / 8). This response
contains ceil(3 / 8) = 1 byte to describe the status of the inputs. The
structure of a compleet response PDU looks like this:
================ ===============
Field Length (bytes)
================ ===============
Function code 1
Byte count 1
Coil status n
================ ===============
Assume the status of 102 is 0, 101 is 1 and 100 is also 1. This is binary
011 which is decimal 3.
The PDU can packed like this::
>>> struct.pack('>BBB', function_code, byte_count, 3)
b'\\x02\\x01\\x03'
"""
function_code = READ_DISCRETE_INPUTS
max_quantity = 2000
format_character = 'B'
data = None
starting_address = None
_quantity = None
@property
def quantity(self):
return self._quantity
@quantity.setter
def quantity(self, value):
""" Set number of inputs to read. Quantity must be between 1 and 2000.
:param value: Quantity.
:raises: IllegalDataValueError.
"""
if not (1 <= value <= 2000):
raise IllegalDataValueError('Quantify field of request must be a '
'value between 0 and '
'{0}.'.format(2000))
self._quantity = value
@property
def request_pdu(self):
""" Build request PDU to read discrete inputs.
:return: Byte array of 5 bytes with PDU.
"""
if None in [self.starting_address, self.quantity]:
# TODO Raise proper exception.
raise Exception
return struct.pack('>BHH', self.function_code, self.starting_address,
self.quantity)
@classmethod
def create_from_request_pdu(cls, pdu):
""" Create instance from request PDU.
:param pdu: A request PDU.
:return: Instance of this class.
"""
_, starting_address, quantity = struct.unpack('>BHH', pdu)
instance = cls()
instance.starting_address = starting_address
instance.quantity = quantity
return instance
@property
def expected_response_pdu_size(self):
""" Return number of bytes expected for response PDU.
:return: number of bytes.
"""
return 2 + int(math.ceil(self.quantity / 8))
def create_response_pdu(self, data):
""" Create response pdu.
:param data: A list with 0's and/or 1's.
:return: Byte array of at least 3 bytes.
"""
log.debug('Create single bit response pdu {0}.'.format(data))
bytes_ = [data[i:i + 8] for i in range(0, len(data), 8)]
# Reduce each all bits per byte to a number. Byte
# [0, 0, 0, 0, 0, 1, 1, 1] is intepreted as binary en is decimal 3.
for index, byte in enumerate(bytes_):
bytes_[index] = \
reduce(lambda a, b: (a << 1) + b, list(reversed(byte)))
log.debug('Reduced single bit data to {0}.'.format(bytes_))
# The first 2 B's of the format encode the function code (1 byte) and
# the length (1 byte) of the following byte series. Followed by # a B
# for every byte in the series of bytes. 3 lead to the format '>BBB'
# and 257 lead to the format '>BBBB'.
fmt = '>BB' + self.format_character * len(bytes_)
return struct.pack(fmt, self.function_code, len(bytes_), *bytes_)
@classmethod
def create_from_response_pdu(cls, resp_pdu, req_pdu):
""" Create instance from response PDU.
Response PDU is required together with the quantity of inputs read.
:param resp_pdu: Byte array with request PDU.
:param quantity: Number of inputs read.
:return: Instance of :class:`ReadDiscreteInputs`.
"""
read_discrete_inputs = cls()
read_discrete_inputs.quantity = struct.unpack('>H', req_pdu[-2:])[0]
byte_count = struct.unpack('>B', resp_pdu[1:2])[0]
fmt = '>' + ('B' * byte_count)
bytes_ = struct.unpack(fmt, resp_pdu[2:])
data = list()
for i, value in enumerate(bytes_):
padding = 8 if (read_discrete_inputs.quantity - (8 * i)) // 8 > 0 \
else read_discrete_inputs.quantity % 8
fmt = '{{0:0{padding}b}}'.format(padding=padding)
# Create binary representation of integer, convert it to a list
# and reverse the list.
data = data + [int(i) for i in fmt.format(value)][::-1]
read_discrete_inputs.data = data
return read_discrete_inputs
def execute(self, slave_id, route_map):
""" Execute the Modbus function registered for a route.
:param slave_id: Slave id.
:param route_map: Instance of modbus.route.Map.
:return: Result of call to endpoint.
"""
values = []
for address in range(self.starting_address,
self.starting_address + self.quantity):
endpoint = route_map.match(slave_id, self.function_code, address)
if endpoint is None:
raise IllegalDataAddressError()
values.append(endpoint(slave_id=slave_id, address=address,
function_code=self.function_code))
return values
class ReadHoldingRegisters(ModbusFunction):
""" Implement Modbus function code 03.
"This function code is used to read the contents of a contiguous block
of holding registers in a remote device. The Request PDU specifies the
starting register address and the number of registers. In the PDU
Registers are addressed starting at zero. Therefore registers numbered
1-16 are addressed as 0-15.
The register data in the response message are packed as two bytes per
register, with the binary contents right justified within each byte.
For each register, the first byte contains the high order bits and the
second contains the low order bits."
-- MODBUS Application Protocol Specification V1.1b3, chapter 6.3
The request PDU with function code 03 must be 5 bytes:
================ ===============
Field Length (bytes)
================ ===============
Function code 1
Starting address 2
Quantity 2
================ ===============
The PDU can unpacked to this:
..
Note: the backslash in the bytes below are escaped using an extra back
slash. Without escaping the bytes aren't printed correctly in the HTML
output of this docs.
To work with the bytes in Python you need to remove the escape sequences.
`b'\\x01\\x00d` -> `b\x01\x00d`
.. code-block:: python
>>> struct.unpack('>BHH', b'\\x03\\x00d\\x00\\x03')
(3, 100, 3)
The reponse PDU varies in length, depending on the request. By default,
holding registers are 16 bit (2 bytes) values. So values of 3 holding
registers is expressed in 2 * 3 = 6 bytes.
================ ===============
Field Length (bytes)
================ ===============
Function code 1
Byte count 1
Register values Quantity * 2
================ ===============
Assume the value of 100 is 8, 101 is 0 and 102 is also 15.
The PDU can packed like this::
>>> data = [8, 0, 15]
>>> struct.pack('>BBHHH', function_code, len(data) * 2, *data)
b'\\x03\\x06\\x00\\x08\\x00\\x00\\x00\\x0f'
"""
function_code = READ_HOLDING_REGISTERS
max_quantity = 0x007D
data = None
starting_address = None
_quantity = None
@property
def quantity(self):
return self._quantity
@quantity.setter
def quantity(self, value):
""" Set number of registers to read. Quantity must be between 1 and
0x00FD.
:param value: Quantity.
:raises: IllegalDataValueError.
"""
if not (1 <= value <= 0x007D):
raise IllegalDataValueError('Quantify field of request must be a '
'value between 0 and '
'{0}.'.format(0x007D))
self._quantity = value
@property
def request_pdu(self):
""" Build request PDU to read coils.
:return: Byte array of 5 bytes with PDU.
"""
if None in [self.starting_address, self.quantity]:
# TODO Raise proper exception.
raise Exception
return struct.pack('>BHH', self.function_code, self.starting_address,
self.quantity)
@classmethod
def create_from_request_pdu(cls, pdu):
""" Create instance from request PDU.
:param pdu: A request PDU.
:return: Instance of this class.
"""
_, starting_address, quantity = struct.unpack('>BHH', pdu)
instance = cls()
instance.starting_address = starting_address
instance.quantity = quantity
return instance
@property
def expected_response_pdu_size(self):
""" Return number of bytes expected for response PDU.
:return: number of bytes.
"""
return 2 + self.quantity * 2
def create_response_pdu(self, data):
""" Create response pdu.
:param data: A list with values.
:return: Byte array of at least 4 bytes.
"""
log.debug('Create multi bit response pdu {0}.'.format(data))
fmt = '>BB' + conf.TYPE_CHAR * len(data)
return struct.pack(fmt, self.function_code, len(data) * 2, *data)
@classmethod
def create_from_response_pdu(cls, resp_pdu, req_pdu):
""" Create instance from response PDU.
Response PDU is required together with the number of registers read.
:param resp_pdu: Byte array with request PDU.
:param quantity: Number of coils read.
:return: Instance of :class:`ReadCoils`.
"""
read_holding_registers = cls()
read_holding_registers.quantity = struct.unpack('>H', req_pdu[-2:])[0]
read_holding_registers.byte_count = \
struct.unpack('>B', resp_pdu[1:2])[0]
fmt = '>' + (conf.TYPE_CHAR * read_holding_registers.quantity)
read_holding_registers.data = list(struct.unpack(fmt, resp_pdu[2:]))
return read_holding_registers
def execute(self, slave_id, route_map):
""" Execute the Modbus function registered for a route.
:param slave_id: Slave id.
:param route_map: Instance of modbus.route.Map.
:return: Result of call to endpoint.
"""
values = []
for address in range(self.starting_address,
self.starting_address + self.quantity):
endpoint = route_map.match(slave_id, self.function_code, address)
if endpoint is None:
raise IllegalDataAddressError()
values.append(endpoint(slave_id=slave_id, address=address,
function_code=self.function_code))
return values
class ReadInputRegisters(ModbusFunction):
""" Implement Modbus function code 04.
"This function code is used to read from 1 to 125 contiguous input
registers in a remote device. The Request PDU specifies the starting
register address and the number of registers. In the PDU Registers are
addressed starting at zero. Therefore input registers numbered 1-16 are
addressed as 0-15.
The register data in the response message are packed as two bytes per
register, with the binary contents right justified within each byte.
For each register, the first byte contains the high order bits and the
second contains the low order bits."
-- MODBUS Application Protocol Specification V1.1b3, chapter 6.4
The request PDU with function code 04 must be 5 bytes:
================ ===============
Field Length (bytes)
================ ===============
Function code 1
Starting address 2
Quantity 2
================ ===============
The PDU can unpacked to this:
..
Note: the backslash in the bytes below are escaped using an extra back
slash. Without escaping the bytes aren't printed correctly in the HTML
output of this docs.
To work with the bytes in Python you need to remove the escape sequences.
`b'\\x01\\x00d` -> `b\x01\x00d`
.. code-block:: python
>>> struct.unpack('>BHH', b'\\x04\\x00d\\x00\\x03')
(4, 100, 3)
The reponse PDU varies in length, depending on the request. By default,
holding registers are 16 bit (2 bytes) values. So values of 3 holding
registers is expressed in 2 * 3 = 6 bytes.
================ ===============
Field Length (bytes)
================ ===============
Function code 1
Byte count 1
Register values Quantity * 2
================ ===============
Assume the value of 100 is 8, 101 is 0 and 102 is also 15.
The PDU can packed like this::
>>> data = [8, 0, 15]
>>> struct.pack('>BBHHH', function_code, len(data) * 2, *data)
b'\\x04\\x06\\x00\\x08\\x00\\x00\\x00\\x0f'
"""
function_code = READ_INPUT_REGISTERS
max_quantity = 0x007D
data = None
starting_address = None
_quantity = None
@property
def quantity(self):
return self._quantity
@quantity.setter
def quantity(self, value):
""" Set number of registers to read. Quantity must be between 1 and
0x00FD.
:param value: Quantity.
:raises: IllegalDataValueError.
"""
if not (1 <= value <= 0x007D):
raise IllegalDataValueError('Quantify field of request must be a '
'value between 0 and '
'{0}.'.format(0x007D))
self._quantity = value
@property
def request_pdu(self):
""" Build request PDU to read coils.
:return: Byte array of 5 bytes with PDU.
"""
if None in [self.starting_address, self.quantity]:
# TODO Raise proper exception.
raise Exception
return struct.pack('>BHH', self.function_code, self.starting_address,
self.quantity)
@classmethod
def create_from_request_pdu(cls, pdu):
""" Create instance from request PDU.
:param pdu: A request PDU.
:return: Instance of this class.
"""
_, starting_address, quantity = struct.unpack('>BHH', pdu)
instance = cls()
instance.starting_address = starting_address
instance.quantity = quantity
return instance
@property
def expected_response_pdu_size(self):
""" Return number of bytes expected for response PDU.
:return: number of bytes.
"""
return 2 + self.quantity * 2
def create_response_pdu(self, data):
""" Create response pdu.
:param data: A list with values.
:return: Byte array of at least 4 bytes.
"""
log.debug('Create multi bit response pdu {0}.'.format(data))
fmt = '>BB' + conf.TYPE_CHAR * len(data)
return struct.pack(fmt, self.function_code, len(data) * 2, *data)
@classmethod
def create_from_response_pdu(cls, resp_pdu, req_pdu):
""" Create instance from response PDU.
Response PDU is required together with the number of registers read.
:param resp_pdu: Byte array with request PDU.
:param quantity: Number of coils read.
:return: Instance of :class:`ReadCoils`.
"""
read_input_registers = cls()
read_input_registers.quantity = struct.unpack('>H', req_pdu[-2:])[0]
fmt = '>' + (conf.TYPE_CHAR * read_input_registers.quantity)
read_input_registers.data = list(struct.unpack(fmt, resp_pdu[2:]))
return read_input_registers
def execute(self, slave_id, route_map):
""" Execute the Modbus function registered for a route.
:param slave_id: Slave id.
:param route_map: Instance of modbus.route.Map.
:return: Result of call to endpoint.
"""
values = []
for address in range(self.starting_address,
self.starting_address + self.quantity):
endpoint = route_map.match(slave_id, self.function_code, address)
if endpoint is None:
raise IllegalDataAddressError()
values.append(endpoint(slave_id=slave_id, address=address,
function_code=self.function_code))
return values
class WriteSingleCoil(ModbusFunction):
""" Implement Modbus function code 05.
"This function code is used to write a single output to either ON or
OFF in a remote device. The requested ON/OFF state is specified by a
constant in the request data field. A value of FF 00 hex requests the
output to be ON. A value of 00 00 requests it to be OFF. All other
values are illegal and will not affect the output.
The Request PDU specifies the address of the coil to be forced. Coils
are addressed starting at zero. Therefore coil numbered 1 is addressed
as 0. The requested ON/OFF state is specified by a constant in the
Coil Value field. A value of 0XFF00 requests the coil to be ON. A value
of 0X0000 requests the coil to be off. All other values are illegal and
will not affect the coil.
The normal response is an echo of the request, returned after the coil
state has been written."
-- MODBUS Application Protocol Specification V1.1b3, chapter 6.5
The request PDU with function code 05 must be 5 bytes:
================ ===============
Field Length (bytes)
================ ===============
Function code 1
Address 2
Value 2
================ ===============
The PDU can unpacked to this:
..
Note: the backslash in the bytes below are escaped using an extra back
slash. Without escaping the bytes aren't printed correctly in the HTML
output of this docs.
To work with the bytes in Python you need to remove the escape sequences.
`b'\\x01\\x00d` -> `b\x01\x00d`
.. code-block:: python
>>> struct.unpack('>BHH', b'\\x05\\x00d\\xFF\\x00')
(5, 100, 65280)
The reponse PDU is a copy of the request PDU.
================ ===============
Field Length (bytes)
================ ===============
Function code 1
Address 2
Value 2
================ ===============
"""
function_code = WRITE_SINGLE_COIL
format_character = 'B'
address = None
data = None
_value = None
@property
def value(self):
if self._value == 0xFF00:
return 1
return self._value
@value.setter
def value(self, value):
if value not in [0, 1, 0xFF00]:
raise IllegalDataValueError
value = 0xFF00 if value == 1 else value
self._value = value
@property
def request_pdu(self):
""" Build request PDU to write single coil.
:return: Byte array of 5 bytes with PDU.
"""
if None in [self.address, self.value]:
# TODO Raise proper exception.
raise Exception
return struct.pack('>BHH', self.function_code, self.address,
self._value)
@classmethod
def create_from_request_pdu(cls, pdu):
""" Create instance from request PDU.
:param pdu: A response PDU.
:return: Instance of this class.
"""
_, address, value = struct.unpack('>BHH', pdu)
value = 1 if value == 0xFF00 else value
instance = cls()
instance.address = address
instance.value = value
return instance
@property
def expected_response_pdu_size(self):
""" Return number of bytes expected for response PDU.
:return: number of bytes.
"""
return 5
def create_response_pdu(self):
""" Create response pdu.
:param data: A list with values.
:return: Byte array of at least 4 bytes.
"""
fmt = '>BHH'
return struct.pack(fmt, self.function_code, self.address, self._value)
@classmethod
def create_from_response_pdu(cls, resp_pdu):
""" Create instance from response PDU.
:param resp_pdu: Byte array with request PDU.
:return: Instance of :class:`WriteSingleCoil`.
"""
write_single_coil = cls()
address, value = struct.unpack('>HH', resp_pdu[1:5])
value = 1 if value == 0xFF00 else value
write_single_coil.address = address
write_single_coil.data = value
return write_single_coil
def execute(self, slave_id, route_map):
""" Execute the Modbus function registered for a route.
:param slave_id: Slave id.
:param route_map: Instance of modbus.route.Map.
"""
endpoint = route_map.match(slave_id, self.function_code, self.address)
if endpoint is None:
raise IllegalDataAddressError()
endpoint(slave_id=slave_id, address=self.address, value=self.value,
function_code=self.function_code)
class WriteSingleRegister(ModbusFunction):
""" Implement Modbus function code 06.
"This function code is used to write a single holding register in a
remote device. The Request PDU specifies the address of the register to
be written. Registers are addressed starting at zero. Therefore
register numbered 1 is addressed as 0. The normal response is an echo
of the request, returned after the register contents have been
written."
-- MODBUS Application Protocol Specification V1.1b3, chapter 6.6
The request PDU with function code 06 must be 5 bytes:
================ ===============
Field Length (bytes)
================ ===============
Function code 1
Address 2
Value 2
================ ===============
The PDU can unpacked to this:
..
Note: the backslash in the bytes below are escaped using an extra back
slash. Without escaping the bytes aren't printed correctly in the HTML
output of this docs.
To work with the bytes in Python you need to remove the escape sequences.
`b'\\x01\\x00d` -> `b\x01\x00d`
.. code-block:: python
>>> struct.unpack('>BHH', b'\\x06\\x00d\\x00\\x03')
(6, 100, 3)
The reponse PDU is a copy of the request PDU.
================ ===============
Field Length (bytes)
================ ===============
Function code 1
Address 2
Value 2
================ ===============
"""
function_code = WRITE_SINGLE_REGISTER
address = None
data = None
_value = None
@property
def value(self):
return self._value
@value.setter
def value(self, value):
""" Value to be written on register.
:param value: An integer.
:raises: IllegalDataValueError when value isn't in range.
"""
try:
struct.pack('>' + conf.TYPE_CHAR, value)
except struct.error:
raise IllegalDataValueError
self._value = value
@property
def request_pdu(self):
""" Build request PDU to write single register.
:return: Byte array of 5 bytes with PDU.
"""
if None in [self.address, self.value]:
# TODO Raise proper exception.
raise Exception
return struct.pack('>BH' + conf.TYPE_CHAR, self.function_code,
self.address, self.value)
@classmethod
def create_from_request_pdu(cls, pdu):
""" Create instance from request PDU.
:param pdu: A request PDU.
:return: Instance of this class.
"""
_, address, value = \
struct.unpack('>BH' + conf.MULTI_BIT_VALUE_FORMAT_CHARACTER, pdu)
instance = cls()
instance.address = address
instance.value = value
return instance
@property
def expected_response_pdu_size(self):
""" Return number of bytes expected for response PDU.
:return: number of bytes.
"""
return 5
def create_response_pdu(self):
fmt = '>BH' + conf.TYPE_CHAR
return struct.pack(fmt, self.function_code, self.address, self.value)
@classmethod
def create_from_response_pdu(cls, resp_pdu):
""" Create instance from response PDU.
:param resp_pdu: Byte array with request PDU.
:return: Instance of :class:`WriteSingleRegister`.
"""
write_single_register = cls()
address, value = struct.unpack('>H' + conf.TYPE_CHAR, resp_pdu[1:5])
write_single_register.address = address
write_single_register.data = value
return write_single_register
def execute(self, slave_id, route_map):
""" Execute the Modbus function registered for a route.
:param slave_id: Slave id.
:param route_map: Instance of modbus.route.Map.
"""
endpoint = route_map.match(slave_id, self.function_code, self.address)
if endpoint is None:
raise IllegalDataAddressError()
endpoint(slave_id=slave_id, address=self.address, value=self.value,
function_code=self.function_code)
class WriteMultipleCoils(ModbusFunction):
""" Implement Modbus function 15 (0x0F) Write Multiple Coils.
"This function code is used to force each coil in a sequence of coils
to either ON or OFF in a remote device. The Request PDU specifies the
coil references to be forced. Coils are addressed starting at zero.
Therefore coil numbered 1 is addressed as 0.
The requested ON/OFF states are specified by contents of the request
data field. A logical '1' in a bit position of the field requests the
corresponding output to be ON. A logical '0' requests it to be OFF.
The normal response returns the function code, starting address, and
quantity of coils forced."
-- MODBUS Application Protocol Specification V1.1b3, chapter 6.11
The request PDU with function code 15 must be at least 7 bytes:
================ ===============
Field Length (bytes)
================ ===============
Function code 1
Starting Address 2
Quantity 2
Byte count 1
Value n
================ ===============
The PDU can unpacked to this:
..
Note: the backslash in the bytes below are escaped using an extra back
slash. Without escaping the bytes aren't printed correctly in the HTML
output of this docs.
To work with the bytes in Python you need to remove the escape sequences.
`b'\\x01\\x00d` -> `b\x01\x00d`
.. code-block:: python
>>> struct.unpack('>BHHBB', b'\\x0f\\x00d\\x00\\x03\\x01\\x05')
(16, 100, 3, 1, 5)
The reponse PDU is 5 bytes and contains following structure:
================ ===============
Field Length (bytes)
================ ===============
Function code 1
Starting address 2
Quantity 2
================ ===============
"""
function_code = WRITE_MULTIPLE_COILS
starting_address = None
_values = None
_data = None
@property
def values(self):
return self._values
@values.setter
def values(self, values):
if not (1 <= len(values) <= 0x7B0):
raise IllegalDataValueError
for value in values:
if value not in [0, 1]:
raise IllegalDataValueError
self._values = values
@property
def request_pdu(self):
if None in [self.starting_address, self._values]:
raise IllegalDataValueError
bytes_ = [self.values[i:i + 8] for i in range(0, len(self.values), 8)]
# Reduce each all bits per byte to a number. Byte
# [0, 0, 0, 0, 0, 1, 1, 1] is intepreted as binary en is decimal 3.
for index, byte in enumerate(bytes_):
bytes_[index] = \
reduce(lambda a, b: (a << 1) + b, list(reversed(byte)))
fmt = '>BHHB' + 'B' * len(bytes_)
return struct.pack(fmt, self.function_code, self.starting_address,
len(self.values), (len(self.values) + 7) // 8,
*bytes_)
@classmethod
def create_from_request_pdu(cls, pdu):
""" Create instance from request PDU.
This method requires some clarification regarding the unpacking of
the status that are being passed to the callbacks.
A coil status can be 0 or 1. The request PDU contains at least 1 byte,
representing the status for 1 to 8 coils.
Assume a request with starting address 100, quantity set to 3 and the
value byte is 6. 0b110 is the binary reprensention of decimal 6. The
Least Significant Bit (LSB) is status of coil with starting address. So
status of coil 100 is 0, status of coil 101 is 1 and status of coil 102
is 1 too.
coil address 102 101 100
1 1 0
Again, assume starting address 100 and byte value is 6. But now
quantity is 4. So the value byte is addressing 4 coils. The binary
representation of 6 is now 0b0110. LSB again is 0, meaning status of
coil 100 is 0. Status of 101 and 102 is 1, like in the previous
example. Status of coil 104 is 0.
coil address 104 102 101 100
0 1 1 0
In short: the binary representation of the byte value is in reverse
mapped to the coil addresses. In table below you can see some more
examples.
# quantity value binary representation | 102 101 100
== ======== ===== ===================== | === === ===
01 1 0 0b0 - - 0
02 1 1 0b1 - - 1
03 2 0 0b00 - 0 0
04 2 1 0b01 - 0 1
05 2 2 0b10 - 1 0
06 2 3 0b11 - 1 1
07 3 0 0b000 0 0 0
08 3 1 0b001 0 0 1
09 3 2 0b010 0 1 0
10 3 3 0b011 0 1 1
11 3 4 0b100 1 0 0
12 3 5 0b101 1 0 1
13 3 6 0b110 1 1 0
14 3 7 0b111 1 1 1
:param pdu: A request PDU.
"""
_, starting_address, quantity, byte_count = \
struct.unpack('>BHHB', pdu[:6])
fmt = '>' + (conf.SINGLE_BIT_VALUE_FORMAT_CHARACTER * byte_count)
values = struct.unpack(fmt, pdu[6:])
res = list()
for i, value in enumerate(values):
padding = 8 if (quantity - (8 * i)) // 8 > 0 else quantity % 8
fmt = '{{0:0{padding}b}}'.format(padding=padding)
# Create binary representation of integer, convert it to a list
# and reverse the list.
res = res + [int(i) for i in fmt.format(value)][::-1]
instance = cls()
instance.starting_address = starting_address
instance.quantity = quantity
instance.values = res
return instance
@property
def expected_response_pdu_size(self):
""" Return number of bytes expected for response PDU.
:return: number of bytes.
"""
return 5
def create_response_pdu(self):
""" Create response pdu.
:param data: A list with values.
:return: Byte array 5 bytes.
"""
return struct.pack('>BHH', self.function_code, self.starting_address,
len(self.values))
@classmethod
def create_from_response_pdu(cls, resp_pdu):
write_multiple_coils = cls()
starting_address, data = struct.unpack('>HH', resp_pdu[1:5])
write_multiple_coils.starting_address = starting_address
write_multiple_coils.data = data
return write_multiple_coils
def execute(self, slave_id, route_map):
""" Execute the Modbus function registered for a route.
:param slave_id: Slave id.
:param route_map: Instance of modbus.route.Map.
"""
for index, value in enumerate(self.values):
address = self.starting_address + index
endpoint = route_map.match(slave_id, self.function_code, address)
if endpoint is None:
raise IllegalDataAddressError()
endpoint(slave_id=slave_id, address=address, value=value,
function_code=self.function_code)
class WriteMultipleRegisters(ModbusFunction):
""" Implement Modbus function 16 (0x10) Write Multiple Registers.
"This function code is used to write a block of contiguous registers (1
to 123 registers) in a remote device.
The requested written values are specified in the request data field.
Data is packed as two bytes per register.
The normal response returns the function code, starting address, and
quantity of registers written."
-- MODBUS Application Protocol Specification V1.1b3, chapter 6.12
The request PDU with function code 16 must be at least 8 bytes:
================ ===============
Field Length (bytes)
================ ===============
Function code 1
Starting Address 2
Quantity 2
Byte count 1
Value Quantity * 2
================ ===============
The PDU can unpacked to this:
..
Note: the backslash in the bytes below are escaped using an extra back
slash. Without escaping the bytes aren't printed correctly in the HTML
output of this docs.
To work with the bytes in Python you need to remove the escape sequences.
`b'\\x01\\x00d` -> `b\x01\x00d`
.. code-block:: python
>>> struct.unpack('>BHHBH', b'\\x10\\x00d\\x00\\x01\\x02\\x00\\x05')
(16, 100, 1, 2, 5)
The reponse PDU is 5 bytes and contains following structure:
================ ===============
Field Length (bytes)
================ ===============
Function code 1
Starting address 2
Quantity 2
================ ===============
"""
function_code = WRITE_MULTIPLE_REGISTERS
starting_address = None
_values = None
_data = None
@property
def values(self):
return self._values
@values.setter
def values(self, values):
if not (1 <= len(values) <= 0x7B0):
raise IllegalDataValueError
for value in values:
try:
struct.pack(">" + conf.MULTI_BIT_VALUE_FORMAT_CHARACTER, value)
except struct.error:
raise IllegalDataValueError
self._values = values
self._values = values
@property
def request_pdu(self):
fmt = '>BHHB' + (conf.TYPE_CHAR * len(self.values))
return struct.pack(fmt, self.function_code, self.starting_address,
len(self.values), len(self.values) * 2,
*self.values)
@classmethod
def create_from_request_pdu(cls, pdu):
""" Create instance from request PDU.
:param pdu: A request PDU.
:return: Instance of this class.
"""
_, starting_address, quantity, byte_count = \
struct.unpack('>BHHB', pdu[:6])
# Values are 16 bit, so each value takes up 2 bytes.
fmt = '>' + (conf.MULTI_BIT_VALUE_FORMAT_CHARACTER *
int((byte_count / 2)))
values = list(struct.unpack(fmt, pdu[6:]))
instance = cls()
instance.starting_address = starting_address
instance.values = values
return instance
@property
def expected_response_pdu_size(self):
""" Return number of bytes expected for response PDU.
:return: number of bytes.
"""
return 5
def create_response_pdu(self):
""" Create response pdu.
:param data: A list with values.
:return: Byte array 5 bytes.
"""
return struct.pack('>BHH', self.function_code, self.starting_address,
len(self.values))
@classmethod
def create_from_response_pdu(cls, resp_pdu):
write_multiple_registers = cls()
starting_address, data = struct.unpack('>HH', resp_pdu[1:5])
write_multiple_registers.starting_address = starting_address
write_multiple_registers.data = data
return write_multiple_registers
def execute(self, slave_id, route_map):
""" Execute the Modbus function registered for a route.
:param slave_id: Slave id.
:param route_map: Instance of modbus.route.Map.
"""
for index, value in enumerate(self.values):
address = self.starting_address + index
endpoint = route_map.match(slave_id, self.function_code, address)
if endpoint is None:
raise IllegalDataAddressError()
endpoint(slave_id=slave_id, address=address, value=value,
function_code=self.function_code)
function_code_to_function_map = {
READ_COILS: ReadCoils,
READ_DISCRETE_INPUTS: ReadDiscreteInputs,
READ_HOLDING_REGISTERS: ReadHoldingRegisters,
READ_INPUT_REGISTERS: ReadInputRegisters,
WRITE_SINGLE_COIL: WriteSingleCoil,
WRITE_SINGLE_REGISTER: WriteSingleRegister,
WRITE_MULTIPLE_COILS: WriteMultipleCoils,
WRITE_MULTIPLE_REGISTERS: WriteMultipleRegisters,
}
|