本文整理汇总了Python中pymodbus.client.sync.ModbusTcpClient.write_coil方法的典型用法代码示例。如果您正苦于以下问题:Python ModbusTcpClient.write_coil方法的具体用法?Python ModbusTcpClient.write_coil怎么用?Python ModbusTcpClient.write_coil使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pymodbus.client.sync.ModbusTcpClient
的用法示例。
在下文中一共展示了ModbusTcpClient.write_coil方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: TestMbTcpClass1
# 需要导入模块: from pymodbus.client.sync import ModbusTcpClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusTcpClient import write_coil [as 别名]
class TestMbTcpClass1(unittest.TestCase):
read_values = range(0xAA50, 0xAA60)
write_values = range(0xBB50, 0xBB60)
def setUp(self):
self.client = ModbusTcpClient(SERVER_HOST)
self.client.connect()
def tearDown(self):
self.client.close()
def test_write_single_holding_register(self):
rq = self.client.write_register(8, 0xCC)
self.assertEqual(rq.function_code, 0x06)
rr = self.client.read_holding_registers(8, 1)
self.assertEqual(rr.registers[0], 0xCC)
rq = self.client.write_register(16, 0x00)
self.assertEqual(rq.function_code, 0x86)
rq = self.client.write_register(8, 0xAA58)
def test_write_coil(self):
rq = self.client.write_coil(0, True)
self.assertEqual(rq.function_code, 0x05)
rq = self.client.write_coil(0, False)
self.assertEqual(rq.function_code, 0x05)
rq = self.client.write_coil(256, False)
self.assertEqual(rq.function_code, 0x85)
def test_read_coil(self):
coil_read_values = [True, False, True, False, False, True, False, False]
示例2: ModbusModule
# 需要导入模块: from pymodbus.client.sync import ModbusTcpClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusTcpClient import write_coil [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))
示例3: run
# 需要导入模块: from pymodbus.client.sync import ModbusTcpClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusTcpClient import write_coil [as 别名]
def run(self):
comm=server_addr[random.randint(0,len(serverlist)-1)]
client = ModbusTcpClient(comm, self.port, source_address=(self.ipaddr,0), retries=1, retry_on_empty=True)
while(not self.clientstop.is_set()):
client.write_coil(1, True)
print "coil write from:" + self.ipaddr + " --->" + comm
time.sleep(random.randint(0,3))
print "stopping"
client.socket.shutdown(1)
client.close()
return
示例4: ButtonUpdateThread
# 需要导入模块: from pymodbus.client.sync import ModbusTcpClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusTcpClient import write_coil [as 别名]
def ButtonUpdateThread(pin, update_interval, e):
print 'ButtomUpdateThread'
client = ModbusTcpClient(ip)
# Setup pin mode
GPIO.setup(pin, GPIO.IN)
while True:
if not e.isSet():
pin_status = GPIO.input(pin)
print status
client.write_coil(20, pin_status)
time.sleep(update_interval)
else:
break
client.close()
print 'Button Stopped'
示例5: ModbusClient
# 需要导入模块: from pymodbus.client.sync import ModbusTcpClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusTcpClient import write_coil [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)
示例6: clientthreads
# 需要导入模块: from pymodbus.client.sync import ModbusTcpClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusTcpClient import write_coil [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
示例7: client
# 需要导入模块: from pymodbus.client.sync import ModbusTcpClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusTcpClient import write_coil [as 别名]
pin_status = 1
update_interval = 0.05
if __name__ == "__main__":
print "=== Modbus client (Single button) ==="
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)
GPIO.setup(led, GPIO.IN)
try:
while True:
pin_status = GPIO.input(led)
print status
client.write_coil(20, pin_status)
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)
示例8: assert
# 需要导入模块: from pymodbus.client.sync import ModbusTcpClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusTcpClient import write_coil [as 别名]
# NOTE: write_register
if args.type == 'HR':
if args.count == 1:
hr_write = client.write_register(args.offset, args.register[0])
assert(hr_write.function_code < 0x80)
else:
hrs_write = client.write_registers(args.offset, args.register)
assert(hrs_write.function_code < 0x80)
# NOTE: write_coil: map integers to bools
elif args.type == 'CO':
if args.count == 1:
# NOTE: coil is a list with one bool
if args.coil[0] == 1:
co_write = client.write_coil(args.offset, True)
else:
co_write = client.write_coil(args.offset, False)
assert(co_write.function_code < 0x80)
else:
coils = []
for c in args.coil:
if c == 1:
coils.append(True)
else:
coils.append(False)
cos_write = client.write_coils(args.offset, coils)
assert(cos_write.function_code < 0x80)
示例9: server
# 需要导入模块: from pymodbus.client.sync import ModbusTcpClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusTcpClient import write_coil [as 别名]
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)
rr = client.read_coils(0, 1, unit=1)
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=1)
assert(rq.function_code < 0x80) # test that we are not an error
rr = client.read_coils(1, 21, unit=1)
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).
示例10: ModbusClass
# 需要导入模块: from pymodbus.client.sync import ModbusTcpClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusTcpClient import write_coil [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]
示例11: InModbus
# 需要导入模块: from pymodbus.client.sync import ModbusTcpClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusTcpClient import write_coil [as 别名]
class InModbus(ApplicationSession):
"""
Provides an RPC to control the shutters
"""
def __init__(self, config=None):
ApplicationSession.__init__(self, config)
self.pfcIp = '192.168.1.53'
self.modbusTcpPort = 502
self.client = ModbusClient(self.pfcIp, self.modbusTcpPort)
def shutterMapping(self, name):
if name == "FlurLinksUnten":
return 32768
elif name == "FlurLinksOben":
return 32769
elif name == "FlurRechtsUnten":
return 32770
elif name == "FlurRechtsOben":
return 32771
# elif name == "ZimmerLinksUnten":
# return 32772
# elif name == "ZimmerLinksOben":
# return 32773
elif name == "ZimmerRechtsUnten":
return 32774
elif name == "ZimmerRechtsOben":
return 32775
elif name == "KuecheUnten":
return 32776
elif name == "KuecheOben":
return 32777
else:
return "unknown"
@inlineCallbacks
def shutterControl(self, name):
name = str(name)
print(name)
try:
if (self.client.connect() is False):
print('not connected')
self.client = self.client.connect()
print('trying to connecto to ' + str(self.pfcIp))
modbusCoil = self.shutterMapping(name)
if (modbusCoil != "unknown"):
self.client.write_coil(modbusCoil, 1)
yield sleep(0.1)
self.client.write_coil(modbusCoil, 0)
else:
return "unknown shutter"
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"
def onJoin(self, details):
print("session ready")
self.register(self.shutterControl, u'eshl.wago.v1.misc.shuttercontrol')
示例12: InModbus
# 需要导入模块: from pymodbus.client.sync import ModbusTcpClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusTcpClient import write_coil [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: run_sync_client
# 需要导入模块: from pymodbus.client.sync import ModbusTcpClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusTcpClient 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/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)
#.........这里部分代码省略.........
示例14: Connection
# 需要导入模块: from pymodbus.client.sync import ModbusTcpClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusTcpClient import write_coil [as 别名]
class Connection():
def __init__(self, indicator_list, coil_on_list, coil_off_list, command_list, coil_list, port,
method="rtu", timeout=0.1, unit=0x01):
self.unit = unit
self.indicator_list = indicator_list
self.coil_on_list = coil_on_list
self.coil_off_list = coil_off_list
self.coil_list = coil_list
self.command_list = command_list
self.lock = threading.Lock()
if method == "rtu":
self.client = ModbusSerialClient(method=method, port=port, baudrate=19200, stopbits=1, bytesize=8,
timeout=timeout)
elif method == "tcp":
self.client = ModbusTcpClient(host=port)
def translate(self, command):
self.lock.acquire()
self.client.connect()
print self.client.connect()
# input registers
if command.split("_")[0] == "IReg":
rr = self.client.read_input_registers(self.indicator_list[command.split()[0]], 1, unit=self.unit)
self.client.close()
self.lock.release()
return rr.getRegister(0)
# coils
elif command.split("_")[0] == "Coil":
if command.split()[0] in self.coil_on_list:
wr = self.client.write_coil(self.coil_on_list[command.split()[0]], 1, unit=self.unit)
rr = self.client.read_coils(self.coil_on_list[command.split()[0]], 1, unit=self.unit)
elif command.split()[0] in self.coil_off_list:
wr = self.client.write_coil(self.coil_off_list[command.split()[0]], 0, unit=self.unit)
rr = self.client.read_coils(self.coil_off_list[command.split()[0]], 1, unit=self.unit)
elif command.split()[0] in self.coil_list and len(command.split()) > 1 and \
command.split()[1].isdigit():
wr = self.client.write_coil(self.coil_list[command.split()[0]], int(command.split()[1]),
unit=self.unit)
rr = self.client.read_coils(self.coil_list[command.split()[0]], 1, unit=self.unit)
self.client.close()
self.lock.release()
return rr.getBit(0)
# holding registers
elif command.split("_")[0] == "HReg":
if len(command.split()) > 1 and command.split()[1].isdigit():
wr = self.client.write_registers(self.command_list[command.split()[0]], [int(command.split()[1])],
unit=self.unit)
rr = self.client.read_holding_registers(self.command_list[command.split()[0]], 1, unit=self.unit)
self.client.close()
self.lock.release()
return rr.getRegister(0)
else:
print "Not correct command"
self.lock.release()
return "Not correct command"
示例15: __init__
# 需要导入模块: from pymodbus.client.sync import ModbusTcpClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusTcpClient import write_coil [as 别名]
class ModbusClient:
connected = False
def __init__(self, *kwargs):
self.connect()
def connect(self):
"""Open Modbus connection
"""
if not self.connected:
self.client = ModbusTcpClient("192.168.50.238", port=502)
self.client.connect()
self.connected = True
def transfer_bahn_nr(self, nr):
"""Send the number to PLC
:Parameters:
`nr`: int
number of bahn to build
:Returns:
bool, True if processing went well
"""
# Write number into memory
print "write number", nr
rq = self.client.write_register(532, nr)
# Set flag to true/false => PLC reads the value in memory
rq = self.client.write_coil(8481, True)
time.sleep(1)
rq = self.client.write_coil(8481, False)
return True
def start_build(self):
"""Start the build process
"""
rq = self.client.write_coil(8480, True)
time.sleep(0.5)
rq = self.client.write_coil(8480, False)
def read_active_bahn(self):
"""Read the current loaded bahn from the PLC
:Returns:
int, Number of bahn which is currently loaded
"""
rq = self.client.read_holding_registers(533, 1)
return int(rq.registers[0])
def is_machine_building(self):
"""
:Returns:
bool, True if machine is building
"""
def send_array(self, array):
"""Send the array to PLC
:Parameters:
`array`: list
list with dictionaries of cubes
:Returns:
bool, True if sending went well.
"""
if not self.connected:
print ("You don't have an open Modbus connection! - please restart server!")
return False
# check array size
AMMOUNT_OF_CUBES = 106
c = 0
for cube in array:
c += 1
if c != AMMOUNT_OF_CUBES:
print ("Array size isn't suitable. - size is: " + str(c) + " but it should be:" + str(AMMOUNT_OF_CUBES))
return False
# write cubes into PLC
lis = array
c = 0
for cube in lis:
try:
# 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
except:
print ("Can't send the cube data to PLC over Modbus")
print ("Cubes sent to PLC")
#.........这里部分代码省略.........