本文整理汇总了Python中pymodbus.client.sync.ModbusTcpClient.read_coils方法的典型用法代码示例。如果您正苦于以下问题:Python ModbusTcpClient.read_coils方法的具体用法?Python ModbusTcpClient.read_coils怎么用?Python ModbusTcpClient.read_coils使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pymodbus.client.sync.ModbusTcpClient
的用法示例。
在下文中一共展示了ModbusTcpClient.read_coils方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: ModbusModule
# 需要导入模块: from pymodbus.client.sync import ModbusTcpClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusTcpClient import read_coils [as 别名]
class ModbusModule():
def __init__(self, io_module_name, ip):
logger.debug('Creating new controller with name {} and address {}.'.format(io_module_name, ip))
self.io_module_name = io_module_name
self.ip_address = ip
self.controller_type = CONTROLLER_TYPE.Modbus
# build connection object
self.client = ModbusClient(ip, port=config.DEFAULT_MODBUS_PORT)
self.client.connect()
def __del__(self):
self.client.close()
def __str__(self):
return 'Controller "{}" at address {}'.format(self.io_module_name, self.ip_address)
def get_bit(self, address):
try:
result = self.client.read_coils(address)
bit_value = result.bits[0]
except ConnectionException:
logger.error('Could not connect to Modbus module "{}"!'
.format(self.io_module_name))
bit_value = False
return bit_value
def set_bit(self, address, value):
try:
self.client.write_coil(address, value)
except ConnectionException:
logger.error('Could not connect to Modbus module "{}"!'
.format(self.io_module_name))
示例2: LEDUpdateThread
# 需要导入模块: from pymodbus.client.sync import ModbusTcpClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusTcpClient import read_coils [as 别名]
def LEDUpdateThread(pin, update_interval, e):
print 'LEDUpdateThread'
client = ModbusTcpClient(args.ip)
GPIO.setup(pin, GPIO.OUT)
while True:
if not e.isSet():
result = client.read_coils(0, 1)
if result is not None:
pin_status = result.bits[0]
GPIO.output(pin, pin_status)
print pin_status
time.sleep(update_interval)
else:
break
client.close()
print 'LED thread stoped'
示例3: get_modbus
# 需要导入模块: from pymodbus.client.sync import ModbusTcpClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusTcpClient import read_coils [as 别名]
def get_modbus(properties):
try:
print "Performing an action which may throw an exception."
client = ModbusClient(properties['ip'], port=502)
client.connect()
log.debug(properties['registers'])
log.debug(properties['coils'])
modbus_values = {}
# Get holding registers values
modbus_registers = {}
for i in properties['registers']:
register_start_nb = i.split('-')[0]
register_end_nb = i.split('-')[1]
log.debug('Register start number : %s' % register_start_nb)
log.debug('Register end number : %s' % register_end_nb)
register_count = int(register_end_nb) - int(register_start_nb)
log.debug('Number of registers to read : %s' % register_count)
rr = client.read_holding_registers(int(register_start_nb),register_count, unit=0x01)
modbus_registers[register_start_nb] = rr.registers
log.debug('Registers values : %s' % rr.registers)
# Get coils values
modbus_coils = {}
for i in properties['coils']:
coil_start_nb = i.split('-')[0]
coil_end_nb = i.split('-')[1]
log.debug('Coil start number : ' + register_start_nb)
log.debug('Coil end number : ' + register_end_nb)
coil_count = int(coil_end_nb) - int(coil_start_nb)
log.debug('Number of coils to read : ' + str(coil_count))
rr = client.read_coils(int(coil_start_nb),coil_count, unit=0x01)
modbus_coils[coil_start_nb] = rr.bits
log.debug('Coils values : ' + str(rr.bits))
log.debug('Modbus coils values : ' + str(modbus_coils))
client.close()
modbus_values['registers'] = modbus_registers
modbus_values['coils'] = modbus_coils
log.debug(str(modbus_values))
return modbus_values
except Exception, error:
log.debug('Error connecting to %s' % properties['ip'])
log.debug(str(error))
示例4: RGBLEDUpdateThread
# 需要导入模块: from pymodbus.client.sync import ModbusTcpClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusTcpClient import read_coils [as 别名]
def RGBLEDUpdateThread(pins, update_interval, e):
print 'RGBLEDUpdateThread'
client = ModbusTcpClient(ip)
# Setup pins mode
for i in range(0, 3):
GPIO.setup(pins[i], GPIO.OUT)
while True:
if not e.isSet():
result = client.read_coils(10, 3)
print 'RGB LED. R:', result.bits[0], 'G:', result.bits[1], 'B:', result.bits[2]
for i in range(0, 3):
GPIO.output(pins[i], result.bits[i])
time.sleep(update_interval)
else:
break
client.close()
print 'RGB LED Stopped'
示例5: readMBcoils
# 需要导入模块: from pymodbus.client.sync import ModbusTcpClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusTcpClient import read_coils [as 别名]
def readMBcoils(clientIP, coil, number=1):
from pymodbus.client.sync import ModbusTcpClient, ConnectionException
client = ModbusTcpClient(clientIP)
values = []
try:
rawresult = client.read_coils(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
示例6: ModbusClient
# 需要导入模块: from pymodbus.client.sync import ModbusTcpClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusTcpClient import read_coils [as 别名]
client = ModbusClient('127.0.0.1')
#---------------------------------------------------------------------------#
# 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).
#---------------------------------------------------------------------------#
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)
示例7: ModbusTcpClient
# 需要导入模块: from pymodbus.client.sync import ModbusTcpClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusTcpClient import read_coils [as 别名]
from pymodbus.client.sync import ModbusTcpClient
client = ModbusTcpClient('127.0.0.1')
result = client.read_coils(0,1)
print result.bits[0]
client.close()
示例8: clientthreads
# 需要导入模块: from pymodbus.client.sync import ModbusTcpClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusTcpClient import read_coils [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
示例9: assert
# 需要导入模块: from pymodbus.client.sync import ModbusTcpClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusTcpClient import read_coils [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()
示例10: ModbusClient
# 需要导入模块: from pymodbus.client.sync import ModbusTcpClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusTcpClient import read_coils [as 别名]
# 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)
#---------------------------------------------------------------------------#
# 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=1)
示例11: ModbusClass
# 需要导入模块: from pymodbus.client.sync import ModbusTcpClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusTcpClient import read_coils [as 别名]
class ModbusClass():
connected=False
def __init__(self, *kwargs):
self.connect()
def connect(self):
'''Try to connect to the Modbus client
(mostely internal)
'''
if not self.connected:
self.client = ModbusClient('192.168.50.238', port=502)
self.client.connect()
self.connected=True
def reset_safety(self, callback):
'''Call this class to reset safety
:param callback: callback which should be called at the end
'''
if not self.connected:
self.connect()
#write to bit 8480
rq = self.client.write_coil(8480, True)
time.sleep(0.5)
rq = self.client.write_coil(8480, False)
callback()
def transfer_bahn_nr(self, nr):
rq = self.client.write_register(532, nr)
rq = self.client.write_coil(8483, True)
time.sleep(0.5)
rq = self.client.write_coil(8483, False)
print "transfered"
def transfer_array(self, array, callback):
'''Call this function to move the array to the PLC
:param array: array which should be transmitted
:param callback: callback which should be called when finished
'''
#check array size
c=0
for cube in array:
c+=1
if c!= 106:
print "Array size isn't suitable", c
return
lis = array
#write cubes into PLC
c=0
for cube in lis:
print '-', (c/5)+1, cube
#write x
rq = self.client.write_register(c, cube['x'])
c+=1
#write y
rq = self.client.write_register(c, cube['y'])
c+=1
#write z
rq = self.client.write_register(c, cube['z'])
c+=1
#write rot
rq = self.client.write_register(c, cube['typ'])
c+=1
#write type
rq = self.client.write_register(c, cube['rot'])
c+=1
callback()
def machine_is_building(self, *kwargs):
'''Call this class to get the bool if the machine is working or not
'''
rq = self.client.read_coils(8481,1)
return rq.bits[0]
def read_active_bahn(self, *kwargs):
rq = self.client.read_holding_registers(533, 1)
return rq.registers[0]
示例12: InModbus
# 需要导入模块: from pymodbus.client.sync import ModbusTcpClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusTcpClient import read_coils [as 别名]
class InModbus(ApplicationSession):
"""
Checks the state of the relays of the lights (eshl/eshl.wago.v1.switch) and
makes three different RPCs to toggle/switch on/switch off the lights available.
"""
def __init__(self, config=None):
ApplicationSession.__init__(self, config)
self.pfcIp = '192.168.1.52'
self.modbusTcpPort = 502
self.client = ModbusClient(self.pfcIp, self.modbusTcpPort)
#==============================================================================
# Generates a blank Dataset with the current system timestamp
#==============================================================================
def blankDataSetGen(self):
blankDataset = {'K16': None,
'K17': None,
'K18': None,
'K19': None,
'K20': None,
'K21': None,
'TimestampSYS' : round(time.time() * 1000)
}
return blankDataset
def requestLoop(self):
try:
if (self.client.connect() is False):
print('not connected')
self.client = self.client.connect()
print('trying to connecto to ' + str(self.pfcIp))
address = 0
timestampSys = round(time.time() * 1000)
result = self.client.read_coils(560, 6)
relayState = {'K16': result.bits[0],
'K17': result.bits[1],
'K18': result.bits[2],
'K19': result.bits[3],
'K20': result.bits[4],
'K21': result.bits[5],
'TimestampSYS' : timestampSys}
self.publish(u'eshl.wago.v1.switch', relayState)
except ConnectionException as connErr:
relayState = self.blankDataSetGen()
self.publish(u'eshl.wago.v1.switch', relayState)
print(str(connErr))
except Exception as err:
print("error: {}".format(err), file=sys.stdout)
traceback.print_exc(file=sys.stdout)
@inlineCallbacks
def toggleSwitch(self, id):
try:
if (self.client.connect() is False):
print('not connected')
self.client.connect()
print('trying to connecto to ' + str(self.pfcIp))
print("toggleSwitch {}".format(id))
id = int(id)
if (id >= 16 and id <= 21):
id = 32768 + (id - 16)
elif (id == 0):
id = 32768 + 6
else:
return "unknown switch"
self.client.write_coil(id, 1)
yield sleep(0.1)
self.client.write_coil(id, 0)
return "ok"
except ConnectionException as connErr:
return "connection error"
except Exception as err:
print("error: {}".format(err), file=sys.stdout)
traceback.print_exc(file=sys.stdout)
return "connection error"
@inlineCallbacks
def switchOn(self, id):
try:
if (self.client.connect() is False):
print('not connected')
self.client.connect()
print('trying to connecto to ' + str(self.pfcIp))
print("switchOn {}".format(id))
id = int(id)
state = False
result = self.client.read_coils(560, 6)
if (id >= 16 and id <= 21):
#.........这里部分代码省略.........
示例13: client
# 需要导入模块: from pymodbus.client.sync import ModbusTcpClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusTcpClient import read_coils [as 别名]
if __name__ == "__main__":
print '=== Modbus client (RGB LED) ==='
parser = argparse.ArgumentParser(description='Modbus client')
parser.add_argument('ip', default='localhost', help='IP adress of modbus server')
args = parser.parse_args()
client = ModbusTcpClient(args.ip)
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
for i in range(0, 3):
GPIO.setup(LED_Pins[i], GPIO.OUT)
try:
while True:
result = client.read_coils(10, 3)
print 'R:', result.bits[0], 'G:', result.bits[1], 'B:', result.bits[2]
for i in range(0, 3):
GPIO.output(LED_Pins[i], result.bits[i])
time.sleep(update_interval)
except KeyboardInterrupt:
print 'Stopping program'
except Exception:
traceback.print_exc(file=sys.stdout)
GPIO.cleanup()
client.close()
print 'Done'
sys.exit(0)