Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def testSyncTcpClientInstantiation(self):
client = ModbusTcpClient()
self.assertNotEqual(client, None)
def testBasicSyncTcpClient(self, mock_select):
''' Test the basic methods for the tcp sync client'''
# receive/send
mock_select.select.return_value = [True]
client = ModbusTcpClient()
client.socket = mockSocket()
self.assertEqual(0, client._send(None))
self.assertEqual(1, client._send(b'\x00'))
self.assertEqual(b'\x00', client._recv(1))
# connect/disconnect
self.assertTrue(client.connect())
client.close()
# already closed socket
client.socket = False
client.close()
self.assertEqual("ModbusTcpClient(127.0.0.1:502)", str(client))
def testTcpClientRegister(self):
class CustomeRequest:
function_code = 79
client = ModbusTcpClient()
client.framer = Mock()
client.register(CustomeRequest)
assert client.framer.decoder.register.called_once_with(CustomeRequest)
# -----------------------------------------------------------------------#
#!/usr/bin/env python
from pymodbus.client.sync import ModbusTcpClient
import dweepy
import config
client = ModbusTcpClient(config.inverter_ip, timeout=3, port=502)
client.connect()
slave = 0x01
inverter = {}
modmap = {"5008": "internal_temp_10",
"5011": "pv1_voltage_10",
"5012": "pv1_current_10",
"5013": "pv2_voltage_10",
"5014": "pv1_current_10",
"5017": "total_pv_power",
"5019": "grid_voltage_10",
"5022": "inverter_current_10",
"5031": "consumption?",
"5036": "grid_frequency_10",
"13003": "total_pv_energy",
def set_point_sync(self, point_name, value):
register = self.point_map[point_name]
client = SyncModbusClient(self.ip_address, port=self.port)
result = None
try:
result = register.set_state_sync(client, value)
except (ConnectionException, ModbusIOException, ModbusInterfaceException):
result = None
finally:
client.close()
return result
stopbits=self.stopbits,
retry_on_empty=True,
timeout=self.timeout)
elif self.type == 3: # TCP
from pymodbus.client.sync import ModbusTcpClient
try:
self.master = ModbusTcpClient(
host=self.host,
port=self.port,
retry_on_empty=True,
retries=1,
timeout=0.9, #self.timeout
)
self.readRetries = 0
except:
self.master = ModbusTcpClient(
host=self.host,
port=self.port,
)
elif self.type == 4: # UDP
from pymodbus.client.sync import ModbusUdpClient
try:
self.master = ModbusUdpClient(
host=self.host,
port=self.port,
retry_on_empty=True,
retries=3,
timeout=0.7, #self.timeout
)
except: # older versions of pymodbus don't support the retries, timeout nor the retry_on_empty arguments
self.master = ModbusUdpClient(
host=self.host,
self._timeout = ( Defaults.Timeout
if ( timeout is True or timeout == 0 )
else timeout )
def __enter__( self ):
self._lock.acquire( True )
logging.debug( "Acquired lock on %r", self )
return self
def __exit__( self, typ, val, tbk ):
logging.debug( "Release lock on %r", self )
self._lock.release()
return False
class modbus_client_tcp( modbus_client_timeout, ModbusTcpClient ):
"""A ModbusTcpClient with transaction timeouts."""
def connect( self ):
"""Duplicate the functionality of connect (handling optional .source_address attribute added
in pymodbus 1.2.0), but pass the computed remaining timeout.
"""
if self.socket: return True
logging.debug( "Connecting to (%s, %s)", getattr( self, 'host', '(serial)' ), self.port )
begun = misc.timer()
timeout = self.timeout # This computes the remaining timeout available
try:
self.socket = socket.create_connection( (self.host, self.port),
timeout=timeout, source_address=getattr( self, 'source_address', None ))
except socket.error as exc:
logging.debug('Connection to (%s, %s) failed: %s' % (
self.host, self.port, exc ))
def start_monitor():
global monitor_active
global mb_client
if (monitor_active != True):
monitor_active = True
mb_client = ModbusTcpClient('127.0.0.1')
modbus_monitor()
help='list of int values', type=int,
choices=range(0, 65536), nargs='+',
default=0)
parser.add_argument('-c', dest='coil',
help='list of 0 (False) or 1 (True) int values', type=int, nargs='+',
default=0, choices=[0, 1]) # argparse does not manage bool well
args = parser.parse_args()
# import logging
# logging.basicConfig()
# log = logging.getLogger()
# log.setLevel(logging.DEBUG)
# TODO: check retries, and other options
client = ModbusClient(args.ip, port=args.port)
# retries=3, retry_on_empty=True)
client.connect()
# TODO: check if asserts are slowing down read/write
if args.mode == 'w':
# NOTE: write_register
if args.type == 'HR':
if args.count == 1:
hr_write = client.write_register(args.offset, args.register[0])
assert(hr_write.function_code < 0x80)
else:
hrs_write = client.write_registers(args.offset, args.register)
assert(hrs_write.function_code < 0x80)
#!/usr/bin/python
import sys
import os
import time
import getopt
import socket
import ConfigParser
import struct
import binascii
import logging
from pymodbus.payload import BinaryPayloadDecoder
from pymodbus.constants import Endian
from pymodbus.client.sync import ModbusTcpClient
client = ModbusTcpClient('192.168.193.125', port=8899)
sdmid = int(85)
time.sleep(0.1)
resp = client.read_holding_registers(0x0006,4, unit=sdmid)
decoder = BinaryPayloadDecoder.fromRegisters(resp.registers,byteorder=Endian.Big,wordorder=Endian.Big)
gridw = int(decoder.decode_32bit_int())
f = open('/var/www/html/openWB/ramdisk/wattbezug', 'w')
f.write(str(gridw))
f.close()
resp = client.read_holding_registers(0x0008,4, unit=sdmid)
decoder = BinaryPayloadDecoder.fromRegisters(resp.registers,byteorder=Endian.Big,wordorder=Endian.Big)
einspwh = int(decoder.decode_32bit_int()) * 10
#print('grideinwh'+str(einspwh))
f = open('/var/www/html/openWB/ramdisk/einspeisungkwh', 'w')
f.write(str(einspwh))