本文整理汇总了Python中pymodbus.client.sync.ModbusSerialClient.write_coil方法的典型用法代码示例。如果您正苦于以下问题:Python ModbusSerialClient.write_coil方法的具体用法?Python ModbusSerialClient.write_coil怎么用?Python ModbusSerialClient.write_coil使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pymodbus.client.sync.ModbusSerialClient
的用法示例。
在下文中一共展示了ModbusSerialClient.write_coil方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: from pymodbus.client.sync import ModbusSerialClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusSerialClient import write_coil [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 write_coil [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 write_coil [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 write_coil [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: device
# 需要导入模块: from pymodbus.client.sync import ModbusSerialClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusSerialClient import write_coil [as 别名]
#.........这里部分代码省略.........
def _disconnect(self):
"""
close the connection to the modbus slave (server)
"""
self.slave.close()
def request_data(self):
"""
"""
if not driver_ok:
return None
if not self._connect():
if self._device_not_accessible == -1: #
logger.error("device with id: %d is not accessible" % self.device.pk)
self._device_not_accessible -= 1
return []
output = []
for register_block in self._variable_config:
result = register_block.request_data(self.slave, self._unit_id)
if result is None:
self._disconnect()
self._connect()
result = register_block.request_data(self.slave, self._unit_id)
if result is not None:
for variable_id in register_block.variables:
if self.variables[variable_id].update_value(result[variable_id], time()):
recorded_data_element = self.variables[variable_id].create_recorded_data_element()
if recorded_data_element is not None:
output.append(recorded_data_element)
if self.variables[variable_id].accessible < 1:
logger.info("variable with id: %d is now accessible" % variable_id)
self.variables[variable_id].accessible = 1
else:
for variable_id in register_block.variables:
if self.variables[variable_id].accessible == -1:
logger.error("variable with id: %d is not accessible" % variable_id)
self.variables[variable_id].update_value(None, time())
self.variables[variable_id].accessible -= 1
# reset device not accessible status
if self._device_not_accessible <= -1:
logger.info("device with id: %d is now accessible" % self.device.pk)
if self._device_not_accessible < 1:
self._device_not_accessible = 1
self._disconnect()
return output
def write_data(self, variable_id, value, task):
"""
write value to single modbus register or coil
"""
if variable_id not in self.variables:
return False
if not self.variables[variable_id].writeable:
return False
if self.variables[variable_id].modbusvariable.function_code_read == 3:
# write register
if 0 <= self.variables[variable_id].modbusvariable.address <= 65535:
if self._connect():
if self.variables[variable_id].get_bits_by_class() / 16 == 1:
# just write the value to one register
self.slave.write_register(self.variables[variable_id].modbusvariable.address, int(value),
unit=self._unit_id)
else:
# encode it first
self.slave.write_registers(self.variables[variable_id].modbusvariable.address,
list(self.variables[variable_id].encode_value(value)),
unit=self._unit_id)
self._disconnect()
return True
else:
logger.info("device with id: %d is now accessible" % self.device.pk)
return False
else:
logger.error('Modbus Address %d out of range' % self.variables[variable_id].modbusvariable.address)
return False
elif self.variables[variable_id].modbusvariable.function_code_read == 1:
# write coil
if 0 <= self.variables[variable_id].modbusvariable.address <= 65535:
if self._connect():
self.slave.write_coil(self.variables[variable_id].modbusvariable.address, bool(value),
unit=self._unit_id)
self._disconnect()
return True
else:
logger.info("device with id: %d is now accessible" % self.device.pk)
return False
else:
logger.error('Modbus Address %d out of range' % self.variables[variable_id].modbusvariable.address)
else:
logger.error('wrong type of function code %d' %
self.variables[variable_id].modbusvariable.function_code_read)
return False
示例6: ModbusRtuClient
# 需要导入模块: from pymodbus.client.sync import ModbusSerialClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusSerialClient import write_coil [as 别名]
#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:
client.close()
print 'Закрыли соединение'
示例7: ModbusSerialClient
# 需要导入模块: from pymodbus.client.sync import ModbusSerialClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusSerialClient import write_coil [as 别名]
#!/usr/bin/python
from pymodbus.client.sync import ModbusSerialClient
import sys
client = ModbusSerialClient(method='rtu', port='/dev/ttyUSB0', baudrate=19200, bytesize=8, stopbits=1, parity="E")
client.connect()
result=client.read_input_registers(address=36,count=1,unit=1)
print "Current filter alarm : ",result.registers[0]
client.write_coil(address=12,value=1,unit=1)
result=client.read_input_registers(address=36,count=1,unit=1)
print "New filter alarm : ",result.registers[0]