本文整理汇总了Python中pymodbus.client.sync.ModbusTcpClient.read_discrete_inputs方法的典型用法代码示例。如果您正苦于以下问题:Python ModbusTcpClient.read_discrete_inputs方法的具体用法?Python ModbusTcpClient.read_discrete_inputs怎么用?Python ModbusTcpClient.read_discrete_inputs使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pymodbus.client.sync.ModbusTcpClient
的用法示例。
在下文中一共展示了ModbusTcpClient.read_discrete_inputs方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: readMBinputs
# 需要导入模块: from pymodbus.client.sync import ModbusTcpClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusTcpClient import read_discrete_inputs [as 别名]
def readMBinputs(clientIP, coil, number=1):
from pymodbus.client.sync import ModbusTcpClient, ConnectionException
client = ModbusTcpClient(clientIP)
values = []
try:
rawresult = client.read_discrete_inputs(coil, number)
except ConnectionException:
# print('we were unable to connect to the host')
statuscode = 7
else:
# print(rawresult)
try:
resultregisters = rawresult.bits[0:number]
except AttributeError:
statuscode = rawresult.exception_code
else:
statuscode = 0
values = resultregisters
client.close()
result = {'message': messagefrommbstatuscode(statuscode), 'statuscode': statuscode, 'values':values}
return result
示例2: server
# 需要导入模块: from pymodbus.client.sync import ModbusTcpClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusTcpClient import read_discrete_inputs [as 别名]
# blocks for the two sets, so a change to one is a change to the other.
# Keep both of these cases in mind when testing as the following will
# _only_ pass with the supplied async modbus server (script supplied).
#---------------------------------------------------------------------------#
rq = client.write_coil(1, True)
rr = client.read_coils(1,1)
assert(rq.function_code < 0x80) # test that we are not an error
assert(rr.bits[0] == True) # test the expected value
rq = client.write_coils(1, [True]*8)
rr = client.read_coils(1,8)
assert(rq.function_code < 0x80) # test that we are not an error
assert(rr.bits == [True]*8) # test the expected value
rq = client.write_coils(1, [False]*8)
rr = client.read_discrete_inputs(1,8)
assert(rq.function_code < 0x80) # test that we are not an error
assert(rr.bits == [True]*8) # test the expected value
rq = client.write_register(1, 10)
rr = client.read_holding_registers(1,1)
assert(rq.function_code < 0x80) # test that we are not an error
assert(rr.registers[0] == 10) # test the expected value
rq = client.write_registers(1, [10]*8)
rr = client.read_input_registers(1,8)
assert(rq.function_code < 0x80) # test that we are not an error
assert(rr.registers == [17]*8) # test the expected value
arguments = {
'read_address': 1,
示例3: dataValidation
# 需要导入模块: from pymodbus.client.sync import ModbusTcpClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusTcpClient import read_discrete_inputs [as 别名]
#.........这里部分代码省略.........
logger.debug('difference is: %.2f' % (start_test_data['cell_temp'] - current_data['cell_temp']))
except KeyError:
logger.error('ENV data unavailable')
# MBS-1 data
try:
mbs_data = []
for i in range(1, 11):
mbs_data.append(device_data['alpha']['mbs1']['MBS-1']['value%02d' % (i)])
logger.debug('%s data: %s' % (device_data['alpha']['mbs1']['MBS-1']['identifier'], mbs_data))
# for i in range(1, 11):
# logger.debug('%s data: %s' % (device_data['alpha']['mbs1']['MBS-1']['identifier'], device_data['alpha']['mbs1']['MBS-1']['value%02d' % (i)]))
if self.testrunning:
# check modbus data
if checkModbusData('MBS-1', device_data['alpha']['mbs1']['MBS-1']):
logger.info('MBS-1: Modbus Data VALID')
else:
logger.error('MBS-1: Modbus Data INVALID')
except KeyError:
logger.error('MBS-1 data unavailable')
# MBS-2 data
try:
mbs_data = []
for i in range(1, 11):
mbs_data.append(device_data['alpha']['mbs2']['MBS-2']['value%02d' % (i)])
logger.debug('%s data: %s' % (device_data['alpha']['mbs2']['MBS-2']['identifier'], mbs_data))
# for i in range(1, 11):
# logger.debug('%s data: %s' % (device_data['alpha']['mbs2']['MBS-2']['identifier'], device_data['alpha']['mbs2']['MBS-2']['value%02d' % (i)]))
if self.testrunning:
if checkModbusData('MBS-2', device_data['alpha']['mbs2']['MBS-2']):
logger.info('MBS-2: Modbus Data VALID')
else:
logger.error('MBS-2: Modbus Data INVALID')
except KeyError:
logger.error('MBS-2 data unavailable')
#sixnet data
try:
# try:
if not self.modbusclient.connect():
logger.error('failing to connect to sixnet Ethernet switch for Modbus query')
sixnet_link_status = self.modbusclient.read_discrete_inputs(0, 8, unit=11)
sixnet_pwr_status = self.modbusclient.read_discrete_inputs(29, 3, unit=11)
if self.begintest:
start_test_data['link_bits'] = sixnet_link_status.bits
start_test_data['status_bits'] = sixnet_pwr_status.bits
if self.testrunning:
logger.debug('prev_link_bits: %s' % (start_test_data['link_bits']))
logger.debug('prev_status_bits: %s' % (start_test_data['status_bits']))
logger.debug('curr_link_bits: %s' % (sixnet_link_status.bits))
logger.debug('curr_status_bits: %s' % (sixnet_pwr_status.bits))
if self.testrunning:
if start_test_data['link_bits'] != sixnet_link_status.bits:
logger.error('sixnet "link" status has changed')
elif start_test_data['status_bits'] != sixnet_pwr_status.bits:
logger.error('sixnet "OK" status has changed')
else:
logger.info('sixnet switch status is good')
# except KeyError:
# logger.error('sixnet data unavailable')
except pymodbus.exceptions.ConnectionException:
logger.error('Sixnet Modbus query failed')
if self.begintest:
self.begintest = False
self.testrunning = True
time.sleep(5)
os.system('clear')
self.modbusclient.close()
def join(self, timeout=None):
if self.testrunning:
logger.info('Stopping Test...')
self.testrunning = False
self.stoprequest.set()
super(dataValidation, self).join(timeout)
def starttest(self, timeout=None):
self.begintest = True
def stoptest(self, timeout=None):
self.testrunning = False
示例4: clientthreads
# 需要导入模块: from pymodbus.client.sync import ModbusTcpClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusTcpClient import read_discrete_inputs [as 别名]
class clientthreads(threading.Thread):
def __init__(self, vnic, ipaddr, port):
threading.Thread.__init__(self)
self.ipaddr = ipaddr # ip address
self.port = port # port address
self.vnic = vnic # virtual nic
self.mode = "" # server or client
self.state = "" # up or down
self.dest = "" # destination address for client
self.clientstop = threading.Event()
self.server = ""
self.client = ""
self.framer = ""
self.vnicm = ""
self.runtime= 0
self.delayr = random.uniform(0,5)
self.delayw = random.uniform(0,60)
self.firstdelay = 0
self.pstart= ""
def run(self):
self.client = ModbusTcpClient(self.dest, self.port, source_address=(self.ipaddr, 0), retries=1, retry_on_empty=True)
if(self.mode=="read"):
self.clientintr()
elif(self.mode=="write"):
self.clientintw()
else:
print "wrong mode specified"
def clientintr(self): # instantiate server stuff
while(not self.clientstop.is_set()):
if(time.time() - self.pstart > self.runtime):
print "stopping"
break
if(self.firstdelay < 1):
print "Start RDelay is: " + str(self.delayr)
time.sleep(self.delayr)
self.firstdelay = 1
print "Starting Reads"
self.clientreads()
print "\n\r-----read-----\n\r"
print self.dest
print time.time() - self.pstart
print "------------------\n\r"
def clientintw(self): # instantiate server stuff
while(not self.clientstop.is_set()):
if(time.time() - self.pstart > self.runtime):
print "stopping"
break
if(self.firstdelay < 1):
print "Start WDelay is: " + str(self.delayw)
time.sleep(self.delayw)
self.firstdelay = 1
print "Starting Writes"
self.clientwrites()
print "\n\r-----write----\n\r"
print self.dest
print time.time() - self.pstart
print "------------------\n\r"
def clientreads(self):
self.client.read_coils(1, 10)
self.client.read_discrete_inputs(1, 10)
self.client.read_holding_registers(1, 10)
self.client.read_input_registers(1, 10)
time.sleep(5)
def clientwrites(self):
self.client.write_coil(1, True)
self.client.write_register(1, 3)
self.client.write_coils(1, [True]*10)
self.client.write_registers(1, [3]*10)
time.sleep(60)
def alloc(self): # Allocate ip address
if (validateIP(self.ipaddr, self.vnicm)):
cmdargs = [self.vnic, self.ipaddr]
subprocess.call(["ifconfig"] + cmdargs)
else:
return 0
def dealloc(self): # De-allocate ip address
cmdargs = [self.vnic]
subprocess.call(["ifconfig"] + cmdargs + ["down"])
def stop(self):
self.clientstop.set()
return
示例5: assert
# 需要导入模块: from pymodbus.client.sync import ModbusTcpClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusTcpClient import read_discrete_inputs [as 别名]
if args.type == 'HR':
hr_read = client.read_holding_registers(args.offset,
count=args.count)
assert(hr_read.function_code < 0x80)
print(hr_read.registers[0:args.count])
# NOTE: read_holding_registers
elif args.type == 'IR':
ir_read = client.read_input_registers(args.offset,
count=args.count)
assert(ir_read.function_code < 0x80)
print(ir_read.registers[0:args.count])
# NOTE: read_discrete_inputs
elif args.type == 'DI':
di_read = client.read_discrete_inputs(args.offset,
count=args.count)
assert(di_read.function_code < 0x80)
print(di_read.bits)
# NOTE: read_discrete_inputs
elif args.type == 'CO':
co_read = client.read_coils(args.offset,
count=args.count)
assert(co_read.function_code < 0x80)
print(co_read.bits)
client.close()
示例6: assert
# 需要导入模块: from pymodbus.client.sync import ModbusTcpClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusTcpClient import read_discrete_inputs [as 别名]
# If the returned output quantity is not a multiple of eight,
# the remaining bits in the final data byte will be padded with zeros
# (toward the high order end of the byte).
resp.extend([False]*3)
assert(rr.bits == resp) # test the expected value
log.debug("Write to multiple coils and read back - test 2")
rq = client.write_coils(1, [False]*8, unit=1)
rr = client.read_coils(1, 8, unit=1)
assert(rq.function_code < 0x80) # test that we are not an error
assert(rr.bits == [False]*8) # test the expected value
log.debug("Read discrete inputs")
rr = client.read_discrete_inputs(0, 8, unit=1)
assert(rq.function_code < 0x80) # test that we are not an error
log.debug("Write to a holding register and read back")
rq = client.write_register(1, 10, unit=1)
rr = client.read_holding_registers(1, 1, unit=1)
assert(rq.function_code < 0x80) # test that we are not an error
assert(rr.registers[0] == 10) # test the expected value
log.debug("Write to multiple holding registers and read back")
rq = client.write_registers(1, [10]*8, unit=1)
rr = client.read_holding_registers(1, 8, unit=1)
assert(rq.function_code < 0x80) # test that we are not an error
assert(rr.registers == [10]*8) # test the expected value
log.debug("Read input registers")
示例7: youbot_modbus_server_service
# 需要导入模块: from pymodbus.client.sync import ModbusTcpClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusTcpClient import read_discrete_inputs [as 别名]
def youbot_modbus_server_service():
global station_states, button_states, modbus_data_validity
connection_error_count = 0
rospy.init_node('youbot_modbus_server')
# Grab all of the parameters from the launch file
mb_server_ip = rospy.get_param("~modbus_server_ip")
mb_server_port = rospy.get_param("~modbus_server_port")
mb_station_status_topic = rospy.get_param("~station_status_topic")
mb_button_status_topic = rospy.get_param("~button_status_topic")
plc_polling_rate = rospy.Rate(rospy.get_param("~plc_polling_rate_hz"))
# Update the array sizes
station_states = [False] * plc_num_stations
button_states = [False] * (plc_num_buttons * 2)
# Create two services for nodes to call and get current sensor & button states
s = rospy.Service(mb_station_status_topic, YoubotModbusSensorMsg, handle_station_request)
t = rospy.Service(mb_button_status_topic, YoubotModbusButtonMsg, handle_button_request)
# Attempt to connect to the PLC Modbus server
try:
# Connect to the Modbus Server
client = ModbusClient(mb_server_ip, mb_server_port)
if client.connect() == False:
raise
# We failed to connect to the PLC Modbus server. Report error and shutdown.
except:
except_desc = "Could not initiate connection with Modbus server"
rospy.logerr(except_desc)
rospy.signal_shutdown(except_desc)
# We suceeded, so report the connection and continue
else:
rospy.loginfo("Youbot Modbus service successfully connected to: " + str(mb_server_ip) + ":" + str(mb_server_port))
rospy.loginfo("Awaiting ROS service calls...")
# Main loop for polling the Modbus Server on the PLC - plc_polling_rate param is in launch file
while not rospy.is_shutdown():
# Request data from the PLC Modbus server
try:
# Get the current station values (every two values is a ball/done pair)
returned_station_states = client.read_discrete_inputs(0x8000, plc_num_stations*2)
# Get the current button values (every two values is a button/indicator pair) (buttons follow stations in PLC addresses)
returned_button_states = client.read_discrete_inputs((0x8000+(plc_num_stations*2)), plc_num_buttons*2)
# Raise an exception if the server did not respond with the message type we were expecting
if type(returned_station_states) != bit_read_message.ReadDiscreteInputsResponse or \
type(returned_button_states ) != bit_read_message.ReadDiscreteInputsResponse:
raise
# If the data was invalid on a previous iteration, we need to report the transition
if modbus_data_validity == False:
connection_error_count = 0
modbus_data_validity = True
rospy.loginfo("PLC communication has been restored. Data validity: " + str(modbus_data_validity))
# We did not get a reply from the PLC Modbus server, so count it and report a warning message.
except exceptions.ConnectionException:
modbus_data_validity = False
connection_error_count += 1
except_desc = "PLC did not respond to data request. Data validity: " + str(modbus_data_validity)
rospy.logwarn(except_desc)
# The PLC Modbus server did not respond with the type of message we were expecting.
except:
except_desc = "An exception was raised while attempting to read from the Modbus server"
rospy.logerr(except_desc)
rospy.signal_shutdown(except_desc)
# Data is GOOD, so let's process it.
else:
# Report to all service calls that the data is GOOD
modbus_data_validity = True
# We got a good response, so update the arrays
update_sensor_array(returned_station_states, plc_num_stations)
update_button_array(returned_button_states, plc_num_buttons)
# If we have not heard back from the PLC Modbus server in
# (connection_error_count * (1/plc_polling_rate) seconds, so we should shutdown.
if connection_error_count >= 10:
except_desc = "Could not communicate with PLC. Error count exceeded: "+ str(connection_error_count) + " failures"
rospy.logerr(except_desc)
rospy.signal_shutdown(except_desc)
# Wait until the next Modbus poll
plc_polling_rate.sleep()
示例8: run_sync_client
# 需要导入模块: from pymodbus.client.sync import ModbusTcpClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusTcpClient import read_discrete_inputs [as 别名]
def run_sync_client():
# ------------------------------------------------------------------------#
# choose the client you want
# ------------------------------------------------------------------------#
# make sure to start an implementation to hit against. For this
# you can use an existing device, the reference implementation in the tools
# directory, or start a pymodbus server.
#
# If you use the UDP or TCP clients, you can override the framer being used
# to use a custom implementation (say RTU over TCP). By default they use
# the socket framer::
#
# client = ModbusClient('localhost', port=5020, framer=ModbusRtuFramer)
#
# It should be noted that you can supply an ipv4 or an ipv6 host address
# for both the UDP and TCP clients.
#
# There are also other options that can be set on the client that controls
# how transactions are performed. The current ones are:
#
# * retries - Specify how many retries to allow per transaction (default=3)
# * retry_on_empty - Is an empty response a retry (default = False)
# * source_address - Specifies the TCP source address to bind to
#
# Here is an example of using these options::
#
# client = ModbusClient('localhost', retries=3, retry_on_empty=True)
# ------------------------------------------------------------------------#
client = ModbusClient('localhost', port=5020)
# client = ModbusClient(method='ascii', port='/dev/pts/2', timeout=1)
# client = ModbusClient(method='rtu', port='/dev/ttyp0', timeout=1)
client.connect()
# ------------------------------------------------------------------------#
# specify slave to query
# ------------------------------------------------------------------------#
# The slave to query is specified in an optional parameter for each
# individual request. This can be done by specifying the `unit` parameter
# which defaults to `0x00`
# ----------------------------------------------------------------------- #
log.debug("Reading Coils")
rr = client.read_coils(1, 1, unit=0x01)
print(rr)
# ----------------------------------------------------------------------- #
# example requests
# ----------------------------------------------------------------------- #
# simply call the methods that you would like to use. An example session
# is displayed below along with some assert checks. Note that some modbus
# implementations differentiate holding/input discrete/coils and as such
# you will not be able to write to these, therefore the starting values
# are not known to these tests. Furthermore, some use the same memory
# blocks for the two sets, so a change to one is a change to the other.
# Keep both of these cases in mind when testing as the following will
# _only_ pass with the supplied async modbus server (script supplied).
# ----------------------------------------------------------------------- #
log.debug("Write to a Coil and read back")
rq = client.write_coil(0, True, unit=UNIT)
rr = client.read_coils(0, 1, unit=UNIT)
assert(rq.function_code < 0x80) # test that we are not an error
assert(rr.bits[0] == True) # test the expected value
log.debug("Write to multiple coils and read back- test 1")
rq = client.write_coils(1, [True]*8, unit=UNIT)
assert(rq.function_code < 0x80) # test that we are not an error
rr = client.read_coils(1, 21, unit=UNIT)
assert(rr.function_code < 0x80) # test that we are not an error
resp = [True]*21
# If the returned output quantity is not a multiple of eight,
# the remaining bits in the final data byte will be padded with zeros
# (toward the high order end of the byte).
resp.extend([False]*3)
assert(rr.bits == resp) # test the expected value
log.debug("Write to multiple coils and read back - test 2")
rq = client.write_coils(1, [False]*8, unit=UNIT)
rr = client.read_coils(1, 8, unit=UNIT)
assert(rq.function_code < 0x80) # test that we are not an error
assert(rr.bits == [False]*8) # test the expected value
log.debug("Read discrete inputs")
rr = client.read_discrete_inputs(0, 8, unit=UNIT)
assert(rq.function_code < 0x80) # test that we are not an error
log.debug("Write to a holding register and read back")
rq = client.write_register(1, 10, unit=UNIT)
rr = client.read_holding_registers(1, 1, unit=UNIT)
assert(rq.function_code < 0x80) # test that we are not an error
assert(rr.registers[0] == 10) # test the expected value
log.debug("Write to multiple holding registers and read back")
rq = client.write_registers(1, [10]*8, unit=UNIT)
rr = client.read_holding_registers(1, 8, unit=UNIT)
assert(rq.function_code < 0x80) # test that we are not an error
assert(rr.registers == [10]*8) # test the expected value
log.debug("Read input registers")
rr = client.read_input_registers(1, 8, unit=UNIT)
#.........这里部分代码省略.........
示例9: range
# 需要导入模块: from pymodbus.client.sync import ModbusTcpClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusTcpClient import read_discrete_inputs [as 别名]
for i in range(0, len(totusTemps)):
print totusTemps[i] + " = " + str(result.getRegister(i)/10.0) + "\xb0C"# scaling is 10
# read alarms
totusAlarms = [
"ALARM/System/HL/State",
"ALARM/System/HHLL/State"
]
numInputs = 2
startAddress = 100
slaveID = 1
result = client.read_discrete_inputs(startAddress, numInputs, slaveID)
for i in range(0, len(totusAlarms)):
print totusAlarms[i] + " = " + str(result.getBit(i))
# read DGA float32 gases
totusDGA = [
"DGA/SourceA/CH4",
"DGA/SourceA/C2H6",
"DGA/SourceA/C2H4",
"DGA/SourceA/C2H2",
"DGA/SourceA/CO",
"DGA/SourceA/CO2",
"DGA/SourceA/O2",