本文整理汇总了Python中pymodbus.client.sync.ModbusSerialClient.read_discrete_inputs方法的典型用法代码示例。如果您正苦于以下问题:Python ModbusSerialClient.read_discrete_inputs方法的具体用法?Python ModbusSerialClient.read_discrete_inputs怎么用?Python ModbusSerialClient.read_discrete_inputs使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pymodbus.client.sync.ModbusSerialClient
的用法示例。
在下文中一共展示了ModbusSerialClient.read_discrete_inputs方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: from pymodbus.client.sync import ModbusSerialClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusSerialClient import read_discrete_inputs [as 别名]
class EPsolarTracerClient:
''' EPsolar Tracer client
'''
def __init__(self, unit = 1, serialclient = None, **kwargs):
''' Initialize a serial client instance
'''
self.unit = unit
if serialclient == None:
port = kwargs.get('port', '/dev/ttyXRUSB0')
baudrate = kwargs.get('baudrate', 115200)
self.client = ModbusClient(method = 'rtu', port = port, baudrate = baudrate, kwargs = kwargs)
else:
self.client = serialclient
def connect(self):
''' Connect to the serial
:returns: True if connection succeeded, False otherwise
'''
return self.client.connect()
def close(self):
''' Closes the underlying connection
'''
return self.client.close()
def read_device_info(self):
request = ReadDeviceInformationRequest (unit = self.unit)
response = self.client.execute(request)
return response
def read_input(self, name):
register = registerByName(name)
if register.is_coil():
response = self.client.read_coils(register.address, register.size, unit = self.unit)
elif register.is_discrete_input():
response = self.client.read_discrete_inputs(register.address, register.size, unit = self.unit)
elif register.is_input_register():
response = self.client.read_input_registers(register.address, register.size, unit = self.unit)
else:
response = self.client.read_holding_registers(register.address, register.size, unit = self.unit)
return register.decode(response)
def write_output(self, name, value):
register = registerByName(name)
values = register.encode(value)
response = False
if register.is_coil():
self.client.write_coil(register.address, values, unit = self.unit)
response = True
elif register.is_discrete_input():
_logger.error("Cannot write discrete input " + repr(name))
pass
elif register.is_input_register():
_logger.error("Cannot write input register " + repr(name))
pass
else:
self.client.write_registers(register.address, values, unit = self.unit)
response = True
return response
示例2: run_sync_client
# 需要导入模块: from pymodbus.client.sync import ModbusSerialClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusSerialClient 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/ttyS3', baudrate=9600, timeout=1)
client.connect()
# ----------------------------------------------------------------------- #
# 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).
# ----------------------------------------------------------------------- #
# 读模块型号
rr = client.read_holding_registers(40001, 1, unit=UNIT)
print(rr.registers[0])
# 读两路输入(寄存器地址200,共2个)
log.debug("Read discrete inputs")
rr = client.read_discrete_inputs(200, 2, unit=UNIT)
print(rr.bits) # bit0表示DI1的状态,bit1表示DI2
# 写单个输出DO1(寄存器地址100)
log.debug("Write to a Coil and read back")
rq = client.write_coil(100, True, unit=UNIT)
rr = client.read_coils(100, 1, unit=UNIT)
assert(rq.function_code < 0x80) # test that we are not an error
assert(rr.bits[0] == True) # test the expected value
# ----------------------------------------------------------------------- #
# close the client
# ----------------------------------------------------------------------- #
client.close()
示例3: run_sync_client
# 需要导入模块: from pymodbus.client.sync import ModbusSerialClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusSerialClient 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
# * strict - Applicable only for Modbus RTU clients.
# Adheres to modbus protocol for timing restrictions
# (default = True).
# Setting this to False would disable the inter char timeout
# restriction (t1.5) for Modbus RTU
#
#
# Here is an example of using these options::
#
# client = ModbusClient('localhost', retries=3, retry_on_empty=True)
# ------------------------------------------------------------------------#
client = ModbusClient('localhost', port=5020)
# from pymodbus.transaction import ModbusRtuFramer
# client = ModbusClient('localhost', port=5020, framer=ModbusRtuFramer)
# client = ModbusClient(method='binary', port='/dev/ptyp0', timeout=1)
# client = ModbusClient(method='ascii', port='/dev/ptyp0', timeout=1)
# client = ModbusClient(method='rtu', port='/dev/ptyp0', timeout=1,
# baudrate=9600)
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=UNIT)
log.debug(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 asynchronous 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(not rq.isError()) # 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(not rq.isError()) # test that we are not an error
rr = client.read_coils(1, 21, unit=UNIT)
assert(not rr.isError()) # 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(not rq.isError()) # 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(not rq.isError()) # 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)
#.........这里部分代码省略.........
示例4: byteswap
# 需要导入模块: from pymodbus.client.sync import ModbusSerialClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusSerialClient import read_discrete_inputs [as 别名]
while True:
result = client.read_input_registers(100, 6, unit=1)
if result:
#result.registers[0] = byteswap(result.registers[0])
#result.registers[1] = byteswap(result.registers[1])
#result.registers[2] = byteswap(result.registers[2])
#result.registers[3] = byteswap(result.registers[3])
#result.registers[4] = byteswap(result.registers[4])
#result.registers[5] = byteswap(result.registers[5])
decoder = BinaryPayloadDecoder.fromRegisters(result.registers, endian=Endian.Big)
decoded = {
'voltage': decoder.decode_32bit_float(),
'pt100': decoder.decode_32bit_float(),
'freq': decoder.decode_32bit_float()
}
print decoded
client.write_coils(100, (1, 1, 1, 1, 1, 1), unit=1)
result = client.read_discrete_inputs(100, 4, unit=1)
print result.bits
encoder = BinaryPayloadBuilder(endian=Endian.Big)
encoder.add_32bit_float(20)
encoder.add_32bit_float(80)
buf = encoder.build()
#buf[0] = charswap(buf[0])
#buf[1] = charswap(buf[1])
#buf[2] = charswap(buf[2])
#buf[3] = charswap(buf[3])
client.write_registers(100, buf, unit=1, skip_encode=True)
#break
示例5: ModbusRtuClient
# 需要导入模块: from pymodbus.client.sync import ModbusSerialClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusSerialClient import read_discrete_inputs [as 别名]
#logging.basicConfig()
#log = logging.getLogger()
#log.setLevel(logging.DEBUG)
sleep_time=0.2;#in sec
try:
print'Открываем соединение...'
client = ModbusRtuClient(method="rtu",port="/dev/ttyUSB0",stopbits=1,bytesize=8,parity="O",baudrate=115200,timeout=0.01);
print client
client.connect(); print'Установили соединение'
start_address = 0x00; regs=8;i=0;
#for i in range(200):
while (True):
#print "."*20,"we are going to read now","."*20
rq = client.read_discrete_inputs(start_address,regs,unit=0x05)
print i,"M-7050D ",rq.bits
if not(rq.bits[0]) : client.write_coil(0, True, unit=0x05) #print "send on";
if rq.bits[0]: client.write_coil(0, False, unit=0x05) #print "sen off";
#rq = client.read_discrete_inputs(start_address,16,unit=0x04)
#print i,"modsim32",rq.bits
i+=1
#sleep(sleep_time)
except:
print'ошибка!'
else:
print'Всё хорошо.'
finally:
示例6: state
# 需要导入模块: from pymodbus.client.sync import ModbusSerialClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusSerialClient import read_discrete_inputs [as 别名]
print "[27] state of post heating battery ............. : ",result.registers[27]," <=> ",state_of_postheating
print "[28] ** UNDOCUMENTED / UNSED ** ................ : ",result.registers[28]
print "[29] ** UNDOCUMENTED / UNSED ** ................ : ",result.registers[29]
print "[30] ** UNDOCUMENTED / UNSED ** ................ : ",result.registers[30]
print "[31] ** UNDOCUMENTED / UNSED ** ................ : ",result.registers[31]
print "[32] ** UNDOCUMENTED / UNSED ** ................ : ",result.registers[32]
print "[33] ** UNDOCUMENTED / UNSED ** ................ : ",result.registers[33]
print "[34] ** UNDOCUMENTED / UNSED ** ................ : ",result.registers[34]
print "[35] ** UNDOCUMENTED / UNSED ** ................ : ",result.registers[35]
print "[36] filter alarm .............................. : ",result.registers[36],"months"
print "[37] temperature tin pre heating battery ....... : ",result.registers[37]
print "[38] temperature tout pre heating battery ...... : ",result.registers[38]
print "[39] temperature tin post heating battery ...... : ",result.registers[39]
print "[40] temperature tout post heating battery ..... : ",result.registers[40]
result = client.read_discrete_inputs(address=0x00, count=15, unit=0x01)
print "===================================================="
print "DISCRETES INPUT"
print "===================================================="
print "[00] ** UNDOCUMENTED / UNSED ** ................ : ",convert_bit_to_string(result.bits[0],"False","True")
print "[01] version ................................... : ",convert_bit_to_string(result.bits[1],"STANDARD+ABSENCE","ALLEMAGNE+STANDBY")
print "[02] free contact .............................. : ",convert_bit_to_string(result.bits[2],"NO","NC")
print "[03] ** UNDOCUMENTED / UNSED ** ................ : ",convert_bit_to_string(result.bits[3],"False","True")
print "[04] ** UNDOCUMENTED / UNSED ** ................ : ",convert_bit_to_string(result.bits[4],"False","True")
print "[05] defroost mode ............................. : ",convert_bit_to_string(result.bits[5],"desactivated","actived")
print "[06] extract motor state ....................... : ",convert_bit_to_string(result.bits[6],"ok","error")
print "[07] input motor state ......................... : ",convert_bit_to_string(result.bits[7],"ok","error")
print "[08] ** UNDOCUMENTED / UNSED ** ................ : ",convert_bit_to_string(result.bits[8],"False","True")
print "[09] ** UNDOCUMENTED / UNSED ** ................ : ",convert_bit_to_string(result.bits[9],"False","True")
print "[10] inside temperature sensor state (tint) .... : ",convert_bit_to_string(result.bits[10],"ok","error")
print "[11] outside temperature sensor state (tout) ... : ",convert_bit_to_string(result.bits[11],"ok","error")
示例7: range
# 需要导入模块: from pymodbus.client.sync import ModbusSerialClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusSerialClient import read_discrete_inputs [as 别名]
numInputs = 10
startAddress = 1000
slaveID = 1
result = client.read_input_registers(startAddress, numInputs, slaveID)
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",
"DGA/SourceA/N2",
"DGA/SourceA/H2",
示例8: __init__
# 需要导入模块: from pymodbus.client.sync import ModbusSerialClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusSerialClient import read_discrete_inputs [as 别名]
#.........这里部分代码省略.........
raise SystemExit('Modbus Error: Failed 3 Attemps')
elif w == ValueError:
#TODO: remove sys exit and handle properly
raise SystemExit('Invalid Register - Use 15 or 16')
else:
return w
return ValueError('Invalid Operation')
def __readData(self, reg, addr, length, encoding):
"""Read data from the MODBUS Slave
Called by 'dataHandler' in modbusClient.py
Arguments:
:param reg: Modbus register to access (1-4)
:param addr: Address to start reading from
:param length: Quantity of registers to read
:param encoding: States whether data should be decoded
:type reg: int
:type addr: int
:type length: int
:type encoding: int
:return: List containing the requested data or failure exception.
"""
data = []
if 1 <= reg <= 2:
try:
if reg == 1:
co = self.client.read_coils(addr,length,unit=0x01)
else:
co = self.client.read_discrete_inputs(addr,length,unit=0x01)
except ConnectionException:
return ConnectionException
if co.function_code != reg:
return ModbusIOException
for i in range(length):
data.append(co.getBit(i))
return data
elif 3 <= reg <= 4:
try:
if reg == 3:
hr = self.client.read_holding_registers(addr,length,unit=0x01)
else:
hr = self.client.read_input_registers(addr,length,unit=0x01)
except ConnectionException:
return ConnectionException
if hr.function_code != reg:
return ModbusIOException
for i in range(length):
data.append(hr.getRegister(i))
if encoding == 1:
return self.__decodeData(data)
return data
else:
return ValueError