""" Copyright (C) 2018 SunSpec Alliance Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ import socket import struct import time PARITY_NONE = 'N' PARITY_EVEN = 'E' REQ_COUNT_MAX = 125 REQ_WRITE_COUNT_MAX = 123 FUNC_READ_HOLDING = 3 FUNC_READ_INPUT = 4 FUNC_WRITE_MULTIPLE = 16 FUNC_WRITE_SINGLE = 6 TEST_NAME = 'test_name' modbus_rtu_clients = {} TCP_HDR_LEN = 6 TCP_RESP_MIN_LEN = 3 TCP_HDR_O_LEN = 4 TCP_READ_REQ_LEN = 6 TCP_WRITE_MULT_REQ_LEN = 7 TCP_WRITE_SINGLE_REQ_LEN = 4 TCP_DEFAULT_PORT = 502 TCP_DEFAULT_TIMEOUT = 2 class ModbusClientError(Exception): pass class ModbusClientTimeout(ModbusClientError): pass class ModbusClientException(ModbusClientError): pass def __generate_crc16_table(): ''' Generates a crc16 lookup table .. note:: This will only be generated once ''' result = [] for byte in range(256): crc = 0x0000 for bit in range(8): if (byte ^ crc) & 0x0001: crc = (crc >> 1) ^ 0xa001 else: crc >>= 1 byte >>= 1 result.append(crc) return result __crc16_table = __generate_crc16_table() def computeCRC(data): ''' Computes a crc16 on the passed in string. For modbus, this is only used on the binary serial protocols (in this case RTU). The difference between modbus's crc16 and a normal crc16 is that modbus starts the crc value out at 0xffff. :param data: The data to create a crc16 of :returns: The calculated CRC ''' crc = 0xffff for a in data: idx = __crc16_table[(crc ^ a) & 0xff]; crc = ((crc >> 8) & 0xff) ^ idx swapped = ((crc << 8) & 0xff00) | ((crc >> 8) & 0x00ff) return swapped def checkCRC(data, check): ''' Checks if the data matches the passed in CRC :param data: The data to create a crc16 of :param check: The CRC to validate :returns: True if matched, False otherwise ''' return computeCRC(data) == check class ModbusClientTCP: def __init__(self, slave_id=1, ipaddr='127.0.0.1', ipport=502, timeout=None, ctx=None, trace_func=None, max_count=REQ_COUNT_MAX, max_write_count=REQ_WRITE_COUNT_MAX): self.slave_id = slave_id self.ipaddr = ipaddr self.ipport = ipport self.timeout = timeout self.ctx = ctx self.socket = None self.trace_func = trace_func self.max_count = max_count self.max_write_count = max_write_count if ipport is None: self.ipport = TCP_DEFAULT_PORT if timeout is None: self.timeout = TCP_DEFAULT_TIMEOUT def close(self): self.disconnect() def connect(self, timeout=None): """Connect to TCP destination. Parameters: timeout : Connection timeout in seconds. """ if self.socket: self.disconnect() if timeout is None: timeout = self.timeout try: self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.settimeout(timeout) self.socket.connect((self.ipaddr, self.ipport)) except Exception as e: raise ModbusClientError('Connection error: %s' % str(e)) def disconnect(self): """Disconnect from TCP destination. """ try: if self.socket: self.socket.close() self.socket = None except Exception: pass def is_connected(self): return self.socket def _read(self, addr, count, op=FUNC_READ_HOLDING): resp = bytearray() len_remaining = TCP_HDR_LEN + TCP_RESP_MIN_LEN len_found = False except_code = None req = struct.pack('>HHHBBHH', 0, 0, TCP_READ_REQ_LEN, int(self.slave_id), op, int(addr), int(count)) if self.trace_func: # s = '%s:%s:%s[addr=%s] ->' % (self.ipaddr, str(self.ipport), str(self.slave_id), addr) s = '> ' for c in req: s += '%02X' % c self.trace_func(s) try: self.socket.sendall(req) except Exception as e: raise ModbusClientError('Socket write error: %s' % str(e)) while len_remaining > 0: c = self.socket.recv(len_remaining) len_read = len(c) if len_read > 0: resp += c len_remaining -= len_read if len_found is False and len(resp) >= TCP_HDR_LEN + TCP_RESP_MIN_LEN: data_len = struct.unpack('>H', resp[TCP_HDR_O_LEN:TCP_HDR_O_LEN + 2]) len_remaining = data_len[0] - (len(resp) - TCP_HDR_LEN) else: raise ModbusClientTimeout('Response timeout') if resp[TCP_HDR_LEN + 1] & 0x80: except_code = resp[TCP_HDR_LEN + 2] if self.trace_func: # s = '%s:%s:%s[addr=%s] <--' % (self.ipaddr, str(self.ipport), str(self.slave_id), addr) s ='< ' for c in resp: s += '%02X' % c self.trace_func(s) if except_code: raise ModbusClientException('Modbus exception %d: addr: %s count: %s' % (except_code, addr, count)) return resp[(TCP_HDR_LEN + 3):] def read(self, addr, count, op=FUNC_READ_HOLDING): """ Read Modbus device registers. If no connection exists to the destination, one is created and disconnected at the end of the request. Parameters: addr : Starting Modbus address. count : Read length in Modbus registers. op : Modbus function code for request. Returns: Byte string containing register contents. """ resp = bytearray() read_offset = 0 local_connect = False if self.socket is None: local_connect = True self.connect(self.timeout) try: while count > 0: if count > self.max_count: read_count = self.max_count else: read_count = count data = self._read(addr + read_offset, read_count, op=op) if data: resp += data count -= read_count read_offset += read_count else: break except socket.timeout as e: raise ModbusClientTimeout(str(e)) finally: if local_connect: self.disconnect() return bytes(resp) def _write(self, addr, data): resp = bytearray() len_remaining = TCP_HDR_LEN + TCP_RESP_MIN_LEN len_found = False except_code = None func = FUNC_WRITE_MULTIPLE write_len = len(data) write_count = int(write_len/2) req = struct.pack('>HHHBBHHB', 0, 0, TCP_WRITE_MULT_REQ_LEN + write_len, int(self.slave_id), func, int(addr), write_count, write_len) req += data if self.trace_func: # s = '%s:%s:%s[addr=%s] ->' % (self.ipaddr, str(self.ipport), str(self.slave_id), addr) s = '> ' for c in req: s += '%02X' % c self.trace_func(s) try: self.socket.sendall(req) except Exception as e: raise ModbusClientError('Socket write error: %s' % str(e)) while len_remaining > 0: c = self.socket.recv(len_remaining) len_read = len(c) if len_read > 0: resp += c len_remaining -= len_read if len_found is False and len(resp) >= TCP_HDR_LEN + TCP_RESP_MIN_LEN: data_len = struct.unpack('>H', resp[TCP_HDR_O_LEN:TCP_HDR_O_LEN + 2]) len_remaining = data_len[0] - (len(resp) - TCP_HDR_LEN) else: raise ModbusClientTimeout('Response timeout') if (resp[TCP_HDR_LEN + 1]) & 0x80: except_code = resp[TCP_HDR_LEN + 2] if self.trace_func: # s = '%s:%s:%s[addr=%s] <--' % (self.ipaddr, str(self.ipport), str(self.slave_id), addr) s = '< ' for c in resp: s += '%02X' % c self.trace_func(s) if except_code: raise ModbusClientException('Modbus exception: %d' % except_code) def _write_single(self, addr, data): """ Write Single Modbus device register """ resp = bytearray() len_remaining = TCP_HDR_LEN + TCP_RESP_MIN_LEN len_found = False except_code = None func = FUNC_WRITE_SINGLE write_len = len(data) req = struct.pack('>HHHBBH', 0, 0, TCP_WRITE_SINGLE_REQ_LEN + write_len, int(self.slave_id), func, int(addr)) req += data if self.trace_func: # s = '%s:%s:%s[addr=%s] ->' % (self.ipaddr, str(self.ipport), str(self.slave_id), addr) s = '> ' for c in req: s += '%02X' % c self.trace_func(s) try: self.socket.sendall(req) except Exception as e: raise ModbusClientError('Socket write error: %s' % str(e)) while len_remaining > 0: c = self.socket.recv(len_remaining) len_read = len(c) if len_read > 0: resp += c len_remaining -= len_read if len_found is False and len(resp) >= TCP_HDR_LEN + TCP_RESP_MIN_LEN: data_len = struct.unpack('>H', resp[TCP_HDR_O_LEN:TCP_HDR_O_LEN + 2]) len_remaining = data_len[0] - (len(resp) - TCP_HDR_LEN) else: raise ModbusClientTimeout('Response timeout') if (resp[TCP_HDR_LEN + 1]) & 0x80: except_code = resp[TCP_HDR_LEN + 2] if self.trace_func: # s = '%s:%s:%s[addr=%s] <--' % (self.ipaddr, str(self.ipport), str(self.slave_id), addr) s = '< ' for c in resp: s += '%02X' % c self.trace_func(s) if except_code: raise ModbusClientException('Modbus exception: %d' % except_code) def write(self, addr, data): """ Write Modbus device registers. If no connection exists to the destination, one is created and disconnected at the end of the request. Parameters: addr : Starting Modbus address. data : Byte string containing register contents. """ write_offset = 0 local_connect = False count = len(data)/2 if self.socket is None: local_connect = True self.connect(self.timeout) try: if count == 1: self._write_single(addr, data) # If only one register, use Func Code 0x06 else: while count > 0: if count > self.max_write_count: write_count = self.max_write_count else: write_count = count start = write_offset * 2 end = int((write_offset + write_count) * 2) self._write(addr + write_offset, data[start:end]) count -= write_count write_offset += write_count finally: if local_connect: self.disconnect()