本文整理汇总了Python中pymodbus.client.sync.ModbusSerialClient.read_coils方法的典型用法代码示例。如果您正苦于以下问题:Python ModbusSerialClient.read_coils方法的具体用法?Python ModbusSerialClient.read_coils怎么用?Python ModbusSerialClient.read_coils使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pymodbus.client.sync.ModbusSerialClient
的用法示例。
在下文中一共展示了ModbusSerialClient.read_coils方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: from pymodbus.client.sync import ModbusSerialClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusSerialClient import read_coils [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: PyModbusClient
# 需要导入模块: from pymodbus.client.sync import ModbusSerialClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusSerialClient import read_coils [as 别名]
class PyModbusClient(BaseModbusClient):
def __init__(self, *args, **kwargs):
super(PyModbusClient, self).__init__(*args, **kwargs)
if self.method == "tcp":
from pymodbus.client.sync import ModbusTcpClient
self.client = ModbusTcpClient(self.host, self.port)
else:
from pymodbus.client.sync import ModbusSerialClient
argnames = ("stopbits", "bytesize", "parity", "baudrate", "timeout")
kwargs = dict((k, getattr(self, k)) for k in argnames)
kwargs.update({
"port": self.host,
})
self.client = ModbusSerialClient(self.method, **kwargs)
def read_coils(self, address, count):
resp = self.client.read_coils(address, count, unit=self.unit)
if resp is None:
raise NoDeviceResponse()
return resp.bits[:count]
def write_coil(self, address, value):
resp = self.client.write_coil(address, int(value), unit=self.unit)
if resp is None:
raise NoDeviceResponse()
return resp.value
示例3: run_sync_client
# 需要导入模块: from pymodbus.client.sync import ModbusSerialClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusSerialClient import read_coils [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()
示例4: run_sync_client
# 需要导入模块: from pymodbus.client.sync import ModbusSerialClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusSerialClient import read_coils [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)
#.........这里部分代码省略.........
示例5: server
# 需要导入模块: from pymodbus.client.sync import ModbusSerialClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusSerialClient import read_coils [as 别名]
# 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).
#---------------------------------------------------------------------------#
#rq = client.write_coil(1, True)
var = 1
try:
conn=psycopg2.connect("dbname='hcam' user='adminbwhvjhr' password='xnw5Px3WqUi6'")
except:
print "I am unable to connect to the database."
cur = conn.cursor()
while var == 1 :
rr1 = client.read_coils(2048,10,unit=0x01)
#print rr1.bits[0]
#print rr1.bits[1]
#print rr1.bits[2]
#print rr1.bits[8]
rr2 = client.read_coils(3099,2,unit=0x01)
#print rr2.bits[0]
#print rr2.bits[1]
rr3 = client.read_holding_registers(1088,2,unit=0x01)
#print hex(rr3.registers[0]).lstrip("0x")
#print hex(rr3.registers[1]).lstrip("0x")
try:
query = "insert into presion_flujo(id,fecha,presion,flujo) values(nextval('seq_presion_flujo'), current_timestamp, %s, %s)"
示例6: state
# 需要导入模块: from pymodbus.client.sync import ModbusSerialClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusSerialClient import read_coils [as 别名]
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")
print "[12] extract temperature sensor state (text) ... : ",convert_bit_to_string(result.bits[12],"ok","error")
print "[13] input temperature sensor state (tinp) ..... : ",convert_bit_to_string(result.bits[13],"ok","error")
print "[14] alarm filters state ....................... : ",convert_bit_to_string(result.bits[14],"off","on")
result = client.read_coils(address=0x00, count=14, unit=0x01)
print "===================================================="
print "COILS"
print "===================================================="
print "[00] ** UNDOCUMENTED / UNSED ** ................ : ",convert_bit_to_string(result.bits[0],"False","True")
print "[01] ** UNDOCUMENTED / UNSED ** ................ : ",convert_bit_to_string(result.bits[1],"False","True")
print "[02] pre heating battery ....................... : ",convert_bit_to_string(result.bits[2],"not installed","installed")
print "[03] post heating battery ...................... : ",convert_bit_to_string(result.bits[3],"not installed","installed")
print "[04] sense of switch ........................... : ",convert_bit_to_string(result.bits[4],"no","nc")
print "[05] ** UNDOCUMENTED / UNSED ** ................ : ",convert_bit_to_string(result.bits[5],"False","True")
print "[06] selection of version ...................... : ",convert_bit_to_string(result.bits[6],"STANDBY+ABSENCE","ALLEMAGNE+STANDBY")
print "[07] activation mode stanby absence ............ : ",convert_bit_to_string(result.bits[7],"STANBY/ABSENCE ON","STANDBY/ABSENCE OFF")
print "[08] bypass auto control ....................... : ",convert_bit_to_string(result.bits[8],"actived","desactivated")
print "[09] manual bypass ............................. : ",convert_bit_to_string(result.bits[9],"desactivated","activated")
print "[10] ** UNDOCUMENTED / UNSED ** ................ : ",convert_bit_to_string(result.bits[10],"False","True")
print "[11] ** UNDOCUMENTED / UNSED ** ................ : ",convert_bit_to_string(result.bits[11],"False","True")
示例7: ModbusClient
# 需要导入模块: from pymodbus.client.sync import ModbusSerialClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusSerialClient import read_coils [as 别名]
#!/usr/bin/env python
# test script to write to coils on enervent ventilation unit
from pymodbus.client.sync import ModbusSerialClient as ModbusClient
import logging
logging.basicConfig()
log = logging.getLogger()
log.setLevel(logging.DEBUG)
client = ModbusClient(method='rtu', port='/dev/ttyUSB0', timeout=1)
client.connect()
log.debug("Reading Coils")
# starting register, number of registers, slave unit id
rr = client.read_coils(12, 1, unit=0x01)
#hh = client.read_holding_registers(1,45,unit=0x01)
#print "holding registers:"
#print hh.registers
#print "coild register:"
#print rr.bits
#print("{}: {}".format("summernight cooling status:", rr.bits[0]))
#rq = client.write_register(53, 70, unit=0x01)
#rqq = client.write_register(53, 71, unit=0x01)
#print rqq
kk = client.read_holding_registers(53,1,unit=0x01)
print "ventilation:"
示例8: __init__
# 需要导入模块: from pymodbus.client.sync import ModbusSerialClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusSerialClient import read_coils [as 别名]
#.........这里部分代码省略.........
if i == 2:
#TODO: remove sys exit and handle properly
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
示例9:
# 需要导入模块: from pymodbus.client.sync import ModbusSerialClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusSerialClient import read_coils [as 别名]
logging.info("Holding registers: %s" % ex.registers)
else:
logging.error("Error pidiendo HRs")
continue
regs = ex.registers
led_value = 0 if regs[0] == 1 else 1
count += 1
regs[2] = count
regs[0] = led_value
ex = client.write_registers(0, regs, unit=client_id)
if ex is not None:
logging.debug("Nuevo valor para el led: %d, respuesta: %s" % (led_value, ex))
else:
logging.error("Error seteando led con valor %d" % led_value)
logging.info("%02d/%02d/%d %02d:%02d:%02d:\tLed %03s, Light: %s ohms, Counter: %d" % (regs[4], regs[5], regs[6], regs[7], regs[8], regs[9], ("ON" if led_value == 1 else "OFF"), regs[1], regs[3]))
# testeo errores en invocacion a funcion invalida
ex = client.read_coils(address=0, count=20, unit=client_id);
if ex is not None:
logging.debug("read_coils with error: %s" % ex)
else:
logging.error("Error invocando read_coils con argumentos invalidos")
client.close()
示例10: DemeterClient
# 需要导入模块: from pymodbus.client.sync import ModbusSerialClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusSerialClient import read_coils [as 别名]
class DemeterClient(object):
def __init__(self, unit, modbus_config):
self.client = ModbusSerialClient(**modbus_config)
self.unit = unit
self.valid_commands = {
'read_holding_registers': self.read_holding_registers,
'write_registers': self.write_holding_registers,
'read_input_registers': self.read_input_registers,
'read_coils': self.read_coils,
'write_coils': self.write_coils,
'get_datetime': self.get_datetime,
'set_datetime': self.set_datetime,
'get_loginterval': self.get_loginterval,
'set_loginterval': self.set_loginterval,
'read_event': self.read_event,
'write_event': self.write_event,
'enable_event': self.enable_event,
'disable_event': self.disable_event,
'read_events': self.read_events,
'disable_event': self.disable_event,
'enable_event': self.enable_event,
'disable_relay': self.disable_relay,
'enable_relay': self.enable_relay,
'temperatura': self.get_temperature,
'humedad': self.get_humidity,
'luz': self.get_light,
}
def is_valid(self, command):
return command in self.valid_commands
def read_holding_registers(self, arguments):
if len(arguments) != 2:
return "Modo de uso: read_holding_registers <start-address> <registers>"
for i in range(0, len(arguments)):
if not self.__is_number(arguments[i]):
return "%s: se esperaba un entero" % arguments[i]
values = [int(x) for x in arguments]
return self.client.read_holding_registers(address=values[0], count=values[1], unit=self.unit)
def write_holding_registers(self, arguments):
if len(arguments) < 2:
return "Modo de uso: write_holding_registers <start-address> <register-1> <register-2> ... <register-n>"
for i in range(0, len(arguments)):
if not self.__is_number(arguments[i]):
return "%s: se esperaba un entero" % arguments[i]
values = [int(x) for x in arguments]
return self.client.write_registers(values[0], values[1:], unit=self.unit)
def get_temperature(self, arguments):
value = self.client.read_input_registers(address=0, count=1, unit=self.unit)
if isinstance(value, ReadRegistersResponseBase):
value = "%d,%d °C" % (value.registers[0]/10, value.registers[0]%10)
return value
def get_humidity(self, arguments):
value = self.client.read_input_registers(address=1, count=1, unit=self.unit)
if isinstance(value, ReadRegistersResponseBase):
value = "%d,%d %%" % (value.registers[0]/10, value.registers[0]%10)
return value
def get_light(self, arguments):
value = self.client.read_input_registers(address=2, count=1, unit=self.unit)
if isinstance(value, ReadRegistersResponseBase):
value = value.registers[0]
return value
def read_input_registers(self, arguments):
if len(arguments) != 2:
return "Modo de uso: read_input_registers <start-address> <registers>"
for i in range(0, len(arguments)):
if not self.__is_number(arguments[i]):
return "%s: se esperaba un entero" % arguments[i]
values = [int(x) for x in arguments]
return self.client.read_input_registers(address=values[0], count=values[1], unit=self.unit)
def read_coils(self, arguments):
if len(arguments) != 2:
return "Modo de uso: read_coils <start-address> <coils>"
for i in range(0, len(arguments)):
if not self.__is_number(arguments[i]):
return "%s: se esperaba un entero" % arguments[i]
values = [int(x) for x in arguments]
return self.client.read_coils(address=values[0], count=values[1], unit=self.unit)
def write_coils(self, arguments):
if len(arguments) < 2:
return "Modo de uso: write_coils <start-address> <bit-1> <bit-2> ... <bit-n>"
#.........这里部分代码省略.........