增加高压空闲调节
This commit is contained in:
@@ -0,0 +1,4 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: UTF-8 -*-
|
||||
|
||||
from .version import __version__
|
||||
@@ -0,0 +1,392 @@
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# Copyright (c) 2019, Pycom Limited.
|
||||
#
|
||||
# This software is licensed under the GNU GPL version 3 or any
|
||||
# later version, with permitted additional terms. For more information
|
||||
# see the Pycom Licence v1.0 document supplied with this file, or
|
||||
# available at https://www.pycom.io/opensource/licensing
|
||||
#
|
||||
|
||||
# system packages
|
||||
import struct
|
||||
|
||||
# custom packages
|
||||
from . import const as Const
|
||||
from . import functions
|
||||
|
||||
# typing not natively supported on MicroPython
|
||||
from .typing import List, Optional, Tuple, Union
|
||||
|
||||
|
||||
class Request(object):
|
||||
"""Deconstruct request data received via TCP or Serial"""
|
||||
def __init__(self, interface, data: bytearray) -> None:
|
||||
self._itf = interface
|
||||
self.unit_addr = data[0]
|
||||
self.function, self.register_addr = struct.unpack_from('>BH', data, 1)
|
||||
|
||||
if self.function in [Const.READ_COILS, Const.READ_DISCRETE_INPUTS]:
|
||||
self.quantity = struct.unpack_from('>H', data, 4)[0]
|
||||
|
||||
if self.quantity < 0x0001 or self.quantity > 0x07D0:
|
||||
raise ModbusException(self.function, Const.ILLEGAL_DATA_VALUE)
|
||||
|
||||
self.data = None
|
||||
elif self.function in [Const.READ_HOLDING_REGISTERS, Const.READ_INPUT_REGISTER]:
|
||||
self.quantity = struct.unpack_from('>H', data, 4)[0]
|
||||
|
||||
if self.quantity < 0x0001 or self.quantity > 0x007D:
|
||||
raise ModbusException(self.function, Const.ILLEGAL_DATA_VALUE)
|
||||
|
||||
self.data = None
|
||||
elif self.function == Const.WRITE_SINGLE_COIL:
|
||||
self.quantity = None
|
||||
self.data = data[4:6]
|
||||
|
||||
# allowed values: 0x0000 or 0xFF00
|
||||
if (self.data[0] not in [0x00, 0xFF]) or self.data[1] != 0x00:
|
||||
raise ModbusException(self.function, Const.ILLEGAL_DATA_VALUE)
|
||||
elif self.function == Const.WRITE_SINGLE_REGISTER:
|
||||
self.quantity = None
|
||||
self.data = data[4:6]
|
||||
# all values allowed
|
||||
elif self.function == Const.WRITE_MULTIPLE_COILS:
|
||||
self.quantity = struct.unpack_from('>H', data, 4)[0]
|
||||
if self.quantity < 0x0001 or self.quantity > 0x07D0:
|
||||
raise ModbusException(self.function, Const.ILLEGAL_DATA_VALUE)
|
||||
self.data = data[7:]
|
||||
if len(self.data) != ((self.quantity - 1) // 8) + 1:
|
||||
raise ModbusException(self.function, Const.ILLEGAL_DATA_VALUE)
|
||||
elif self.function == Const.WRITE_MULTIPLE_REGISTERS:
|
||||
self.quantity = struct.unpack_from('>H', data, 4)[0]
|
||||
if self.quantity < 0x0001 or self.quantity > 0x007B:
|
||||
raise ModbusException(self.function, Const.ILLEGAL_DATA_VALUE)
|
||||
self.data = data[7:]
|
||||
if len(self.data) != self.quantity * 2:
|
||||
raise ModbusException(self.function, Const.ILLEGAL_DATA_VALUE)
|
||||
else:
|
||||
# Not implemented functions
|
||||
self.quantity = None
|
||||
self.data = data[4:]
|
||||
|
||||
def send_response(self,
|
||||
values: Optional[list] = None,
|
||||
signed: bool = True) -> None:
|
||||
"""
|
||||
Send a response via the configured interface.
|
||||
|
||||
:param values: The values
|
||||
:type values: Optional[list]
|
||||
:param signed: Indicates if signed values are used
|
||||
:type signed: bool
|
||||
"""
|
||||
self._itf.send_response(self.unit_addr,
|
||||
self.function,
|
||||
self.register_addr,
|
||||
self.quantity,
|
||||
self.data,
|
||||
values,
|
||||
signed)
|
||||
|
||||
def send_exception(self, exception_code: int) -> None:
|
||||
"""
|
||||
Send an exception response.
|
||||
|
||||
:param exception_code: The exception code
|
||||
:type exception_code: int
|
||||
"""
|
||||
self._itf.send_exception_response(self.unit_addr,
|
||||
self.function,
|
||||
exception_code)
|
||||
|
||||
|
||||
class ModbusException(Exception):
|
||||
"""Exception for signaling modbus errors"""
|
||||
def __init__(self, function_code: int, exception_code: int) -> None:
|
||||
self.function_code = function_code
|
||||
self.exception_code = exception_code
|
||||
|
||||
|
||||
class CommonModbusFunctions(object):
|
||||
"""Common Modbus functions"""
|
||||
def __init__(self):
|
||||
pass
|
||||
|
||||
def read_coils(self,
|
||||
slave_addr: int,
|
||||
starting_addr: int,
|
||||
coil_qty: int) -> List[bool]:
|
||||
"""
|
||||
Read coils (COILS).
|
||||
|
||||
:param slave_addr: The slave address
|
||||
:type slave_addr: int
|
||||
:param starting_addr: The coil starting address
|
||||
:type starting_addr: int
|
||||
:param coil_qty: The amount of coils to read
|
||||
:type coil_qty: int
|
||||
|
||||
:returns: State of read coils as list
|
||||
:rtype: List[bool]
|
||||
"""
|
||||
modbus_pdu = functions.read_coils(starting_address=starting_addr,
|
||||
quantity=coil_qty)
|
||||
|
||||
response = self._send_receive(slave_addr=slave_addr,
|
||||
modbus_pdu=modbus_pdu,
|
||||
count=True)
|
||||
|
||||
status_pdu = functions.bytes_to_bool(byte_list=response,
|
||||
bit_qty=coil_qty)
|
||||
|
||||
return status_pdu
|
||||
|
||||
def read_discrete_inputs(self,
|
||||
slave_addr: int,
|
||||
starting_addr: int,
|
||||
input_qty: int) -> List[bool]:
|
||||
"""
|
||||
Read discrete inputs (ISTS).
|
||||
|
||||
:param slave_addr: The slave address
|
||||
:type slave_addr: int
|
||||
:param starting_addr: The discrete input starting address
|
||||
:type starting_addr: int
|
||||
:param input_qty: The amount of discrete inputs to read
|
||||
:type input_qty: int
|
||||
|
||||
:returns: State of read discrete inputs as list
|
||||
:rtype: List[bool]
|
||||
"""
|
||||
modbus_pdu = functions.read_discrete_inputs(
|
||||
starting_address=starting_addr,
|
||||
quantity=input_qty)
|
||||
|
||||
response = self._send_receive(slave_addr=slave_addr,
|
||||
modbus_pdu=modbus_pdu,
|
||||
count=True)
|
||||
|
||||
status_pdu = functions.bytes_to_bool(byte_list=response,
|
||||
bit_qty=input_qty)
|
||||
|
||||
return status_pdu
|
||||
|
||||
def read_holding_registers(self,
|
||||
slave_addr: int,
|
||||
starting_addr: int,
|
||||
register_qty: int,
|
||||
signed: bool = True) -> Tuple[int, ...]:
|
||||
"""
|
||||
Read holding registers (HREGS).
|
||||
|
||||
:param slave_addr: The slave address
|
||||
:type slave_addr: int
|
||||
:param starting_addr: The holding register starting address
|
||||
:type starting_addr: int
|
||||
:param register_qty: The amount of holding registers to read
|
||||
:type register_qty: int
|
||||
:param signed: Indicates if signed
|
||||
:type signed: bool
|
||||
|
||||
:returns: State of read holding register as tuple
|
||||
:rtype: Tuple[int, ...]
|
||||
"""
|
||||
modbus_pdu = functions.read_holding_registers(
|
||||
starting_address=starting_addr,
|
||||
quantity=register_qty)
|
||||
|
||||
response = self._send_receive(slave_addr=slave_addr,
|
||||
modbus_pdu=modbus_pdu,
|
||||
count=True)
|
||||
|
||||
register_value = functions.to_short(byte_array=response, signed=signed)
|
||||
|
||||
return register_value
|
||||
|
||||
def read_input_registers(self,
|
||||
slave_addr: int,
|
||||
starting_addr: int,
|
||||
register_qty: int,
|
||||
signed: bool = True) -> Tuple[int, ...]:
|
||||
"""
|
||||
Read input registers (IREGS).
|
||||
|
||||
:param slave_addr: The slave address
|
||||
:type slave_addr: int
|
||||
:param starting_addr: The input register starting address
|
||||
:type starting_addr: int
|
||||
:param register_qty: The amount of input registers to read
|
||||
:type register_qty: int
|
||||
:param signed: Indicates if signed
|
||||
:type signed: bool
|
||||
|
||||
:returns: State of read input register as tuple
|
||||
:rtype: Tuple[int, ...]
|
||||
"""
|
||||
modbus_pdu = functions.read_input_registers(
|
||||
starting_address=starting_addr,
|
||||
quantity=register_qty)
|
||||
|
||||
response = self._send_receive(slave_addr=slave_addr,
|
||||
modbus_pdu=modbus_pdu,
|
||||
count=True)
|
||||
|
||||
register_value = functions.to_short(byte_array=response, signed=signed)
|
||||
|
||||
return register_value
|
||||
|
||||
def write_single_coil(self,
|
||||
slave_addr: int,
|
||||
output_address: int,
|
||||
output_value: Union[int, bool]) -> bool:
|
||||
"""
|
||||
Update a single coil.
|
||||
|
||||
:param slave_addr: The slave address
|
||||
:type slave_addr: int
|
||||
:param output_address: The output address
|
||||
:type output_address: int
|
||||
:param output_value: The output value
|
||||
:type output_value: Union[int, bool]
|
||||
|
||||
:returns: Result of operation
|
||||
:rtype: bool
|
||||
"""
|
||||
modbus_pdu = functions.write_single_coil(output_address=output_address,
|
||||
output_value=output_value)
|
||||
|
||||
response = self._send_receive(slave_addr=slave_addr,
|
||||
modbus_pdu=modbus_pdu,
|
||||
count=False)
|
||||
|
||||
if response is None:
|
||||
return False
|
||||
|
||||
operation_status = functions.validate_resp_data(
|
||||
data=response,
|
||||
function_code=Const.WRITE_SINGLE_COIL,
|
||||
address=output_address,
|
||||
value=output_value,
|
||||
signed=False)
|
||||
|
||||
return operation_status
|
||||
|
||||
def write_single_register(self,
|
||||
slave_addr: int,
|
||||
register_address: int,
|
||||
register_value: int,
|
||||
signed: bool = True) -> bool:
|
||||
"""
|
||||
Update a single register.
|
||||
|
||||
:param slave_addr: The slave address
|
||||
:type slave_addr: int
|
||||
:param register_address: The register address
|
||||
:type register_address: int
|
||||
:param register_value: The register value
|
||||
:type register_value: int
|
||||
:param signed: Indicates if signed
|
||||
:type signed: bool
|
||||
|
||||
:returns: Result of operation
|
||||
:rtype: bool
|
||||
"""
|
||||
modbus_pdu = functions.write_single_register(
|
||||
register_address=register_address,
|
||||
register_value=register_value,
|
||||
signed=signed)
|
||||
|
||||
response = self._send_receive(slave_addr=slave_addr,
|
||||
modbus_pdu=modbus_pdu,
|
||||
count=False)
|
||||
|
||||
if response is None:
|
||||
return False
|
||||
|
||||
operation_status = functions.validate_resp_data(
|
||||
data=response,
|
||||
function_code=Const.WRITE_SINGLE_REGISTER,
|
||||
address=register_address,
|
||||
value=register_value,
|
||||
signed=signed)
|
||||
|
||||
return operation_status
|
||||
|
||||
def write_multiple_coils(self,
|
||||
slave_addr: int,
|
||||
starting_address: int,
|
||||
output_values: List[Union[int, bool]]) -> bool:
|
||||
"""
|
||||
Update multiple coils.
|
||||
|
||||
:param slave_addr: The slave address
|
||||
:type slave_addr: int
|
||||
:param starting_address: The address of the first coil
|
||||
:type starting_address: int
|
||||
:param output_values: The output values
|
||||
:type output_values: List[Union[int, bool]]
|
||||
|
||||
:returns: Result of operation
|
||||
:rtype: bool
|
||||
"""
|
||||
modbus_pdu = functions.write_multiple_coils(
|
||||
starting_address=starting_address,
|
||||
value_list=output_values)
|
||||
|
||||
response = self._send_receive(slave_addr=slave_addr,
|
||||
modbus_pdu=modbus_pdu,
|
||||
count=False)
|
||||
|
||||
if response is None:
|
||||
return False
|
||||
|
||||
operation_status = functions.validate_resp_data(
|
||||
data=response,
|
||||
function_code=Const.WRITE_MULTIPLE_COILS,
|
||||
address=starting_address,
|
||||
quantity=len(output_values))
|
||||
|
||||
return operation_status
|
||||
|
||||
def write_multiple_registers(self,
|
||||
slave_addr: int,
|
||||
starting_address: int,
|
||||
register_values: List[int],
|
||||
signed: bool = True) -> bool:
|
||||
"""
|
||||
Update multiple registers.
|
||||
|
||||
:param slave_addr: The slave address
|
||||
:type slave_addr: int
|
||||
:param starting_address: The starting address
|
||||
:type starting_address: int
|
||||
:param register_values: The register values
|
||||
:type register_values: List[int]
|
||||
:param signed: Indicates if signed
|
||||
:type signed: bool
|
||||
|
||||
:returns: Result of operation
|
||||
:rtype: bool
|
||||
"""
|
||||
modbus_pdu = functions.write_multiple_registers(
|
||||
starting_address=starting_address,
|
||||
register_values=register_values,
|
||||
signed=signed)
|
||||
|
||||
response = self._send_receive(slave_addr=slave_addr,
|
||||
modbus_pdu=modbus_pdu,
|
||||
count=False)
|
||||
|
||||
if response is None:
|
||||
return False
|
||||
|
||||
operation_status = functions.validate_resp_data(
|
||||
data=response,
|
||||
function_code=Const.WRITE_MULTIPLE_REGISTERS,
|
||||
address=starting_address,
|
||||
quantity=len(register_values),
|
||||
signed=signed
|
||||
)
|
||||
|
||||
return operation_status
|
||||
@@ -0,0 +1,153 @@
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# Copyright (c) 2019, Pycom Limited.
|
||||
#
|
||||
# This software is licensed under the GNU GPL version 3 or any
|
||||
# later version, with permitted additional terms. For more information
|
||||
# see the Pycom Licence v1.0 document supplied with this file, or
|
||||
# available at https://www.pycom.io/opensource/licensing
|
||||
#
|
||||
# Description summary taken from
|
||||
# https://modbus.org/docs/Modbus_Application_Protocol_V1_1b3.pdf
|
||||
|
||||
from micropython import const
|
||||
|
||||
# function codes
|
||||
# defined as const(), see https://github.com/micropython/micropython/issues/573
|
||||
#: Read contiguous status of coils
|
||||
READ_COILS = const(0x01) # COILS, [0, 1]
|
||||
#: Read contiguous status of discrete inputs
|
||||
READ_DISCRETE_INPUTS = const(0x02) # ISTS, [0, 1]
|
||||
#: Read the contents of a contiguous block of holding registers
|
||||
READ_HOLDING_REGISTERS = const(0x03) # HREGS, [0, 65535]
|
||||
#: Read contiguous input registers
|
||||
READ_INPUT_REGISTER = const(0x04) # IREGS, [0, 65535]
|
||||
|
||||
#: Write a single coil output status to ON or OFF
|
||||
WRITE_SINGLE_COIL = const(0x05) # COILS, [0, 1]
|
||||
#: Write a single holding register
|
||||
WRITE_SINGLE_REGISTER = const(0x06) # HREGS, [0, 65535]
|
||||
#: Force each coil in a sequence of coils to either ON or OFF
|
||||
WRITE_MULTIPLE_COILS = const(0x0F) # COILS, [0, 1]
|
||||
#: Write a block of contiguous registers
|
||||
WRITE_MULTIPLE_REGISTERS = const(0x10) # HREGS, [0, 65535]
|
||||
|
||||
"""
|
||||
Modify the contents of a specified holding register using a combination of an
|
||||
AND mask, an OR mask, and the register's current contents
|
||||
"""
|
||||
MASK_WRITE_REGISTER = const(0x16)
|
||||
"""
|
||||
Perform a combination of one read operation and one write operation in a
|
||||
single MODBUS transaction
|
||||
"""
|
||||
READ_WRITE_MULTIPLE_REGISTERS = const(0x17)
|
||||
|
||||
#: Read the contents of a First-In-First-Out (FIFO) queue of register
|
||||
READ_FIFO_QUEUE = const(0x18)
|
||||
|
||||
#: Perform a file record read
|
||||
READ_FILE_RECORD = const(0x14)
|
||||
#: Perform a file record write
|
||||
WRITE_FILE_RECORD = const(0x15)
|
||||
|
||||
#: Read the contents of eight Exception Status outputs
|
||||
READ_EXCEPTION_STATUS = const(0x07)
|
||||
#: Provide series of tests for checking the communication system (serial only)
|
||||
DIAGNOSTICS = const(0x08)
|
||||
#: Get status word and an event count from the remote device com event counter
|
||||
GET_COM_EVENT_COUNTER = const(0x0B)
|
||||
#: Get a status word, event count, message count, and a field of event bytes
|
||||
GET_COM_EVENT_LOG = const(0x0C)
|
||||
#: Read the description of the type, the current status, and other informations
|
||||
REPORT_SERVER_ID = const(0x11)
|
||||
#: Encapsulated Interface Transport
|
||||
READ_DEVICE_IDENTIFICATION = const(0x2B)
|
||||
|
||||
# exception codes
|
||||
#: Function code received in query is not an allowable action for the server
|
||||
ILLEGAL_FUNCTION = const(0x01)
|
||||
#: Data address received in query is not an allowable address for the server
|
||||
ILLEGAL_DATA_ADDRESS = const(0x02)
|
||||
#: A value contained in the query is not an allowable value for the server
|
||||
ILLEGAL_DATA_VALUE = const(0x03)
|
||||
"""
|
||||
An unrecoverable error occurred while the server was attempting to perform the
|
||||
requested action
|
||||
"""
|
||||
SERVER_DEVICE_FAILURE = const(0x04)
|
||||
#: Response is returned to prevent a timeout error from occurring in the client
|
||||
ACKNOWLEDGE = const(0x05)
|
||||
#: Server is engaged in processing a long duration program command
|
||||
SERVER_DEVICE_BUSY = const(0x06)
|
||||
#: Server attempted to read record file, but detected a parity error in memory
|
||||
MEMORY_PARITY_ERROR = const(0x08)
|
||||
"""
|
||||
Gateway was unable to allocate an internal communication path from the input
|
||||
port to the output port for processing the request
|
||||
"""
|
||||
GATEWAY_PATH_UNAVAILABLE = const(0x0A)
|
||||
#: No response was obtained from the target device
|
||||
DEVICE_FAILED_TO_RESPOND = const(0x0B)
|
||||
|
||||
# Protocol Data Unit (PDU) constants
|
||||
#: CRC length
|
||||
CRC_LENGTH = const(0x02)
|
||||
#: Error code offset
|
||||
ERROR_BIAS = const(0x80)
|
||||
#: High Data Response length
|
||||
RESPONSE_HDR_LENGTH = const(0x02)
|
||||
#: Error response length
|
||||
ERROR_RESP_LEN = const(0x05)
|
||||
#: Fixed response length
|
||||
FIXED_RESP_LEN = const(0x08)
|
||||
#: Modbus Application Protocol High Data Response length
|
||||
MBAP_HDR_LENGTH = const(0x07)
|
||||
|
||||
#: CRC16 lookup table
|
||||
CRC16_TABLE = (
|
||||
0x0000, 0xC0C1, 0xC181, 0x0140, 0xC301, 0x03C0, 0x0280, 0xC241, 0xC601,
|
||||
0x06C0, 0x0780, 0xC741, 0x0500, 0xC5C1, 0xC481, 0x0440, 0xCC01, 0x0CC0,
|
||||
0x0D80, 0xCD41, 0x0F00, 0xCFC1, 0xCE81, 0x0E40, 0x0A00, 0xCAC1, 0xCB81,
|
||||
0x0B40, 0xC901, 0x09C0, 0x0880, 0xC841, 0xD801, 0x18C0, 0x1980, 0xD941,
|
||||
0x1B00, 0xDBC1, 0xDA81, 0x1A40, 0x1E00, 0xDEC1, 0xDF81, 0x1F40, 0xDD01,
|
||||
0x1DC0, 0x1C80, 0xDC41, 0x1400, 0xD4C1, 0xD581, 0x1540, 0xD701, 0x17C0,
|
||||
0x1680, 0xD641, 0xD201, 0x12C0, 0x1380, 0xD341, 0x1100, 0xD1C1, 0xD081,
|
||||
0x1040, 0xF001, 0x30C0, 0x3180, 0xF141, 0x3300, 0xF3C1, 0xF281, 0x3240,
|
||||
0x3600, 0xF6C1, 0xF781, 0x3740, 0xF501, 0x35C0, 0x3480, 0xF441, 0x3C00,
|
||||
0xFCC1, 0xFD81, 0x3D40, 0xFF01, 0x3FC0, 0x3E80, 0xFE41, 0xFA01, 0x3AC0,
|
||||
0x3B80, 0xFB41, 0x3900, 0xF9C1, 0xF881, 0x3840, 0x2800, 0xE8C1, 0xE981,
|
||||
0x2940, 0xEB01, 0x2BC0, 0x2A80, 0xEA41, 0xEE01, 0x2EC0, 0x2F80, 0xEF41,
|
||||
0x2D00, 0xEDC1, 0xEC81, 0x2C40, 0xE401, 0x24C0, 0x2580, 0xE541, 0x2700,
|
||||
0xE7C1, 0xE681, 0x2640, 0x2200, 0xE2C1, 0xE381, 0x2340, 0xE101, 0x21C0,
|
||||
0x2080, 0xE041, 0xA001, 0x60C0, 0x6180, 0xA141, 0x6300, 0xA3C1, 0xA281,
|
||||
0x6240, 0x6600, 0xA6C1, 0xA781, 0x6740, 0xA501, 0x65C0, 0x6480, 0xA441,
|
||||
0x6C00, 0xACC1, 0xAD81, 0x6D40, 0xAF01, 0x6FC0, 0x6E80, 0xAE41, 0xAA01,
|
||||
0x6AC0, 0x6B80, 0xAB41, 0x6900, 0xA9C1, 0xA881, 0x6840, 0x7800, 0xB8C1,
|
||||
0xB981, 0x7940, 0xBB01, 0x7BC0, 0x7A80, 0xBA41, 0xBE01, 0x7EC0, 0x7F80,
|
||||
0xBF41, 0x7D00, 0xBDC1, 0xBC81, 0x7C40, 0xB401, 0x74C0, 0x7580, 0xB541,
|
||||
0x7700, 0xB7C1, 0xB681, 0x7640, 0x7200, 0xB2C1, 0xB381, 0x7340, 0xB101,
|
||||
0x71C0, 0x7080, 0xB041, 0x5000, 0x90C1, 0x9181, 0x5140, 0x9301, 0x53C0,
|
||||
0x5280, 0x9241, 0x9601, 0x56C0, 0x5780, 0x9741, 0x5500, 0x95C1, 0x9481,
|
||||
0x5440, 0x9C01, 0x5CC0, 0x5D80, 0x9D41, 0x5F00, 0x9FC1, 0x9E81, 0x5E40,
|
||||
0x5A00, 0x9AC1, 0x9B81, 0x5B40, 0x9901, 0x59C0, 0x5880, 0x9841, 0x8801,
|
||||
0x48C0, 0x4980, 0x8941, 0x4B00, 0x8BC1, 0x8A81, 0x4A40, 0x4E00, 0x8EC1,
|
||||
0x8F81, 0x4F40, 0x8D01, 0x4DC0, 0x4C80, 0x8C41, 0x4400, 0x84C1, 0x8581,
|
||||
0x4540, 0x8701, 0x47C0, 0x4680, 0x8641, 0x8201, 0x42C0, 0x4380, 0x8341,
|
||||
0x4100, 0x81C1, 0x8081, 0x4040
|
||||
)
|
||||
|
||||
|
||||
# Code to generate the CRC-16 lookup table:
|
||||
# def generate_crc16_table():
|
||||
# crc_table = []
|
||||
# for byte in range(256):
|
||||
# crc = 0x0000
|
||||
# for _ in range(8):
|
||||
# if (byte ^ crc) & 0x0001:
|
||||
# crc = (crc >> 1) ^ 0xa001
|
||||
# else:
|
||||
# crc >>= 1
|
||||
# byte >>= 1
|
||||
# crc_table.append(crc)
|
||||
# return crc_table
|
||||
@@ -0,0 +1,459 @@
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# Copyright (c) 2019, Pycom Limited.
|
||||
#
|
||||
# This software is licensed under the GNU GPL version 3 or any
|
||||
# later version, with permitted additional terms. For more information
|
||||
# see the Pycom Licence v1.0 document supplied with this file, or
|
||||
# available at https://www.pycom.io/opensource/licensing
|
||||
#
|
||||
|
||||
# system packages
|
||||
import struct
|
||||
|
||||
# custom packages
|
||||
from . import const as Const
|
||||
|
||||
# typing not natively supported on MicroPython
|
||||
from .typing import List, Optional, Union
|
||||
|
||||
|
||||
def read_coils(starting_address: int, quantity: int) -> bytes:
|
||||
"""
|
||||
Create Modbus Protocol Data Unit for reading coils.
|
||||
|
||||
:param starting_address: The starting address
|
||||
:type starting_address: int
|
||||
:param quantity: Quantity of coils
|
||||
:type quantity: int
|
||||
|
||||
:returns: Packed Modbus message
|
||||
:rtype: bytes
|
||||
"""
|
||||
if not (1 <= quantity <= 2000):
|
||||
raise ValueError('Invalid number of coils')
|
||||
|
||||
return struct.pack('>BHH', Const.READ_COILS, starting_address, quantity)
|
||||
|
||||
|
||||
def read_discrete_inputs(starting_address: int, quantity: int) -> bytes:
|
||||
"""
|
||||
Create Modbus Protocol Data Unit for reading discrete inputs.
|
||||
|
||||
:param starting_address: The starting address
|
||||
:type starting_address: int
|
||||
:param quantity: Quantity of coils
|
||||
:type quantity: int
|
||||
|
||||
:returns: Packed Modbus message
|
||||
:rtype: bytes
|
||||
"""
|
||||
if not (1 <= quantity <= 2000):
|
||||
raise ValueError('Invalid number of discrete inputs')
|
||||
|
||||
return struct.pack('>BHH',
|
||||
Const.READ_DISCRETE_INPUTS,
|
||||
starting_address,
|
||||
quantity)
|
||||
|
||||
|
||||
def read_holding_registers(starting_address: int, quantity: int) -> bytes:
|
||||
"""
|
||||
Create Modbus Protocol Data Unit for reading holding registers.
|
||||
|
||||
:param starting_address: The starting address
|
||||
:type starting_address: int
|
||||
:param quantity: Quantity of coils
|
||||
:type quantity: int
|
||||
|
||||
:returns: Packed Modbus message
|
||||
:rtype: bytes
|
||||
"""
|
||||
if not (1 <= quantity <= 125):
|
||||
raise ValueError('Invalid number of holding registers')
|
||||
|
||||
return struct.pack('>BHH',
|
||||
Const.READ_HOLDING_REGISTERS,
|
||||
starting_address,
|
||||
quantity)
|
||||
|
||||
|
||||
def read_input_registers(starting_address: int, quantity: int) -> bytes:
|
||||
"""
|
||||
Create Modbus Protocol Data Unit for reading input registers.
|
||||
|
||||
:param starting_address: The starting address
|
||||
:type starting_address: int
|
||||
:param quantity: Quantity of coils
|
||||
:type quantity: int
|
||||
|
||||
:returns: Packed Modbus message
|
||||
:rtype: bytes
|
||||
"""
|
||||
if not (1 <= quantity <= 125):
|
||||
raise ValueError('Invalid number of input registers')
|
||||
|
||||
return struct.pack('>BHH',
|
||||
Const.READ_INPUT_REGISTER,
|
||||
starting_address,
|
||||
quantity)
|
||||
|
||||
|
||||
def write_single_coil(output_address: int,
|
||||
output_value: Union[int, bool]) -> bytes:
|
||||
"""
|
||||
Create Modbus message to update single coil
|
||||
|
||||
:param output_address: The output address
|
||||
:type output_address: int
|
||||
:param output_value: The output value
|
||||
:type output_value: Union[int, bool]
|
||||
|
||||
:returns: Packed Modbus message
|
||||
:rtype: bytes
|
||||
"""
|
||||
if output_value not in [0x0000, 0xFF00, False, True, 0, 1]:
|
||||
raise ValueError('Illegal coil value')
|
||||
|
||||
if output_value not in [0x0000, 0xFF00]:
|
||||
if output_value:
|
||||
output_value = 0xFF00
|
||||
else:
|
||||
output_value = 0x0000
|
||||
|
||||
return struct.pack('>BHH',
|
||||
Const.WRITE_SINGLE_COIL,
|
||||
output_address,
|
||||
output_value)
|
||||
|
||||
|
||||
def write_single_register(register_address: int,
|
||||
register_value: int,
|
||||
signed: bool = True) -> bytes:
|
||||
"""
|
||||
Create Modbus message to writes a single register
|
||||
|
||||
:param register_address: The register address
|
||||
:type register_address: int
|
||||
:param register_value: The register value
|
||||
:type register_value: int
|
||||
:param signed: Flag whether data is signed or not
|
||||
:type signed: bool
|
||||
|
||||
:returns: Packed Modbus message
|
||||
:rtype: bytes
|
||||
"""
|
||||
fmt = 'h' if signed else 'H'
|
||||
|
||||
return struct.pack('>BH' + fmt,
|
||||
Const.WRITE_SINGLE_REGISTER,
|
||||
register_address,
|
||||
register_value)
|
||||
|
||||
|
||||
def write_multiple_coils(starting_address: int,
|
||||
value_list: List[Union[int, bool]]) -> bytes:
|
||||
"""
|
||||
Create Modbus message to update multiple coils
|
||||
|
||||
:param starting_address: The starting address
|
||||
:type starting_address: int
|
||||
:param value_list: The list of output values
|
||||
:type value_list: List[Union[int, bool]]
|
||||
|
||||
:returns: Packed Modbus message
|
||||
:rtype: bytes
|
||||
"""
|
||||
if not (1 <= len(value_list) <= 0x07B0):
|
||||
raise ValueError('Invalid quantity of outputs')
|
||||
|
||||
sectioned_list = [value_list[i:i + 8] for i in range(0, len(value_list), 8)] # noqa: E501
|
||||
|
||||
output_value = []
|
||||
for index, byte in enumerate(sectioned_list):
|
||||
# see https://github.com/brainelectronics/micropython-modbus/issues/22
|
||||
# output = sum(v << i for i, v in enumerate(byte))
|
||||
output = 0
|
||||
for bit in byte:
|
||||
output = (output << 1) | bit
|
||||
output_value.append(output)
|
||||
|
||||
fmt = 'B' * len(output_value)
|
||||
quantity = len(value_list)
|
||||
byte_count = quantity // 8
|
||||
if quantity % 8:
|
||||
byte_count += 1
|
||||
|
||||
return struct.pack('>BHHB' + fmt,
|
||||
Const.WRITE_MULTIPLE_COILS,
|
||||
starting_address,
|
||||
quantity,
|
||||
byte_count,
|
||||
*output_value)
|
||||
|
||||
|
||||
def write_multiple_registers(starting_address: int,
|
||||
register_values: List[int],
|
||||
signed: bool = True) -> bytes:
|
||||
"""
|
||||
Create Modbus message to update multiple coils
|
||||
|
||||
:param starting_address: The starting address
|
||||
:type starting_address: int
|
||||
:param register_values: The list of output value
|
||||
:type register_values: List[int, bool]
|
||||
:param signed: Flag whether data is signed or not
|
||||
:type signed: bool
|
||||
|
||||
:returns: Packed Modbus message
|
||||
:rtype: bytes
|
||||
"""
|
||||
if not (1 <= len(register_values) <= 123):
|
||||
raise ValueError('Invalid number of registers')
|
||||
|
||||
quantity = len(register_values)
|
||||
byte_count = quantity * 2
|
||||
fmt = ('h' if signed else 'H') * quantity
|
||||
|
||||
return struct.pack('>BHHB' + fmt,
|
||||
Const.WRITE_MULTIPLE_REGISTERS,
|
||||
starting_address,
|
||||
quantity,
|
||||
byte_count,
|
||||
*register_values)
|
||||
|
||||
|
||||
def validate_resp_data(data: bytes,
|
||||
function_code: int,
|
||||
address: int,
|
||||
value: int = None,
|
||||
quantity: int = None,
|
||||
signed: bool = True) -> bool:
|
||||
"""
|
||||
Validate the response data.
|
||||
|
||||
:param data: The data
|
||||
:type data: bytes
|
||||
:param function_code: The function code
|
||||
:type function_code: int
|
||||
:param address: The address
|
||||
:type address: int
|
||||
:param value: The value
|
||||
:type value: int
|
||||
:param quantity: The quantity
|
||||
:type quantity: int
|
||||
:param signed: Indicates if signed
|
||||
:type signed: bool
|
||||
|
||||
:returns: True if valid, False otherwise
|
||||
:rtype: bool
|
||||
"""
|
||||
fmt = '>H' + ('h' if signed else 'H')
|
||||
|
||||
if function_code in [Const.WRITE_SINGLE_COIL, Const.WRITE_SINGLE_REGISTER]:
|
||||
resp_addr, resp_value = struct.unpack(fmt, data)
|
||||
|
||||
# if bool(True) or int(1) is used as "output_value" of
|
||||
# "write_single_coil" it will be internally converted to int(0xFF00),
|
||||
# see Modbus specification, which is actually int(65280).
|
||||
# Due to the non binary, but real value comparison of "value" and
|
||||
# "resp_value", it would never match without the next two lines
|
||||
# see #21
|
||||
if function_code == Const.WRITE_SINGLE_COIL:
|
||||
resp_value = bool(resp_value)
|
||||
value = bool(value)
|
||||
|
||||
if (address == resp_addr) and (value == resp_value):
|
||||
return True
|
||||
elif function_code in [Const.WRITE_MULTIPLE_COILS,
|
||||
Const.WRITE_MULTIPLE_REGISTERS]:
|
||||
resp_addr, resp_qty = struct.unpack(fmt, data)
|
||||
|
||||
if (address == resp_addr) and (quantity == resp_qty):
|
||||
return True
|
||||
|
||||
return False
|
||||
|
||||
|
||||
def response(function_code: int,
|
||||
request_register_addr: int,
|
||||
request_register_qty: int,
|
||||
request_data: list,
|
||||
value_list: Optional[list] = None,
|
||||
signed: bool = True) -> bytes:
|
||||
"""
|
||||
Construct a Modbus response Protocol Data Unit
|
||||
|
||||
:param function_code: The function code
|
||||
:type function_code: int
|
||||
:param request_register_addr: The request register address
|
||||
:type request_register_addr: int
|
||||
:param request_register_qty: The request register qty
|
||||
:type request_register_qty: int
|
||||
:param request_data: The request data
|
||||
:type request_data: list
|
||||
:param value_list: The values
|
||||
:type value_list: Optional[list]
|
||||
:param signed: Indicates if signed
|
||||
:type signed: bool
|
||||
|
||||
:returns: Protocol data unit
|
||||
:rtype: bytes
|
||||
"""
|
||||
if function_code in [Const.READ_COILS, Const.READ_DISCRETE_INPUTS]:
|
||||
sectioned_list = [value_list[i:i + 8] for i in range(0, len(value_list), 8)] # noqa: E501
|
||||
|
||||
output_value = []
|
||||
for index, byte in enumerate(sectioned_list):
|
||||
output = 0
|
||||
for i, bit in enumerate(byte):
|
||||
output |= bit << i
|
||||
output_value.append(output)
|
||||
|
||||
fmt = 'B' * len(output_value)
|
||||
return struct.pack('>BB' + fmt,
|
||||
function_code,
|
||||
((len(value_list) - 1) // 8) + 1,
|
||||
*output_value)
|
||||
|
||||
elif function_code in [Const.READ_HOLDING_REGISTERS,
|
||||
Const.READ_INPUT_REGISTER]:
|
||||
quantity = len(value_list)
|
||||
|
||||
if not (0x0001 <= quantity <= 0x007D):
|
||||
raise ValueError('invalid number of registers')
|
||||
|
||||
if signed is True or signed is False:
|
||||
fmt = ('h' if signed else 'H') * quantity
|
||||
else:
|
||||
fmt = ''
|
||||
for s in signed:
|
||||
fmt += 'h' if s else 'H'
|
||||
|
||||
return struct.pack('>BB' + fmt,
|
||||
function_code,
|
||||
quantity * 2,
|
||||
*value_list)
|
||||
|
||||
elif function_code in [Const.WRITE_SINGLE_COIL,
|
||||
Const.WRITE_SINGLE_REGISTER]:
|
||||
return struct.pack('>BHBB',
|
||||
function_code,
|
||||
request_register_addr,
|
||||
*request_data)
|
||||
|
||||
elif function_code in [Const.WRITE_MULTIPLE_COILS,
|
||||
Const.WRITE_MULTIPLE_REGISTERS]:
|
||||
return struct.pack('>BHH',
|
||||
function_code,
|
||||
request_register_addr,
|
||||
request_register_qty)
|
||||
|
||||
|
||||
def exception_response(function_code: int, exception_code: int) -> bytes:
|
||||
"""
|
||||
Create Modbus exception response
|
||||
|
||||
:param function_code: The function code
|
||||
:type function_code: int
|
||||
:param exception_code: The exception code
|
||||
:type exception_code: int
|
||||
|
||||
:returns: Packed Modbus message
|
||||
:rtype: bytes
|
||||
"""
|
||||
return struct.pack('>BB', Const.ERROR_BIAS + function_code, exception_code)
|
||||
|
||||
|
||||
def bytes_to_bool(byte_list: bytes, bit_qty: Optional[int] = 1) -> List[bool]:
|
||||
"""
|
||||
Convert bytes to list of boolean values
|
||||
|
||||
:param byte_list: The byte list
|
||||
:type byte_list: bytes
|
||||
:param bit_qty: Amount of bits received
|
||||
:type bit_qty: Optional[int]
|
||||
|
||||
:returns: Boolean representation
|
||||
:rtype: List[bool]
|
||||
"""
|
||||
bool_list = []
|
||||
|
||||
for index, byte in enumerate(byte_list):
|
||||
this_qty = bit_qty
|
||||
|
||||
if this_qty >= 8:
|
||||
this_qty = 8
|
||||
|
||||
# evil hack for missing keyword support in MicroPython format()
|
||||
fmt = '{:0' + str(this_qty) + 'b}'
|
||||
binary_str = fmt.format(byte)
|
||||
bool_list.extend([bool(int(binary_str[i])) for i in range(len(binary_str)-1, -1, -1)])
|
||||
|
||||
bit_qty -= 8
|
||||
|
||||
return bool_list
|
||||
|
||||
|
||||
def to_short(byte_array: bytes, signed: bool = True) -> bytes:
|
||||
"""
|
||||
Convert bytes to tuple of integer values
|
||||
|
||||
:param byte_array: The byte array
|
||||
:type byte_array: bytes
|
||||
:param signed: Indicates if signed
|
||||
:type signed: bool
|
||||
|
||||
:returns: Integer representation
|
||||
:rtype: bytes
|
||||
"""
|
||||
response_quantity = int(len(byte_array) / 2)
|
||||
fmt = '>' + (('h' if signed else 'H') * response_quantity)
|
||||
|
||||
return struct.unpack(fmt, byte_array)
|
||||
|
||||
|
||||
def float_to_bin(num: float) -> bin:
|
||||
"""
|
||||
Convert floating point value to binary
|
||||
|
||||
See IEEE 754
|
||||
|
||||
:param num: The number
|
||||
:type num: float
|
||||
|
||||
:returns: Binary representation
|
||||
:rtype: bin
|
||||
"""
|
||||
# no "zfill" available in MicroPython
|
||||
# return bin(struct.unpack('!I', struct.pack('!f', num))[0])[2:].zfill(32)
|
||||
|
||||
return '{:0>{w}}'.format(
|
||||
bin(struct.unpack('!I', struct.pack('!f', num))[0])[2:],
|
||||
w=32)
|
||||
|
||||
|
||||
def bin_to_float(binary: str) -> float:
|
||||
"""
|
||||
Convert binary string to floating point value
|
||||
|
||||
:param binary: The binary string
|
||||
:type binary: str
|
||||
|
||||
:returns: Converted floating point value
|
||||
:rtype: float
|
||||
"""
|
||||
return struct.unpack('!f', struct.pack('!I', int(binary, 2)))[0]
|
||||
|
||||
|
||||
def int_to_bin(num: int) -> str:
|
||||
"""
|
||||
Convert integer to binary
|
||||
|
||||
:param num: The number
|
||||
:type num: int
|
||||
|
||||
:returns: Binary representation of given input
|
||||
:rtype: str
|
||||
"""
|
||||
return "{0:b}".format(num)
|
||||
@@ -0,0 +1,873 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: UTF-8 -*-
|
||||
|
||||
"""
|
||||
Modbus register abstraction class
|
||||
|
||||
Used to add, remove, set and get values or states of a register or coil.
|
||||
Additional helper properties and functions like getters for changed registers
|
||||
are available as well.
|
||||
|
||||
This class is inherited by the Modbus client implementations
|
||||
:py:class:`umodbus.serial.ModbusRTU` and :py:class:`umodbus.tcp.ModbusTCP`
|
||||
"""
|
||||
|
||||
# system packages
|
||||
import time
|
||||
|
||||
# custom packages
|
||||
from . import functions
|
||||
from . import const as Const
|
||||
from .common import Request
|
||||
|
||||
# typing not natively supported on MicroPython
|
||||
from .typing import Callable, dict_keys, List, Optional, Union
|
||||
|
||||
|
||||
class Modbus(object):
|
||||
"""
|
||||
Modbus register abstraction
|
||||
|
||||
:param itf: Abstraction interface
|
||||
:type itf: Callable
|
||||
:param addr_list: List of addresses
|
||||
:type addr_list: List[int]
|
||||
"""
|
||||
def __init__(self, itf, addr_list: List[int]) -> None:
|
||||
self._itf = itf
|
||||
self._addr_list = addr_list
|
||||
|
||||
# modbus register types with their default value
|
||||
self._available_register_types = ['COILS', 'HREGS', 'IREGS', 'ISTS']
|
||||
self._register_dict = dict()
|
||||
for reg_type in self._available_register_types:
|
||||
self._register_dict[reg_type] = dict()
|
||||
self._default_vals = dict(zip(self._available_register_types,
|
||||
[False, 0, 0, False]))
|
||||
|
||||
# registers which can be set by remote device
|
||||
self._changeable_register_types = ['COILS', 'HREGS']
|
||||
self._changed_registers = dict()
|
||||
for reg_type in self._changeable_register_types:
|
||||
self._changed_registers[reg_type] = dict()
|
||||
|
||||
def process(self) -> bool:
|
||||
"""
|
||||
Process the Modbus requests.
|
||||
|
||||
:returns: Result of processing, True on success, False otherwise
|
||||
:rtype: bool
|
||||
"""
|
||||
reg_type = None
|
||||
req_type = None
|
||||
|
||||
request = self._itf.get_request(unit_addr_list=self._addr_list,
|
||||
timeout=0)
|
||||
if request is None:
|
||||
return False
|
||||
|
||||
if request.function == Const.READ_COILS:
|
||||
# Coils (setter+getter) [0, 1]
|
||||
# function 01 - read single register
|
||||
reg_type = 'COILS'
|
||||
req_type = 'READ'
|
||||
elif request.function == Const.READ_DISCRETE_INPUTS:
|
||||
# Ists (only getter) [0, 1]
|
||||
# function 02 - read input status (discrete inputs/digital input)
|
||||
reg_type = 'ISTS'
|
||||
req_type = 'READ'
|
||||
elif request.function == Const.READ_HOLDING_REGISTERS:
|
||||
# Hregs (setter+getter) [0, 65535]
|
||||
# function 03 - read holding register
|
||||
reg_type = 'HREGS'
|
||||
req_type = 'READ'
|
||||
elif request.function == Const.READ_INPUT_REGISTER:
|
||||
# Iregs (only getter) [0, 65535]
|
||||
# function 04 - read input registers
|
||||
reg_type = 'IREGS'
|
||||
req_type = 'READ'
|
||||
elif (request.function == Const.WRITE_SINGLE_COIL or
|
||||
request.function == Const.WRITE_MULTIPLE_COILS):
|
||||
# Coils (setter+getter) [0, 1]
|
||||
# function 05 - write single coil
|
||||
# function 15 - write multiple coil
|
||||
reg_type = 'COILS'
|
||||
req_type = 'WRITE'
|
||||
elif (request.function == Const.WRITE_SINGLE_REGISTER or
|
||||
request.function == Const.WRITE_MULTIPLE_REGISTERS):
|
||||
# Hregs (setter+getter) [0, 65535]
|
||||
# function 06 - write holding register
|
||||
# function 16 - write multiple holding register
|
||||
reg_type = 'HREGS'
|
||||
req_type = 'WRITE'
|
||||
else:
|
||||
request.send_exception(Const.ILLEGAL_FUNCTION)
|
||||
|
||||
if reg_type:
|
||||
if req_type == 'READ':
|
||||
self._process_read_access(request=request, reg_type=reg_type)
|
||||
elif req_type == 'WRITE':
|
||||
self._process_write_access(request=request, reg_type=reg_type)
|
||||
|
||||
return True
|
||||
|
||||
def _create_response(self,
|
||||
request: Request,
|
||||
reg_type: str) -> Union[List[bool], List[int]]:
|
||||
"""
|
||||
Create a response.
|
||||
|
||||
:param request: The request
|
||||
:type request: Request
|
||||
:param reg_type: The register type
|
||||
:type reg_type: str
|
||||
|
||||
:returns: Values of this register
|
||||
:rtype: Union[List[bool], List[int]]
|
||||
"""
|
||||
data = []
|
||||
default_value = {'val': 0}
|
||||
reg_dict = self._register_dict[reg_type]
|
||||
|
||||
if reg_type in ['COILS', 'ISTS']:
|
||||
default_value = {'val': False}
|
||||
|
||||
for addr in range(request.register_addr,
|
||||
request.register_addr + request.quantity):
|
||||
value = reg_dict.get(addr, default_value)['val']
|
||||
|
||||
if isinstance(value, (list, tuple)):
|
||||
data.extend(value)
|
||||
else:
|
||||
data.append(value)
|
||||
|
||||
# caution LSB vs MSB
|
||||
# [
|
||||
# 1, 0, 1, 1, 0, 0, 1, 1, # 0xB3
|
||||
# 1, 1, 0, 1, 0, 1, 1, 0, # 0xD6
|
||||
# 1, 0, 1 # 0x5
|
||||
# ]
|
||||
# but should be, documented at #38, see
|
||||
# https://github.com/brainelectronics/micropython-modbus/issues/38
|
||||
# this is only an issue of data provisioning as client/slave,
|
||||
# it has thereby NOT to be fixed in
|
||||
# :py:function:`umodbus.functions.bytes_to_bool`
|
||||
# [
|
||||
# 1, 1, 0, 0, 1, 1, 0, 1, # 0xCD
|
||||
# 0, 1, 1, 0, 1, 0, 1, 1, # 0x6B
|
||||
# 1, 0, 1 # 0x5
|
||||
# ]
|
||||
# 27 .... 20
|
||||
# CD 1100 1101
|
||||
#
|
||||
# 35 .... 28
|
||||
# 6B 0110 1011
|
||||
#
|
||||
# 43 .... 36
|
||||
# 05 0000 0101
|
||||
#
|
||||
# 1011 0011 1101 0110 1010 0000
|
||||
|
||||
return data
|
||||
|
||||
def _process_read_access(self, request: Request, reg_type: str) -> None:
|
||||
"""
|
||||
Process read access to register
|
||||
|
||||
:param request: The request
|
||||
:type request: Request
|
||||
:param reg_type: The register type
|
||||
:type reg_type: str
|
||||
"""
|
||||
address = request.register_addr
|
||||
|
||||
if address in self._register_dict[reg_type]:
|
||||
|
||||
if self._register_dict[reg_type][address].get('on_get_cb', 0):
|
||||
vals = self._create_response(request=request,
|
||||
reg_type=reg_type)
|
||||
_cb = self._register_dict[reg_type][address]['on_get_cb']
|
||||
_cb(reg_type=reg_type, address=address, val=vals)
|
||||
|
||||
vals = self._create_response(request=request, reg_type=reg_type)
|
||||
request.send_response(vals)
|
||||
else:
|
||||
request.send_exception(Const.ILLEGAL_DATA_ADDRESS)
|
||||
|
||||
def _process_write_access(self, request: Request, reg_type: str) -> None:
|
||||
"""
|
||||
Process write access to register
|
||||
|
||||
:param request: The request
|
||||
:type request: Request
|
||||
:param reg_type: The register type
|
||||
:type reg_type: str
|
||||
"""
|
||||
address = request.register_addr
|
||||
val = 0
|
||||
valid_register = False
|
||||
|
||||
if address in self._register_dict[reg_type]:
|
||||
if request.data is None:
|
||||
request.send_exception(Const.ILLEGAL_DATA_VALUE)
|
||||
return
|
||||
|
||||
if reg_type == 'COILS':
|
||||
valid_register = True
|
||||
|
||||
if request.function == Const.WRITE_SINGLE_COIL:
|
||||
val = request.data[0]
|
||||
if 0x00 < val < 0xFF:
|
||||
valid_register = False
|
||||
request.send_exception(Const.ILLEGAL_DATA_VALUE)
|
||||
else:
|
||||
val = [(val == 0xFF)]
|
||||
elif request.function == Const.WRITE_MULTIPLE_COILS:
|
||||
tmp = int.from_bytes(request.data, "big")
|
||||
val = [
|
||||
bool(tmp & (1 << n)) for n in range(request.quantity)
|
||||
]
|
||||
|
||||
if valid_register:
|
||||
self.set_coil(address=address, value=val)
|
||||
elif reg_type == 'HREGS':
|
||||
valid_register = True
|
||||
val = list(functions.to_short(byte_array=request.data,
|
||||
signed=False))
|
||||
|
||||
if request.function in [Const.WRITE_SINGLE_REGISTER,
|
||||
Const.WRITE_MULTIPLE_REGISTERS]:
|
||||
self.set_hreg(address=address, value=val)
|
||||
else:
|
||||
# nothing except holding registers or coils can be set
|
||||
request.send_exception(Const.ILLEGAL_FUNCTION)
|
||||
|
||||
if valid_register:
|
||||
request.send_response()
|
||||
self._set_changed_register(reg_type=reg_type,
|
||||
address=address,
|
||||
value=val)
|
||||
if self._register_dict[reg_type][address].get('on_set_cb', 0):
|
||||
_cb = self._register_dict[reg_type][address]['on_set_cb']
|
||||
_cb(reg_type=reg_type, address=address, val=val)
|
||||
else:
|
||||
request.send_exception(Const.ILLEGAL_DATA_ADDRESS)
|
||||
|
||||
def add_coil(self,
|
||||
address: int,
|
||||
value: Union[bool, List[bool]] = False,
|
||||
on_set_cb: Callable[[str, int, Union[List[bool], List[int]]],
|
||||
None] = None,
|
||||
on_get_cb: Callable[[str, int, Union[List[bool], List[int]]],
|
||||
None] = None) -> None:
|
||||
"""
|
||||
Add a coil to the modbus register dictionary.
|
||||
|
||||
:param address: The address (ID) of the register
|
||||
:type address: int
|
||||
:param value: The default value
|
||||
:type value: Union[bool, List[bool]], optional
|
||||
:param on_set_cb: Callback on setting the coil
|
||||
:type on_set_cb: Callable[
|
||||
[str, int, Union[List[bool], List[int]]],
|
||||
None
|
||||
]
|
||||
:param on_get_cb: Callback on getting the coil
|
||||
:type on_get_cb: Callable[
|
||||
[str, int, Union[List[bool], List[int]]],
|
||||
None
|
||||
]
|
||||
"""
|
||||
self._set_reg_in_dict(reg_type='COILS',
|
||||
address=address,
|
||||
value=value,
|
||||
on_set_cb=on_set_cb,
|
||||
on_get_cb=on_get_cb)
|
||||
|
||||
def remove_coil(self, address: int) -> Union[None, bool, List[bool]]:
|
||||
"""
|
||||
Remove a coil from the modbus register dictionary.
|
||||
|
||||
:param address: The address (ID) of the register
|
||||
:type address: int
|
||||
|
||||
:returns: Register value, None if register did not exist in dict
|
||||
:rtype: Union[None, bool, List[bool]]
|
||||
"""
|
||||
return self._remove_reg_from_dict(reg_type='COILS', address=address)
|
||||
|
||||
def set_coil(self,
|
||||
address: int,
|
||||
value: Union[bool, List[bool]] = False) -> None:
|
||||
"""
|
||||
Set the coil value.
|
||||
|
||||
:param address: The address (ID) of the register
|
||||
:type address: int
|
||||
:param value: The default value
|
||||
:type value: Union[bool, List[bool]], optional
|
||||
"""
|
||||
self._set_reg_in_dict(reg_type='COILS',
|
||||
address=address,
|
||||
value=value)
|
||||
|
||||
def get_coil(self, address: int) -> Union[bool, List[bool]]:
|
||||
"""
|
||||
Get the coil value.
|
||||
|
||||
:param address: The address (ID) of the register
|
||||
:type address: bool
|
||||
|
||||
:returns: Coil value
|
||||
:rtype: Union[bool, List[bool]]
|
||||
"""
|
||||
return self._get_reg_in_dict(reg_type='COILS',
|
||||
address=address)
|
||||
|
||||
@property
|
||||
def coils(self) -> dict_keys:
|
||||
"""
|
||||
Get the configured coils.
|
||||
|
||||
:returns: The dictionary keys.
|
||||
:rtype: dict_keys
|
||||
"""
|
||||
return self._get_regs_of_dict(reg_type='COILS')
|
||||
|
||||
def add_hreg(self,
|
||||
address: int,
|
||||
value: Union[int, List[int]] = 0,
|
||||
on_set_cb: Callable[[str, int, List[int]], None] = None,
|
||||
on_get_cb: Callable[[str, int, List[int]], None] = None) -> None:
|
||||
"""
|
||||
Add a holding register to the modbus register dictionary.
|
||||
|
||||
:param address: The address (ID) of the register
|
||||
:type address: int
|
||||
:param value: The default value
|
||||
:type value: Union[int, List[int]], optional
|
||||
:param on_set_cb: Callback on setting the holding register
|
||||
:type on_set_cb: Callable[[str, int, List[int]], None]
|
||||
:param on_get_cb: Callback on getting the holding register
|
||||
:type on_get_cb: Callable[[str, int, List[int]], None]
|
||||
"""
|
||||
self._set_reg_in_dict(reg_type='HREGS',
|
||||
address=address,
|
||||
value=value,
|
||||
on_set_cb=on_set_cb,
|
||||
on_get_cb=on_get_cb)
|
||||
|
||||
def remove_hreg(self, address: int) -> Union[None, int, List[int]]:
|
||||
"""
|
||||
Remove a holding register from the modbus register dictionary.
|
||||
|
||||
:param address: The address (ID) of the register
|
||||
:type address: int
|
||||
|
||||
:returns: Register value, None if register did not exist in dict
|
||||
:rtype: Union[None, int, List[int]]
|
||||
"""
|
||||
return self._remove_reg_from_dict(reg_type='HREGS', address=address)
|
||||
|
||||
def set_hreg(self, address: int, value: Union[int, List[int]] = 0) -> None:
|
||||
"""
|
||||
Set the holding register value.
|
||||
|
||||
:param address: The address (ID) of the register
|
||||
:type address: int
|
||||
:param value: The default value
|
||||
:type value: int or list of int, optional
|
||||
"""
|
||||
self._set_reg_in_dict(reg_type='HREGS',
|
||||
address=address,
|
||||
value=value)
|
||||
|
||||
def get_hreg(self, address: int) -> Union[int, List[int]]:
|
||||
"""
|
||||
Get the holding register value.
|
||||
|
||||
:param address: The address (ID) of the register
|
||||
:type address: int
|
||||
|
||||
:returns: Holding register value
|
||||
:rtype: Union[int, List[int]]
|
||||
"""
|
||||
return self._get_reg_in_dict(reg_type='HREGS',
|
||||
address=address)
|
||||
|
||||
@property
|
||||
def hregs(self) -> dict_keys:
|
||||
"""
|
||||
Get the configured holding registers.
|
||||
|
||||
:returns: The dictionary keys.
|
||||
:rtype: dict_keys
|
||||
"""
|
||||
return self._get_regs_of_dict(reg_type='HREGS')
|
||||
|
||||
def add_ist(self,
|
||||
address: int,
|
||||
value: Union[bool, List[bool]] = False,
|
||||
on_get_cb: Callable[[str, int, Union[List[bool], List[int]]],
|
||||
None] = None) -> None:
|
||||
"""
|
||||
Add a discrete input register to the modbus register dictionary.
|
||||
|
||||
:param address: The address (ID) of the register
|
||||
:type address: int
|
||||
:param value: The default value
|
||||
:type value: bool or list of bool, optional
|
||||
:param on_get_cb: Callback on getting the discrete input register
|
||||
:type on_get_cb: Callable[
|
||||
[str, int, Union[List[bool], List[int]]],
|
||||
None
|
||||
]
|
||||
"""
|
||||
self._set_reg_in_dict(reg_type='ISTS',
|
||||
address=address,
|
||||
value=value,
|
||||
on_get_cb=on_get_cb)
|
||||
|
||||
def remove_ist(self, address: int) -> Union[None, bool, List[bool]]:
|
||||
"""
|
||||
Remove a discrete input register from the modbus register dictionary.
|
||||
|
||||
:param address: The address (ID) of the register
|
||||
:type address: int
|
||||
|
||||
:returns: Register value, None if register did not exist in dict
|
||||
:rtype: Union[None, bool, List[bool]]
|
||||
"""
|
||||
return self._remove_reg_from_dict(reg_type='ISTS', address=address)
|
||||
|
||||
def set_ist(self, address: int, value: bool = False) -> None:
|
||||
"""
|
||||
Set the discrete input register value.
|
||||
|
||||
:param address: The address (ID) of the register
|
||||
:type address: int
|
||||
:param value: The default value
|
||||
:type value: bool or list of bool, optional
|
||||
"""
|
||||
self._set_reg_in_dict(reg_type='ISTS',
|
||||
address=address,
|
||||
value=value)
|
||||
|
||||
def get_ist(self, address: int) -> Union[bool, List[bool]]:
|
||||
"""
|
||||
Get the discrete input register value.
|
||||
|
||||
:param address: The address (ID) of the register
|
||||
:type address: int
|
||||
|
||||
:returns: Discrete input register value
|
||||
:rtype: Union[bool, List[bool]]
|
||||
"""
|
||||
return self._get_reg_in_dict(reg_type='ISTS',
|
||||
address=address)
|
||||
|
||||
@property
|
||||
def ists(self) -> dict_keys:
|
||||
"""
|
||||
Get the configured discrete input registers.
|
||||
|
||||
:returns: The dictionary keys.
|
||||
:rtype: dict_keys
|
||||
"""
|
||||
return self._get_regs_of_dict(reg_type='ISTS')
|
||||
|
||||
def add_ireg(self,
|
||||
address: int,
|
||||
value: Union[int, List[int]] = 0,
|
||||
on_get_cb: Callable[[str, int, Union[List[bool], List[int]]],
|
||||
None] = None) -> None:
|
||||
"""
|
||||
Add an input register to the modbus register dictionary.
|
||||
|
||||
:param address: The address (ID) of the register
|
||||
:type address: int
|
||||
:param value: The default value
|
||||
:type value: Union[int, List[int]], optional
|
||||
:param on_get_cb: Callback on getting the input register
|
||||
:type on_get_cb: Callable[
|
||||
[str, int, Union[List[bool], List[int]]],
|
||||
None
|
||||
]
|
||||
"""
|
||||
self._set_reg_in_dict(reg_type='IREGS',
|
||||
address=address,
|
||||
value=value,
|
||||
on_get_cb=on_get_cb)
|
||||
|
||||
def remove_ireg(self, address: int) -> Union[None, int, List[int]]:
|
||||
"""
|
||||
Remove an input register from the modbus register dictionary.
|
||||
|
||||
:param address: The address (ID) of the register
|
||||
:type address: int
|
||||
|
||||
:returns: Register value, None if register did not exist in dict
|
||||
:rtype: Union[None, int, List[int]]
|
||||
"""
|
||||
return self._remove_reg_from_dict(reg_type='IREGS', address=address)
|
||||
|
||||
def set_ireg(self, address: int, value: Union[int, List[int]] = 0) -> None:
|
||||
"""
|
||||
Set the input register value.
|
||||
|
||||
:param address: The address (ID) of the register
|
||||
:type address: int
|
||||
:param value: The default value
|
||||
:type value: Union[int, List[int]], optional
|
||||
"""
|
||||
self._set_reg_in_dict(reg_type='IREGS',
|
||||
address=address,
|
||||
value=value)
|
||||
|
||||
def get_ireg(self, address: int) -> Union[int, List[int]]:
|
||||
"""
|
||||
Get the input register value.
|
||||
|
||||
:param address: The address (ID) of the register
|
||||
:type address: int
|
||||
|
||||
:returns: Input register value
|
||||
:rtype: Union[int, List[int]]
|
||||
"""
|
||||
return self._get_reg_in_dict(reg_type='IREGS',
|
||||
address=address)
|
||||
|
||||
@property
|
||||
def iregs(self) -> dict_keys:
|
||||
"""
|
||||
Get the configured input registers.
|
||||
|
||||
:returns: The dictionary keys.
|
||||
:rtype: dict_keys
|
||||
"""
|
||||
return self._get_regs_of_dict(reg_type='IREGS')
|
||||
|
||||
def _set_reg_in_dict(self,
|
||||
reg_type: str,
|
||||
address: int,
|
||||
value: Union[bool, int, List[bool], List[int]],
|
||||
on_set_cb: Callable[[str, int, Union[List[bool],
|
||||
List[int]]],
|
||||
None] = None,
|
||||
on_get_cb: Callable[[str, int, Union[List[bool],
|
||||
List[int]]],
|
||||
None] = None) -> None:
|
||||
"""
|
||||
Set the register value in the dictionary of registers.
|
||||
|
||||
:param reg_type: The register type
|
||||
:type reg_type: str
|
||||
:param address: The address (ID) of the register
|
||||
:type address: int
|
||||
:param value: The value(s) of the register(s)
|
||||
:type value: Union[bool, int, List[bool], List[int]]
|
||||
:param on_set_cb: Callback on setting the register
|
||||
:type on_get_cb: Callable[
|
||||
[str, int, Union[List[bool], List[int]]],
|
||||
None
|
||||
]
|
||||
:param on_get_cb: Callback on getting the register
|
||||
:type on_get_cb: Callable[
|
||||
[str, int, Union[List[bool], List[int]]],
|
||||
None
|
||||
]
|
||||
|
||||
:raise KeyError: No register at specified address found
|
||||
"""
|
||||
if not self._check_valid_register(reg_type=reg_type):
|
||||
raise KeyError('{} is not a valid register type of {}'.
|
||||
format(reg_type, self._available_register_types))
|
||||
|
||||
if isinstance(value, (list, tuple)):
|
||||
# flatten the list and add single registers only
|
||||
for idx, val in enumerate(value):
|
||||
this_addr = address + idx
|
||||
self._set_single_reg_in_dict(reg_type=reg_type,
|
||||
address=this_addr,
|
||||
value=val,
|
||||
on_set_cb=on_set_cb,
|
||||
on_get_cb=on_get_cb)
|
||||
else:
|
||||
self._set_single_reg_in_dict(reg_type=reg_type,
|
||||
address=address,
|
||||
value=value,
|
||||
on_set_cb=on_set_cb,
|
||||
on_get_cb=on_get_cb)
|
||||
|
||||
def _set_single_reg_in_dict(self,
|
||||
reg_type: str,
|
||||
address: int,
|
||||
value: Union[bool, int],
|
||||
on_set_cb: Callable[
|
||||
[str, int, Union[List[bool], List[int]]],
|
||||
None
|
||||
] = None,
|
||||
on_get_cb: Callable[
|
||||
[str, int, Union[List[bool], List[int]]],
|
||||
None
|
||||
] = None) -> None:
|
||||
"""
|
||||
Set a register value in the dictionary of registers.
|
||||
|
||||
:param reg_type: The register type
|
||||
:type reg_type: str
|
||||
:param address: The address (ID) of the register
|
||||
:type address: int
|
||||
:param value: The value of the register
|
||||
:type value: Union[bool, int]
|
||||
:param on_set_cb: Callback on setting the register
|
||||
:type on_get_cb: Callable[
|
||||
[str, int, Union[List[bool], List[int]]],
|
||||
None
|
||||
]
|
||||
:param on_get_cb: Callback on getting the register
|
||||
:type on_get_cb: Callable[
|
||||
[str, int, Union[List[bool], List[int]]],
|
||||
None
|
||||
]
|
||||
"""
|
||||
data = {'val': value}
|
||||
|
||||
# if the register exists already in the register dict a "set_*"
|
||||
# function might have called this functions
|
||||
if address in self._register_dict[reg_type]:
|
||||
# try to get the (already) registered callback function from the
|
||||
# register dict of this address with the this time call function
|
||||
# parameter callback value as fallback
|
||||
on_set_cb = self._register_dict[reg_type][address].get('on_set_cb',
|
||||
on_set_cb)
|
||||
|
||||
on_get_cb = self._register_dict[reg_type][address].get('on_get_cb',
|
||||
on_get_cb)
|
||||
|
||||
if callable(on_set_cb):
|
||||
data['on_set_cb'] = on_set_cb
|
||||
|
||||
if callable(on_get_cb):
|
||||
data['on_get_cb'] = on_get_cb
|
||||
|
||||
self._register_dict[reg_type][address] = data
|
||||
|
||||
def _remove_reg_from_dict(self,
|
||||
reg_type: str,
|
||||
address: int) -> Union[None, bool, int, List[bool], List[int]]:
|
||||
"""
|
||||
Remove the register from the dictionary of registers.
|
||||
|
||||
:param reg_type: The register type
|
||||
:type reg_type: str
|
||||
:param address: The address (ID) of the register
|
||||
:type address: int
|
||||
|
||||
:raise KeyError: No register at specified address found
|
||||
:returns: Register value, None if register did not exist in dict
|
||||
:rtype: Union[None, bool, int, List[bool], List[int]]
|
||||
"""
|
||||
if not self._check_valid_register(reg_type=reg_type):
|
||||
raise KeyError('{} is not a valid register type of {}'.
|
||||
format(reg_type, self._available_register_types))
|
||||
|
||||
return self._register_dict[reg_type].pop(address, None)
|
||||
|
||||
def _get_reg_in_dict(self,
|
||||
reg_type: str,
|
||||
address: int) -> Union[bool, int, List[bool], List[int]]:
|
||||
"""
|
||||
Get the register value from the dictionary of registers.
|
||||
|
||||
:param reg_type: The register type
|
||||
:type reg_type: str
|
||||
:param address: The address (ID) of the register
|
||||
:type address: int
|
||||
|
||||
:raise KeyError: No register at specified address found
|
||||
:returns: Register value
|
||||
:rtype: Union[bool, int, List[bool], List[int]]
|
||||
"""
|
||||
if not self._check_valid_register(reg_type=reg_type):
|
||||
raise KeyError('{} is not a valid register type of {}'.
|
||||
format(reg_type, self._available_register_types))
|
||||
|
||||
if address in self._register_dict[reg_type]:
|
||||
return self._register_dict[reg_type][address]['val']
|
||||
else:
|
||||
raise KeyError('No {} available for the register address {}'.
|
||||
format(reg_type, address))
|
||||
|
||||
def _get_regs_of_dict(self, reg_type: str) -> dict_keys:
|
||||
"""
|
||||
Get all configured registers of specified register type.
|
||||
|
||||
:param reg_type: The register type
|
||||
:type reg_type: str
|
||||
|
||||
:raise KeyError: No register at specified address found
|
||||
:returns: The configured registers of the specified register type.
|
||||
:rtype: dict_keys
|
||||
"""
|
||||
if not self._check_valid_register(reg_type=reg_type):
|
||||
raise KeyError('{} is not a valid register type of {}'.
|
||||
format(reg_type, self._available_register_types))
|
||||
|
||||
return self._register_dict[reg_type].keys()
|
||||
|
||||
def _check_valid_register(self, reg_type: str) -> bool:
|
||||
"""
|
||||
Check register type to be a valid modbus register
|
||||
|
||||
:param reg_type: The register type
|
||||
:type reg_type: str
|
||||
|
||||
:returns: Flag whether register type is valid
|
||||
:rtype: bool
|
||||
"""
|
||||
if reg_type in self._available_register_types:
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
|
||||
@property
|
||||
def changed_registers(self) -> dict:
|
||||
"""
|
||||
Get the changed registers.
|
||||
|
||||
:returns: The changed registers.
|
||||
:rtype: dict
|
||||
"""
|
||||
return self._changed_registers
|
||||
|
||||
@property
|
||||
def changed_coils(self) -> dict:
|
||||
"""
|
||||
Get the changed coil registers.
|
||||
|
||||
:returns: The changed coil registers.
|
||||
:rtype: dict
|
||||
"""
|
||||
return self._changed_registers['COILS']
|
||||
|
||||
@property
|
||||
def changed_hregs(self) -> dict:
|
||||
"""
|
||||
Get the changed holding registers.
|
||||
|
||||
:returns: The changed holding registers.
|
||||
:rtype: dict
|
||||
"""
|
||||
return self._changed_registers['HREGS']
|
||||
|
||||
def _set_changed_register(self,
|
||||
reg_type: str,
|
||||
address: int,
|
||||
value: Union[bool, int, List[bool], List[int]]) -> None:
|
||||
"""
|
||||
Set the register value in the dictionary of changed registers.
|
||||
|
||||
:param reg_type: The register type
|
||||
:type reg_type: str
|
||||
:param address: The address (ID) of the register
|
||||
:type address: int
|
||||
:param value: The value
|
||||
:type value: Union[bool, int, List[bool], List[int]]
|
||||
|
||||
:raise KeyError: Register can not be changed externally
|
||||
"""
|
||||
if reg_type in self._changeable_register_types:
|
||||
if isinstance(value, (list, tuple)):
|
||||
for idx, val in enumerate(value):
|
||||
content = {'val': val, 'time': time.ticks_ms()}
|
||||
self._changed_registers[reg_type][address + idx] = content
|
||||
else:
|
||||
content = {'val': value, 'time': time.ticks_ms()}
|
||||
self._changed_registers[reg_type][address] = content
|
||||
else:
|
||||
raise KeyError('{} can not be changed externally'.format(reg_type))
|
||||
|
||||
def _remove_changed_register(self,
|
||||
reg_type: str,
|
||||
address: int,
|
||||
timestamp: int) -> bool:
|
||||
"""
|
||||
Remove the register from the dictionary of changed registers.
|
||||
|
||||
:param reg_type: The register type
|
||||
:type reg_type: str
|
||||
:param address: The address (ID) of the register
|
||||
:type address: int
|
||||
:param timestamp: The timestamp of the change in milliseconds
|
||||
:type timestamp: int
|
||||
|
||||
:raise KeyError: No register at specified address found
|
||||
:returns: Result of removing register from dict
|
||||
:rtype: bool
|
||||
"""
|
||||
result = False
|
||||
|
||||
if reg_type in self._changeable_register_types:
|
||||
_changed_register_timestamp = self._changed_registers[reg_type][address]['time']
|
||||
|
||||
if _changed_register_timestamp == timestamp:
|
||||
self._changed_registers[reg_type].pop(address, None)
|
||||
result = True
|
||||
else:
|
||||
raise KeyError('{} is not a valid register type of {}'.
|
||||
format(reg_type, self._changeable_register_types))
|
||||
|
||||
return result
|
||||
|
||||
def setup_registers(self,
|
||||
registers: dict = dict(),
|
||||
use_default_vals: Optional[bool] = False) -> None:
|
||||
"""
|
||||
Setup all registers of the client
|
||||
|
||||
:param registers: The registers
|
||||
:type registers: dict
|
||||
:param use_default_vals: Flag to use dummy default values
|
||||
:type use_default_vals: Optional[bool]
|
||||
"""
|
||||
if len(registers):
|
||||
for reg_type, default_val in self._default_vals.items():
|
||||
if reg_type in registers:
|
||||
for reg, val in registers[reg_type].items():
|
||||
address = val['register']
|
||||
|
||||
if use_default_vals:
|
||||
if 'len' in val:
|
||||
value = [default_val] * val['len']
|
||||
else:
|
||||
value = default_val
|
||||
else:
|
||||
value = val['val']
|
||||
|
||||
on_set_cb = val.get('on_set_cb', None)
|
||||
on_get_cb = val.get('on_get_cb', None)
|
||||
|
||||
if reg_type == 'COILS':
|
||||
self.add_coil(address=address,
|
||||
value=value,
|
||||
on_set_cb=on_set_cb,
|
||||
on_get_cb=on_get_cb)
|
||||
elif reg_type == 'HREGS':
|
||||
self.add_hreg(address=address,
|
||||
value=value,
|
||||
on_set_cb=on_set_cb,
|
||||
on_get_cb=on_get_cb)
|
||||
elif reg_type == 'ISTS':
|
||||
self.add_ist(address=address,
|
||||
value=value,
|
||||
on_get_cb=on_get_cb) # only getter
|
||||
elif reg_type == 'IREGS':
|
||||
self.add_ireg(address=address,
|
||||
value=value,
|
||||
on_get_cb=on_get_cb) # only getter
|
||||
else:
|
||||
# invalid register type
|
||||
pass
|
||||
else:
|
||||
pass
|
||||
@@ -0,0 +1,476 @@
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# Copyright (c) 2019, Pycom Limited.
|
||||
#
|
||||
# This software is licensed under the GNU GPL version 3 or any
|
||||
# later version, with permitted additional terms. For more information
|
||||
# see the Pycom Licence v1.0 document supplied with this file, or
|
||||
# available at https://www.pycom.io/opensource/licensing
|
||||
#
|
||||
|
||||
# system packages
|
||||
from machine import UART
|
||||
from machine import Pin
|
||||
import struct
|
||||
import time
|
||||
|
||||
# custom packages
|
||||
from . import const as Const
|
||||
from . import functions
|
||||
from .common import Request, CommonModbusFunctions
|
||||
from .common import ModbusException
|
||||
from .modbus import Modbus
|
||||
|
||||
# typing not natively supported on MicroPython
|
||||
from .typing import List, Optional, Union
|
||||
|
||||
|
||||
class ModbusRTU(Modbus):
|
||||
"""
|
||||
Modbus RTU client class
|
||||
|
||||
:param addr: The address of this device on the bus
|
||||
:type addr: int
|
||||
:param baudrate: The baudrate, default 9600
|
||||
:type baudrate: int
|
||||
:param data_bits: The data bits, default 8
|
||||
:type data_bits: int
|
||||
:param stop_bits: The stop bits, default 1
|
||||
:type stop_bits: int
|
||||
:param parity: The parity, default None
|
||||
:type parity: Optional[int]
|
||||
:param pins: The pins as list [TX, RX]
|
||||
:type pins: List[Union[int, Pin], Union[int, Pin]]
|
||||
:param ctrl_pin: The control pin
|
||||
:type ctrl_pin: int
|
||||
:param uart_id: The ID of the used UART
|
||||
:type uart_id: int
|
||||
"""
|
||||
def __init__(self,
|
||||
addr: int,
|
||||
baudrate: int = 9600,
|
||||
data_bits: int = 8,
|
||||
stop_bits: int = 1,
|
||||
parity: Optional[int] = None,
|
||||
pins: List[Union[int, Pin], Union[int, Pin]] = None,
|
||||
ctrl_pin: int = None,
|
||||
uart_id: int = 1):
|
||||
super().__init__(
|
||||
# set itf to Serial object, addr_list to [addr]
|
||||
Serial(uart_id=uart_id,
|
||||
baudrate=baudrate,
|
||||
data_bits=data_bits,
|
||||
stop_bits=stop_bits,
|
||||
parity=parity,
|
||||
pins=pins,
|
||||
ctrl_pin=ctrl_pin),
|
||||
[addr]
|
||||
)
|
||||
|
||||
|
||||
class Serial(CommonModbusFunctions):
|
||||
def __init__(self,
|
||||
uart_id: int = 1,
|
||||
baudrate: int = 9600,
|
||||
data_bits: int = 8,
|
||||
stop_bits: int = 1,
|
||||
parity=None,
|
||||
pins: List[Union[int, Pin], Union[int, Pin]] = None,
|
||||
ctrl_pin: int = None):
|
||||
"""
|
||||
Setup Serial/RTU Modbus
|
||||
|
||||
:param uart_id: The ID of the used UART
|
||||
:type uart_id: int
|
||||
:param baudrate: The baudrate, default 9600
|
||||
:type baudrate: int
|
||||
:param data_bits: The data bits, default 8
|
||||
:type data_bits: int
|
||||
:param stop_bits: The stop bits, default 1
|
||||
:type stop_bits: int
|
||||
:param parity: The parity, default None
|
||||
:type parity: Optional[int]
|
||||
:param pins: The pins as list [TX, RX]
|
||||
:type pins: List[Union[int, Pin], Union[int, Pin]]
|
||||
:param ctrl_pin: The control pin
|
||||
:type ctrl_pin: int
|
||||
"""
|
||||
# UART flush function is introduced in Micropython v1.20.0
|
||||
self._has_uart_flush = callable(getattr(UART, "flush", None))
|
||||
if ctrl_pin is not None and ctrl_pin < 0:
|
||||
self._uart = UART(uart_id,
|
||||
baudrate=baudrate,
|
||||
bits=data_bits,
|
||||
parity=parity,
|
||||
stop=stop_bits,
|
||||
# timeout_chars=2, # WiPy only
|
||||
pins=pins, # WiPy only
|
||||
flow=-ctrl_pin
|
||||
)
|
||||
ctrl_pin = None
|
||||
else:
|
||||
self._uart = UART(uart_id,
|
||||
baudrate=baudrate,
|
||||
bits=data_bits,
|
||||
parity=parity,
|
||||
stop=stop_bits,
|
||||
# timeout_chars=2, # WiPy only
|
||||
pins=pins # WiPy only
|
||||
)
|
||||
|
||||
if ctrl_pin is not None:
|
||||
self._ctrlPin = Pin(ctrl_pin, mode=Pin.OUT)
|
||||
else:
|
||||
self._ctrlPin = None
|
||||
|
||||
# timing of 1 character in microseconds (us)
|
||||
self._t1char = (1000000 * (data_bits + stop_bits + 2)) // baudrate
|
||||
|
||||
# inter-frame delay in microseconds (us)
|
||||
# - <= 19200 bps: 3.5x timing of 1 character
|
||||
# - > 19200 bps: 1750 us
|
||||
if baudrate <= 19200:
|
||||
self._inter_frame_delay = (self._t1char * 3500) // 1000
|
||||
else:
|
||||
self._inter_frame_delay = 1750
|
||||
|
||||
def _calculate_crc16(self, data: bytearray) -> bytes:
|
||||
"""
|
||||
Calculates the CRC16.
|
||||
|
||||
:param data: The data
|
||||
:type data: bytearray
|
||||
|
||||
:returns: The crc 16.
|
||||
:rtype: bytes
|
||||
"""
|
||||
crc = 0xFFFF
|
||||
|
||||
for char in data:
|
||||
crc = (crc >> 8) ^ Const.CRC16_TABLE[((crc) ^ char) & 0xFF]
|
||||
|
||||
return struct.pack('<H', crc)
|
||||
|
||||
def _exit_read(self, response: bytearray) -> bool:
|
||||
"""
|
||||
Return on modbus read error
|
||||
|
||||
:param response: The response
|
||||
:type response: bytearray
|
||||
|
||||
:returns: State of basic read response evaluation,
|
||||
True if entire response has been read
|
||||
:rtype: bool
|
||||
"""
|
||||
response_len = len(response)
|
||||
if response_len >= 2 and response[1] >= Const.ERROR_BIAS:
|
||||
if response_len < Const.ERROR_RESP_LEN:
|
||||
return False
|
||||
elif response_len >= 3 and (Const.READ_COILS <= response[1] <= Const.READ_INPUT_REGISTER):
|
||||
expected_len = Const.RESPONSE_HDR_LENGTH + 1 + response[2] + Const.CRC_LENGTH
|
||||
if response_len < expected_len:
|
||||
return False
|
||||
elif response_len < Const.FIXED_RESP_LEN:
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
def _uart_read(self) -> bytearray:
|
||||
"""
|
||||
Read incoming slave response from UART
|
||||
|
||||
:returns: Read content
|
||||
:rtype: bytearray
|
||||
"""
|
||||
response = bytearray()
|
||||
|
||||
# TODO: use some kind of hint or user-configurable delay
|
||||
# to determine this loop counter
|
||||
for x in range(1, 120):
|
||||
rx = self._uart.read()
|
||||
if rx is not None:
|
||||
# WiPy only
|
||||
# response.extend(self._uart.readall())
|
||||
response.extend(rx)
|
||||
|
||||
# variable length function codes may require multiple reads
|
||||
if self._exit_read(response):
|
||||
break
|
||||
|
||||
# wait for the maximum time between two frames
|
||||
time.sleep_us(self._inter_frame_delay)
|
||||
|
||||
return response
|
||||
|
||||
def _uart_read_frame(self, timeout: Optional[int] = None) -> bytearray:
|
||||
"""
|
||||
Read a Modbus frame
|
||||
|
||||
:param timeout: The timeout
|
||||
:type timeout: Optional[int]
|
||||
|
||||
:returns: Received message
|
||||
:rtype: bytearray
|
||||
"""
|
||||
received_bytes = bytearray()
|
||||
|
||||
if self._uart.any() <= 0:
|
||||
return received_bytes
|
||||
|
||||
# set default timeout to at twice the inter-frame delay
|
||||
if timeout == 0 or timeout is None:
|
||||
timeout = 2 * self._inter_frame_delay # in microseconds
|
||||
|
||||
start_us = time.ticks_us()
|
||||
#print(start_us)
|
||||
|
||||
# stay inside this while loop at least for the timeout time
|
||||
while (time.ticks_diff(time.ticks_us(), start_us) <= timeout):
|
||||
# check amount of available characters
|
||||
if self._uart.any() > 0:
|
||||
# remember this time in microseconds
|
||||
last_byte_ts = time.ticks_us()
|
||||
|
||||
# do not stop reading and appending the result to the buffer
|
||||
# until the time between two frames elapsed
|
||||
while True:
|
||||
# WiPy only
|
||||
# r = self._uart.readall()
|
||||
time.sleep_us(100)
|
||||
r = self._uart.read()
|
||||
|
||||
# if something has been read after the first iteration of
|
||||
# this inner while loop (within self._inter_frame_delay)
|
||||
if r is not None and len(r) > 0:
|
||||
# append the new read stuff to the buffer
|
||||
received_bytes.extend(r)
|
||||
|
||||
# update the timestamp of the last byte being read
|
||||
last_byte_ts = time.ticks_us()
|
||||
#print(last_byte_ts, received_bytes)
|
||||
if time.ticks_diff(time.ticks_us(), last_byte_ts) >= self._inter_frame_delay:
|
||||
break
|
||||
# if something has been read before the overall timeout is reached
|
||||
if len(received_bytes) > 0:
|
||||
#print(time.ticks_diff(time.ticks_us(), start_us))
|
||||
return received_bytes
|
||||
|
||||
#print(time.ticks_diff(time.ticks_us(), start_us))
|
||||
# return the result in case the overall timeout has been reached
|
||||
return received_bytes
|
||||
|
||||
def _send(self, modbus_pdu: bytes, slave_addr: int) -> None:
|
||||
"""
|
||||
Send Modbus frame via UART
|
||||
|
||||
If a flow control pin has been setup, it will be controlled accordingly
|
||||
|
||||
:param modbus_pdu: The modbus Protocol Data Unit
|
||||
:type modbus_pdu: bytes
|
||||
:param slave_addr: The slave address
|
||||
:type slave_addr: int
|
||||
"""
|
||||
# modbus_adu: Modbus Application Data Unit
|
||||
# consists of the Modbus PDU, with slave address prepended and checksum appended
|
||||
modbus_adu = bytearray()
|
||||
modbus_adu.append(slave_addr)
|
||||
modbus_adu.extend(modbus_pdu)
|
||||
modbus_adu.extend(self._calculate_crc16(modbus_adu))
|
||||
|
||||
if self._ctrlPin:
|
||||
self._ctrlPin.on()
|
||||
# wait until the control pin really changed
|
||||
# 85-95us (ESP32 @ 160/240MHz)
|
||||
time.sleep_us(200)
|
||||
|
||||
# the timing of this part is critical:
|
||||
# - if we disable output too early,
|
||||
# the command will not be received in full
|
||||
# - if we disable output too late,
|
||||
# the incoming response will lose some data at the beginning
|
||||
# easiest to just wait for the bytes to be sent out on the wire
|
||||
|
||||
send_start_time = time.ticks_us()
|
||||
# 360-400us @ 9600-115200 baud (measured) (ESP32 @ 160/240MHz)
|
||||
self._uart.write(modbus_adu)
|
||||
send_finish_time = time.ticks_us()
|
||||
|
||||
if self._has_uart_flush:
|
||||
self._uart.flush()
|
||||
time.sleep_us(self._t1char)
|
||||
else:
|
||||
sleep_time_us = (
|
||||
self._t1char * len(modbus_adu) - # total frame time in us
|
||||
time.ticks_diff(send_finish_time, send_start_time) +
|
||||
100 # only required at baudrates above 57600, but hey 100us
|
||||
)
|
||||
time.sleep_us(sleep_time_us)
|
||||
|
||||
if self._ctrlPin:
|
||||
self._ctrlPin.off()
|
||||
|
||||
def _send_receive(self,
|
||||
modbus_pdu: bytes,
|
||||
slave_addr: int,
|
||||
count: bool) -> bytes:
|
||||
"""
|
||||
Send a modbus message and receive the reponse.
|
||||
|
||||
:param modbus_pdu: The modbus Protocol Data Unit
|
||||
:type modbus_pdu: bytes
|
||||
:param slave_addr: The slave address
|
||||
:type slave_addr: int
|
||||
:param count: The count
|
||||
:type count: bool
|
||||
|
||||
:returns: Validated response content
|
||||
:rtype: bytes
|
||||
"""
|
||||
# flush the Rx FIFO buffer
|
||||
self._uart.read()
|
||||
|
||||
self._send(modbus_pdu=modbus_pdu, slave_addr=slave_addr)
|
||||
|
||||
return self._validate_resp_hdr(response=self._uart_read(),
|
||||
slave_addr=slave_addr,
|
||||
function_code=modbus_pdu[0],
|
||||
count=count)
|
||||
|
||||
def _validate_resp_hdr(self,
|
||||
response: bytearray,
|
||||
slave_addr: int,
|
||||
function_code: int,
|
||||
count: bool) -> bytes:
|
||||
"""
|
||||
Validate the response header.
|
||||
|
||||
:param response: The response
|
||||
:type response: bytearray
|
||||
:param slave_addr: The slave address
|
||||
:type slave_addr: int
|
||||
:param function_code: The function code
|
||||
:type function_code: int
|
||||
:param count: The count
|
||||
:type count: bool
|
||||
|
||||
:returns: Modbus response content
|
||||
:rtype: bytes
|
||||
"""
|
||||
if len(response) == 0:
|
||||
raise OSError('no data received from slave')
|
||||
|
||||
resp_crc = response[-Const.CRC_LENGTH:]
|
||||
expected_crc = self._calculate_crc16(
|
||||
response[0:len(response) - Const.CRC_LENGTH]
|
||||
)
|
||||
|
||||
if ((resp_crc[0] is not expected_crc[0]) or
|
||||
(resp_crc[1] is not expected_crc[1])):
|
||||
raise OSError('invalid response CRC')
|
||||
|
||||
if (response[0] != slave_addr):
|
||||
raise ValueError('wrong slave address')
|
||||
|
||||
if (response[1] == (function_code + Const.ERROR_BIAS)):
|
||||
raise ValueError('slave returned exception code: {:d}'.
|
||||
format(response[2]))
|
||||
|
||||
hdr_length = (Const.RESPONSE_HDR_LENGTH + 1) if count else \
|
||||
Const.RESPONSE_HDR_LENGTH
|
||||
|
||||
return response[hdr_length:len(response) - Const.CRC_LENGTH]
|
||||
|
||||
def send_response(self,
|
||||
slave_addr: int,
|
||||
function_code: int,
|
||||
request_register_addr: int,
|
||||
request_register_qty: int,
|
||||
request_data: list,
|
||||
values: Optional[list] = None,
|
||||
signed: bool = True) -> None:
|
||||
"""
|
||||
Send a response to a client.
|
||||
|
||||
:param slave_addr: The slave address
|
||||
:type slave_addr: int
|
||||
:param function_code: The function code
|
||||
:type function_code: int
|
||||
:param request_register_addr: The request register address
|
||||
:type request_register_addr: int
|
||||
:param request_register_qty: The request register qty
|
||||
:type request_register_qty: int
|
||||
:param request_data: The request data
|
||||
:type request_data: list
|
||||
:param values: The values
|
||||
:type values: Optional[list]
|
||||
:param signed: Indicates if signed
|
||||
:type signed: bool
|
||||
"""
|
||||
modbus_pdu = functions.response(
|
||||
function_code=function_code,
|
||||
request_register_addr=request_register_addr,
|
||||
request_register_qty=request_register_qty,
|
||||
request_data=request_data,
|
||||
value_list=values,
|
||||
signed=signed
|
||||
)
|
||||
self._send(modbus_pdu=modbus_pdu, slave_addr=slave_addr)
|
||||
|
||||
def send_exception_response(self,
|
||||
slave_addr: int,
|
||||
function_code: int,
|
||||
exception_code: int) -> None:
|
||||
"""
|
||||
Send an exception response to a client.
|
||||
|
||||
:param slave_addr: The slave address
|
||||
:type slave_addr: int
|
||||
:param function_code: The function code
|
||||
:type function_code: int
|
||||
:param exception_code: The exception code
|
||||
:type exception_code: int
|
||||
"""
|
||||
modbus_pdu = functions.exception_response(
|
||||
function_code=function_code,
|
||||
exception_code=exception_code)
|
||||
self._send(modbus_pdu=modbus_pdu, slave_addr=slave_addr)
|
||||
|
||||
def get_request(self,
|
||||
unit_addr_list: List[int],
|
||||
timeout: Optional[int] = None) -> Union[Request, None]:
|
||||
"""
|
||||
Check for request within the specified timeout
|
||||
|
||||
:param unit_addr_list: The unit address list
|
||||
:type unit_addr_list: Optional[list]
|
||||
:param timeout: The timeout
|
||||
:type timeout: Optional[int]
|
||||
|
||||
:returns: A request object or None.
|
||||
:rtype: Union[Request, None]
|
||||
"""
|
||||
req = self._uart_read_frame(timeout=timeout)
|
||||
|
||||
if len(req) < 8:
|
||||
return None
|
||||
|
||||
if req[0] not in unit_addr_list:
|
||||
return None
|
||||
|
||||
req_crc = req[-Const.CRC_LENGTH:]
|
||||
req_no_crc = req[:-Const.CRC_LENGTH]
|
||||
expected_crc = self._calculate_crc16(req_no_crc)
|
||||
|
||||
if (req_crc[0] != expected_crc[0]) or (req_crc[1] != expected_crc[1]):
|
||||
return None
|
||||
|
||||
try:
|
||||
request = Request(interface=self, data=req_no_crc)
|
||||
except ModbusException as e:
|
||||
self.send_exception_response(
|
||||
slave_addr=req[0],
|
||||
function_code=e.function_code,
|
||||
exception_code=e.exception_code)
|
||||
return None
|
||||
|
||||
return request
|
||||
@@ -0,0 +1,416 @@
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# Copyright (c) 2019, Pycom Limited.
|
||||
#
|
||||
# This software is licensed under the GNU GPL version 3 or any
|
||||
# later version, with permitted additional terms. For more information
|
||||
# see the Pycom Licence v1.0 document supplied with this file, or
|
||||
# available at https://www.pycom.io/opensource/licensing
|
||||
#
|
||||
|
||||
# system packages
|
||||
# import random
|
||||
import struct
|
||||
import socket
|
||||
import time
|
||||
|
||||
# custom packages
|
||||
from . import functions
|
||||
from . import const as Const
|
||||
from .common import Request, CommonModbusFunctions
|
||||
from .common import ModbusException
|
||||
from .modbus import Modbus
|
||||
|
||||
# typing not natively supported on MicroPython
|
||||
from .typing import Optional, Tuple, Union
|
||||
|
||||
|
||||
class ModbusTCP(Modbus):
|
||||
"""Modbus TCP client class"""
|
||||
def __init__(self):
|
||||
super().__init__(
|
||||
# set itf to TCPServer object, addr_list to None
|
||||
TCPServer(),
|
||||
None
|
||||
)
|
||||
|
||||
def bind(self,
|
||||
local_ip: str,
|
||||
local_port: int = 502,
|
||||
max_connections: int = 10) -> None:
|
||||
"""
|
||||
Bind IP and port for incomming requests
|
||||
|
||||
:param local_ip: IP of this device listening for requests
|
||||
:type local_ip: str
|
||||
:param local_port: Port of this device
|
||||
:type local_port: int
|
||||
:param max_connections: Number of maximum connections
|
||||
:type max_connections: int
|
||||
"""
|
||||
self._itf.bind(local_ip, local_port, max_connections)
|
||||
|
||||
def get_bound_status(self) -> bool:
|
||||
"""
|
||||
Get the IP and port binding status.
|
||||
|
||||
:returns: The bound status, True if already bound, False otherwise.
|
||||
:rtype: bool
|
||||
"""
|
||||
try:
|
||||
return self._itf.get_is_bound()
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
class TCP(CommonModbusFunctions):
|
||||
"""
|
||||
TCP class handling socket connections and parsing the Modbus data
|
||||
|
||||
:param slave_ip: IP of this device listening for requests
|
||||
:type slave_ip: str
|
||||
:param slave_port: Port of this device
|
||||
:type slave_port: int
|
||||
:param timeout: Socket timeout in seconds
|
||||
:type timeout: float
|
||||
"""
|
||||
def __init__(self,
|
||||
slave_ip: str,
|
||||
slave_port: int = 502,
|
||||
timeout: float = 5.0):
|
||||
self._sock = socket.socket()
|
||||
self.trans_id_ctr = 0
|
||||
|
||||
# print(socket.getaddrinfo(slave_ip, slave_port))
|
||||
# [(2, 1, 0, '192.168.178.47', ('192.168.178.47', 502))]
|
||||
self._sock.connect(socket.getaddrinfo(slave_ip, slave_port)[0][-1])
|
||||
|
||||
self._sock.settimeout(timeout)
|
||||
|
||||
def _create_mbap_hdr(self,
|
||||
slave_addr: int,
|
||||
modbus_pdu: bytes) -> Tuple[bytes, int]:
|
||||
"""
|
||||
Create a Modbus header.
|
||||
|
||||
:param slave_addr: The slave identifier
|
||||
:type slave_addr: int
|
||||
:param modbus_pdu: The modbus Protocol Data Unit
|
||||
:type modbus_pdu: bytes
|
||||
|
||||
:returns: Modbus header and unique transaction ID
|
||||
:rtype: Tuple[bytes, int]
|
||||
"""
|
||||
# only available on WiPy
|
||||
# trans_id = machine.rng() & 0xFFFF
|
||||
# use builtin function to generate random 24 bit integer
|
||||
# trans_id = random.getrandbits(24) & 0xFFFF
|
||||
# use incrementing counter as it's faster
|
||||
trans_id = self.trans_id_ctr
|
||||
self.trans_id_ctr += 1
|
||||
|
||||
mbap_hdr = struct.pack(
|
||||
'>HHHB', trans_id, 0, len(modbus_pdu) + 1, slave_addr)
|
||||
|
||||
return mbap_hdr, trans_id
|
||||
|
||||
def _validate_resp_hdr(self,
|
||||
response: bytearray,
|
||||
trans_id: int,
|
||||
slave_addr: int,
|
||||
function_code: int,
|
||||
count: bool = False) -> bytes:
|
||||
"""
|
||||
Validate the response header.
|
||||
|
||||
:param response: The response
|
||||
:type response: bytearray
|
||||
:param trans_id: The transaction identifier
|
||||
:type trans_id: int
|
||||
:param slave_addr: The slave identifier
|
||||
:type slave_addr: int
|
||||
:param function_code: The function code
|
||||
:type function_code: int
|
||||
:param count: The count
|
||||
:type count: bool
|
||||
|
||||
:returns: Modbus response content
|
||||
:rtype: bytes
|
||||
"""
|
||||
rec_tid, rec_pid, rec_len, rec_uid, rec_fc = struct.unpack(
|
||||
'>HHHBB', response[:Const.MBAP_HDR_LENGTH + 1])
|
||||
|
||||
if (trans_id != rec_tid):
|
||||
raise ValueError('wrong transaction ID')
|
||||
|
||||
if (rec_pid != 0):
|
||||
raise ValueError('invalid protocol ID')
|
||||
|
||||
if (slave_addr != rec_uid):
|
||||
raise ValueError('wrong slave ID')
|
||||
|
||||
if (rec_fc == (function_code + Const.ERROR_BIAS)):
|
||||
raise ValueError('slave returned exception code: {:d}'.
|
||||
format(rec_fc))
|
||||
|
||||
hdr_length = (Const.MBAP_HDR_LENGTH + 2) if count else \
|
||||
(Const.MBAP_HDR_LENGTH + 1)
|
||||
|
||||
return response[hdr_length:]
|
||||
|
||||
def _send_receive(self,
|
||||
slave_addr: int,
|
||||
modbus_pdu: bytes,
|
||||
count: bool) -> bytes:
|
||||
"""
|
||||
Send a modbus message and receive the reponse.
|
||||
|
||||
:param slave_addr: The slave identifier
|
||||
:type slave_addr: int
|
||||
:param modbus_pdu: The modbus PDU
|
||||
:type modbus_pdu: bytes
|
||||
:param count: The count
|
||||
:type count: bool
|
||||
|
||||
:returns: Modbus data
|
||||
:rtype: bytes
|
||||
"""
|
||||
mbap_hdr, trans_id = self._create_mbap_hdr(slave_addr=slave_addr,
|
||||
modbus_pdu=modbus_pdu)
|
||||
self._sock.send(mbap_hdr + modbus_pdu)
|
||||
|
||||
response = self._sock.recv(256)
|
||||
modbus_data = self._validate_resp_hdr(response=response,
|
||||
trans_id=trans_id,
|
||||
slave_addr=slave_addr,
|
||||
function_code=modbus_pdu[0],
|
||||
count=count)
|
||||
|
||||
return modbus_data
|
||||
|
||||
|
||||
class TCPServer(object):
|
||||
"""Modbus TCP host class"""
|
||||
def __init__(self):
|
||||
self._sock = None
|
||||
self._client_sock = None
|
||||
self._is_bound = False
|
||||
|
||||
@property
|
||||
def is_bound(self) -> bool:
|
||||
"""
|
||||
Get the IP and port binding status
|
||||
|
||||
:returns: True if bound to IP and port, False otherwise
|
||||
:rtype: bool
|
||||
"""
|
||||
return self._is_bound
|
||||
|
||||
def get_is_bound(self) -> bool:
|
||||
"""
|
||||
Get the IP and port binding status, legacy support.
|
||||
|
||||
:returns: True if bound to IP and port, False otherwise
|
||||
:rtype: bool
|
||||
"""
|
||||
return self._is_bound
|
||||
|
||||
def bind(self,
|
||||
local_ip: str,
|
||||
local_port: int = 502,
|
||||
max_connections: int = 10):
|
||||
"""
|
||||
Bind IP and port for incomming requests
|
||||
|
||||
:param local_ip: IP of this device listening for requests
|
||||
:type local_ip: str
|
||||
:param local_port: Port of this device
|
||||
:type local_port: int
|
||||
:param max_connections: Number of maximum connections
|
||||
:type max_connections: int
|
||||
"""
|
||||
if self._client_sock:
|
||||
self._client_sock.close()
|
||||
|
||||
if self._sock:
|
||||
self._sock.close()
|
||||
|
||||
self._sock = socket.socket()
|
||||
|
||||
# print(socket.getaddrinfo(local_ip, local_port))
|
||||
# [(2, 1, 0, '192.168.178.47', ('192.168.178.47', 502))]
|
||||
self._sock.bind(socket.getaddrinfo(local_ip, local_port)[0][-1])
|
||||
|
||||
self._sock.listen(max_connections)
|
||||
|
||||
self._is_bound = True
|
||||
|
||||
def _send(self, modbus_pdu: bytes, slave_addr: int) -> None:
|
||||
"""
|
||||
Send Modbus Protocol Data Unit to slave
|
||||
|
||||
:param modbus_pdu: The Modbus Protocol Data Unit
|
||||
:type modbus_pdu: bytes
|
||||
:param slave_addr: The slave address
|
||||
:type slave_addr: int
|
||||
"""
|
||||
size = len(modbus_pdu)
|
||||
fmt = 'B' * size
|
||||
adu = struct.pack('>HHHB' + fmt, self._req_tid, 0, size + 1, slave_addr, *modbus_pdu)
|
||||
self._client_sock.send(adu)
|
||||
|
||||
def send_response(self,
|
||||
slave_addr: int,
|
||||
function_code: int,
|
||||
request_register_addr: int,
|
||||
request_register_qty: int,
|
||||
request_data: list,
|
||||
values: Optional[list] = None,
|
||||
signed: bool = True) -> None:
|
||||
"""
|
||||
Send a response to a client.
|
||||
|
||||
:param slave_addr: The slave address
|
||||
:type slave_addr: int
|
||||
:param function_code: The function code
|
||||
:type function_code: int
|
||||
:param request_register_addr: The request register address
|
||||
:type request_register_addr: int
|
||||
:param request_register_qty: The request register qty
|
||||
:type request_register_qty: int
|
||||
:param request_data: The request data
|
||||
:type request_data: list
|
||||
:param values: The values
|
||||
:type values: Optional[list]
|
||||
:param signed: Indicates if signed
|
||||
:type signed: bool
|
||||
"""
|
||||
modbus_pdu = functions.response(function_code,
|
||||
request_register_addr,
|
||||
request_register_qty,
|
||||
request_data,
|
||||
values,
|
||||
signed)
|
||||
self._send(modbus_pdu, slave_addr)
|
||||
|
||||
def send_exception_response(self,
|
||||
slave_addr: int,
|
||||
function_code: int,
|
||||
exception_code: int) -> None:
|
||||
"""
|
||||
Send an exception response to a client.
|
||||
|
||||
:param slave_addr: The slave address
|
||||
:type slave_addr: int
|
||||
:param function_code: The function code
|
||||
:type function_code: int
|
||||
:param exception_code: The exception code
|
||||
:type exception_code: int
|
||||
"""
|
||||
modbus_pdu = functions.exception_response(function_code,
|
||||
exception_code)
|
||||
self._send(modbus_pdu, slave_addr)
|
||||
|
||||
def _accept_request(self,
|
||||
accept_timeout: float,
|
||||
unit_addr_list: list) -> Union[Request, None]:
|
||||
"""
|
||||
Accept, read and decode a socket based request
|
||||
|
||||
:param accept_timeout: The socket accept timeout
|
||||
:type accept_timeout: float
|
||||
:param unit_addr_list: The unit address list
|
||||
:type unit_addr_list: list
|
||||
"""
|
||||
self._sock.settimeout(accept_timeout)
|
||||
new_client_sock = None
|
||||
|
||||
try:
|
||||
new_client_sock, client_address = self._sock.accept()
|
||||
except OSError as e:
|
||||
if e.args[0] != 110: # 110 = timeout expired
|
||||
raise e
|
||||
|
||||
if new_client_sock is not None:
|
||||
if self._client_sock is not None:
|
||||
self._client_sock.close()
|
||||
|
||||
self._client_sock = new_client_sock
|
||||
|
||||
# recv() timeout, setting to 0 might lead to the following error
|
||||
# "Modbus request error: [Errno 11] EAGAIN"
|
||||
# This is a socket timeout error
|
||||
self._client_sock.settimeout(0.5)
|
||||
|
||||
if self._client_sock is not None:
|
||||
try:
|
||||
req = self._client_sock.recv(128)
|
||||
|
||||
if len(req) == 0:
|
||||
return None
|
||||
|
||||
req_header_no_uid = req[:Const.MBAP_HDR_LENGTH - 1]
|
||||
self._req_tid, req_pid, req_len = struct.unpack('>HHH', req_header_no_uid)
|
||||
req_uid_and_pdu = req[Const.MBAP_HDR_LENGTH - 1:Const.MBAP_HDR_LENGTH + req_len - 1]
|
||||
except OSError:
|
||||
# MicroPython raises an OSError instead of socket.timeout
|
||||
# print("Socket OSError aka TimeoutError: {}".format(e))
|
||||
return None
|
||||
except Exception:
|
||||
# print("Modbus request error:", e)
|
||||
self._client_sock.close()
|
||||
self._client_sock = None
|
||||
return None
|
||||
|
||||
if (req_pid != 0):
|
||||
# print("Modbus request error: PID not 0")
|
||||
self._client_sock.close()
|
||||
self._client_sock = None
|
||||
return None
|
||||
|
||||
if ((unit_addr_list is not None) and (req_uid_and_pdu[0] not in unit_addr_list)):
|
||||
return None
|
||||
|
||||
try:
|
||||
return Request(self, req_uid_and_pdu)
|
||||
except ModbusException as e:
|
||||
self.send_exception_response(req[0],
|
||||
e.function_code,
|
||||
e.exception_code)
|
||||
return None
|
||||
|
||||
def get_request(self,
|
||||
unit_addr_list: Optional[list] = None,
|
||||
timeout: int = None) -> Union[Request, None]:
|
||||
"""
|
||||
Check for request within the specified timeout
|
||||
|
||||
:param unit_addr_list: The unit address list
|
||||
:type unit_addr_list: Optional[list]
|
||||
:param timeout: The timeout
|
||||
:type timeout: int
|
||||
|
||||
:returns: A request object or None.
|
||||
:rtype: Union[Request, None]
|
||||
|
||||
:raises Exception: If no socket is configured and bound
|
||||
"""
|
||||
if self._sock is None:
|
||||
raise Exception('Modbus TCP server not bound')
|
||||
|
||||
if timeout > 0:
|
||||
start_ms = time.ticks_ms()
|
||||
elapsed = 0
|
||||
while True:
|
||||
if self._client_sock is None:
|
||||
accept_timeout = None if timeout is None else (timeout - elapsed) / 1000
|
||||
else:
|
||||
accept_timeout = 0
|
||||
req = self._accept_request(accept_timeout, unit_addr_list)
|
||||
if req:
|
||||
return req
|
||||
elapsed = time.ticks_diff(start_ms, time.ticks_ms())
|
||||
if elapsed > timeout:
|
||||
return None
|
||||
else:
|
||||
return self._accept_request(0, unit_addr_list)
|
||||
@@ -0,0 +1,212 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: UTF-8 -*-
|
||||
|
||||
"""
|
||||
Fake classes of typing module.
|
||||
|
||||
https://github.com/micropython/micropython-lib/issues/190
|
||||
|
||||
https://github.com/micropython/micropython-lib/blob/3d779b8ceab5b65b9f70accbcbb15ab3509eceb7/typing/typing.py
|
||||
"""
|
||||
|
||||
|
||||
class _Subscriptable():
|
||||
def __getitem__(self, item):
|
||||
return None
|
||||
|
||||
|
||||
_subscriptable = _Subscriptable()
|
||||
|
||||
|
||||
class Any:
|
||||
pass
|
||||
|
||||
|
||||
class NoReturn:
|
||||
pass
|
||||
|
||||
|
||||
class ClassVar:
|
||||
pass
|
||||
|
||||
|
||||
Union = _subscriptable
|
||||
|
||||
|
||||
Optional = _subscriptable
|
||||
|
||||
|
||||
class Generic:
|
||||
pass
|
||||
|
||||
|
||||
class NamedTuple:
|
||||
pass
|
||||
|
||||
|
||||
class Hashable:
|
||||
pass
|
||||
|
||||
|
||||
class Awaitable:
|
||||
pass
|
||||
|
||||
|
||||
class Coroutine:
|
||||
pass
|
||||
|
||||
|
||||
class AsyncIterable:
|
||||
pass
|
||||
|
||||
|
||||
class AsyncIterator:
|
||||
pass
|
||||
|
||||
|
||||
class Iterable:
|
||||
pass
|
||||
|
||||
|
||||
class Iterator:
|
||||
pass
|
||||
|
||||
|
||||
class Reversible:
|
||||
pass
|
||||
|
||||
|
||||
class Sized:
|
||||
pass
|
||||
|
||||
|
||||
class Container:
|
||||
pass
|
||||
|
||||
|
||||
class Collection:
|
||||
pass
|
||||
|
||||
|
||||
# class Callable:
|
||||
# pass
|
||||
Callable = _subscriptable
|
||||
|
||||
|
||||
class AbstractSet:
|
||||
pass
|
||||
|
||||
|
||||
class MutableSet:
|
||||
pass
|
||||
|
||||
|
||||
class Mapping:
|
||||
pass
|
||||
|
||||
|
||||
class MutableMapping:
|
||||
pass
|
||||
|
||||
|
||||
class Sequence:
|
||||
pass
|
||||
|
||||
|
||||
class MutableSequence:
|
||||
pass
|
||||
|
||||
|
||||
class ByteString:
|
||||
pass
|
||||
|
||||
|
||||
Tuple = _subscriptable
|
||||
|
||||
|
||||
List = _subscriptable
|
||||
|
||||
|
||||
class Deque:
|
||||
pass
|
||||
|
||||
|
||||
class Set:
|
||||
pass
|
||||
|
||||
|
||||
class dict_keys:
|
||||
pass
|
||||
|
||||
|
||||
class FrozenSet:
|
||||
pass
|
||||
|
||||
|
||||
class MappingView:
|
||||
pass
|
||||
|
||||
|
||||
class KeysView:
|
||||
pass
|
||||
|
||||
|
||||
class ItemsView:
|
||||
pass
|
||||
|
||||
|
||||
class ValuesView:
|
||||
pass
|
||||
|
||||
|
||||
class ContextManager:
|
||||
pass
|
||||
|
||||
|
||||
class AsyncContextManager:
|
||||
pass
|
||||
|
||||
|
||||
Dict = _subscriptable
|
||||
|
||||
|
||||
class DefaultDict:
|
||||
pass
|
||||
|
||||
|
||||
class Counter:
|
||||
pass
|
||||
|
||||
|
||||
class ChainMap:
|
||||
pass
|
||||
|
||||
|
||||
class Generator:
|
||||
pass
|
||||
|
||||
|
||||
class AsyncGenerator:
|
||||
pass
|
||||
|
||||
|
||||
class Type:
|
||||
pass
|
||||
|
||||
|
||||
def cast(typ, val):
|
||||
return val
|
||||
|
||||
|
||||
def _overload_dummy(*args, **kwds):
|
||||
"""Helper for @overload to raise when called."""
|
||||
raise NotImplementedError(
|
||||
"You should not call an overloaded function. "
|
||||
"A series of @overload-decorated functions "
|
||||
"outside a stub module should always be followed "
|
||||
"by an implementation that is not @overload-ed."
|
||||
)
|
||||
|
||||
|
||||
def overload():
|
||||
return _overload_dummy
|
||||
@@ -0,0 +1,5 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: UTF-8 -*-
|
||||
|
||||
__version_info__ = ("2", "3", "7")
|
||||
__version__ = '.'.join(__version_info__)
|
||||
Reference in New Issue
Block a user