当前位置: 首页>>代码示例>>Python>>正文


Python ModbusSerialClient.execute方法代码示例

本文整理汇总了Python中pymodbus.client.sync.ModbusSerialClient.execute方法的典型用法代码示例。如果您正苦于以下问题:Python ModbusSerialClient.execute方法的具体用法?Python ModbusSerialClient.execute怎么用?Python ModbusSerialClient.execute使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在pymodbus.client.sync.ModbusSerialClient的用法示例。


在下文中一共展示了ModbusSerialClient.execute方法的6个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: main

# 需要导入模块: from pymodbus.client.sync import ModbusSerialClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusSerialClient import execute [as 别名]
def main():
  if len(sys.argv) != 4:
    print(
"""Usage: ./orno_modbus.py serial_port device_address target_device_address
Example: ./orno_modbus.py /dev/ttyUSB0 1 11

If you have only one device you can set the device_address to 0 to change its address.
""")
    sys.exit(0)

  port = sys.argv[1]
  address = int(sys.argv[2])
  target_address = int(sys.argv[3])

  client = ModbusClient(method="rtu", port=port, baudrate=9600)
  client.connect()

  request = SendOrnoPassword('00000000', unit=address)
  client.execute(request)

  response = client.write_registers(15, [target_address], unit=address)
  if response:
    if address:
      print "Success. Changed address from %d to %d." % (address, target_address)
    else:
      print "Success. Changed address to %d." % (target_address)
  else:
    print "Address change failed"

  client.close()
开发者ID:PeWu,项目名称:orno_modbus,代码行数:32,代码来源:orno_modbus.py

示例2: __init__

# 需要导入模块: from pymodbus.client.sync import ModbusSerialClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusSerialClient import execute [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
开发者ID:davcx,项目名称:epsolar-tracer,代码行数:62,代码来源:client.py

示例3: __init__

# 需要导入模块: from pymodbus.client.sync import ModbusSerialClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusSerialClient import execute [as 别名]
class ModbusSlaveReader:

    """
    This class uses the pymodbus library to communicate with modbus slaves
    via serial connection.
    """

    def __init__(self, serial_socket):
        self.logger = logging.getLogger(__name__)

        self.client = ModbusClient(method='rtu', port=serial_socket, timeout=1)

        modbus_client_filter = ModbusClientFilter()
        logging.getLogger("pymodbus.client.sync").addFilter(
            modbus_client_filter)

    def read_register_value(self, slave, register):
        value = self.client.read_holding_registers(register, 1, unit=slave)
        self.logger.debug('value read from modbus slave: ' + value)
        return value

    def check_connection(self):
        """Before a timer is made in the ReadSensorScheduler to read the data
        from the modbus slaves, the connection with the modbus client is
        checked.
        """
        try:
            self.client.connect()
        except:
            self.logger.warning(
                'Unable to connect to modbus network, check serial port')
            raise
            return False

        try:
            rq = ReportSlaveIdRequest()
            rr = self.client.execute(rq)
            assert(rr is None)
            self.logger.warning('Able to see modbus master on network')
            return True
        except:
            self.logger.warning('Unable to see modbus master on network')
            return False
开发者ID:jonathandb,项目名称:datalogger,代码行数:45,代码来源:modbus_slave_reader.py

示例4: SenseAirDevice

# 需要导入模块: from pymodbus.client.sync import ModbusSerialClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusSerialClient import execute [as 别名]
class SenseAirDevice(object):

	def __init__(self):
		#---------------------------------------------------------------------------#
		# This will simply send everything logged to console
		#---------------------------------------------------------------------------#
		logging.basicConfig()
		log = logging.getLogger()
		log.setLevel(logging.DEBUG)
		self.client = None

	def connect(self, deviceName):
	  self.client = ModbusSerialClient(method='rtu',port=deviceName,stopbits=1, bytesize=8, baudrate=9600, timeout=0.2)
	  if not self.client.connect():
	      rospy.logerr("Unable to connect to %s", device)
	      return False
	  return True

	def close(self):
		self.client.close()

	# Not working right now
	def getDeviceIdentification(self, objectId):

		rq = ReadDeviceInformationRequest(read_code=4, object_id=objectId, unit=0xFE)
		#rospy.loginfo("encoded: %h", encoded[0])
		rr = self.client.execute(rq)
		print rr

		return ""
		if rr is None:
			rospy.logerr("No response from device")
			return None

		if rr.function_code < 0x80:                 # test that we are not an error
			return  rr.information[0]
			#vendor_name = rr.information[0]
			#product_code = rr.information[1]
			#code_revision = rr.information[2]

			#rospy.loginfo("vendor: %s", vendor_name)
			#rospy.loginfo("product code: %s", product_code)
			#rospy.loginfo("revision: %s", code_revision)

		else:
			rospy.logwarn("error reading device identification: %h", rr.function_code)


	def getVendor(self):

		vendor = self.getDeviceIdentification(0)
		print vendor

	def readCO2(self):
		response = self.client.read_input_registers(address=3, count=1, unit=0xFE )
		return response.getRegister(0)

	def readTemperature(self):
		response = self.client.read_input_registers(address=4, count=1, unit=0xFE )
		return response.getRegister(0)*100.0

	def sendCommand(self, data):
	  #make sure data has an even number of elements
	  if(len(data) % 2 == 1):
	     data.append(0)

	  #Initiate message as an empty list
	  message = []

	  #Fill message by combining two bytes in one register
	  for i in range(0, len(data)/2):
	     message.append((data[2*i] << 8) + data[2*i+1])

	  #To do!: Implement try/except
	  self.client.write_registers(0x03E8, message, unit=0x0009)


	def getStatus(self, numBytes):
	  """Sends a request to read, wait for the response and returns the Gripper status. The method gets the number of bytes to read as an argument"""
	  numRegs = int(ceil(numBytes/2.0))

	  #To do!: Implement try/except
	  #Get status from the device
	  response = self.client.read_holding_registers(0x07D0, numRegs, unit=0x0009)

	  #Instantiate output as an empty list
	  output = []

	  #Fill the output with the bytes in the appropriate order
	  for i in range(0, numRegs):
	     output.append((response.getRegister(i) & 0xFF00) >> 8)
	     output.append( response.getRegister(i) & 0x00FF)

	  #Output the result
	  return output
开发者ID:tu-darmstadt-ros-pkg,项目名称:hector_senseair_s8_driver,代码行数:97,代码来源:sense_air_device.py

示例5: ClearCountersRequest

# 需要导入模块: from pymodbus.client.sync import ModbusSerialClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusSerialClient import execute [as 别名]
#
# request  = ClearCountersRequest()
# response = client.execute(request)
# if isinstance(response, ClearCountersResponse):
#     ... do something with the response
#
#
# What follows is a listing of all the supported methods. Feel free to
# comment, uncomment, or modify each result set to match with your reference.
#---------------------------------------------------------------------------# 

#---------------------------------------------------------------------------# 
# information requests
#---------------------------------------------------------------------------# 
rq = ReadDeviceInformationRequest(unit=1)
rr = client.execute(rq)
#assert(rr == None)                             # not supported by reference
assert(rr.function_code < 0x80)                 # test that we are not an error
assert(rr.information[0] == b'Pymodbus')  # test the vendor name
assert(rr.information[1] == b'PM')          # test the product code
assert(rr.information[2] == b'1.0')     # test the code revision

rq = ReportSlaveIdRequest(unit=1)
rr = client.execute(rq)
# assert(rr == None)                              # not supported by reference
#assert(rr.function_code < 0x80)                # test that we are not an error
#assert(rr.identifier  == 0x00)                 # test the slave identifier
#assert(rr.status  == 0x00)                     # test that the status is ok

rq = ReadExceptionStatusRequest(unit=1)
rr = client.execute(rq)
开发者ID:jackjweinstein,项目名称:pymodbus,代码行数:33,代码来源:synchronous-client-ext.py

示例6: execute_extended_requests

# 需要导入模块: from pymodbus.client.sync import ModbusSerialClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusSerialClient import execute [as 别名]
def execute_extended_requests():
    # ------------------------------------------------------------------------# 
    # 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.
    #
    # It should be noted that you can supply an ipv4 or an ipv6 host address 
    # for both the UDP and TCP clients.
    # ------------------------------------------------------------------------# 
    client = ModbusClient(method='rtu', port="/dev/ttyp0")
    # client = ModbusClient('127.0.0.1', port=5020)
    client.connect()

    # ----------------------------------------------------------------------- # 
    # extra requests
    # ----------------------------------------------------------------------- # 
    # If you are performing a request that is not available in the client
    # mixin, you have to perform the request like this instead::
    #
    # from pymodbus.diag_message import ClearCountersRequest
    # from pymodbus.diag_message import ClearCountersResponse
    #
    # request  = ClearCountersRequest()
    # response = client.execute(request)
    # if isinstance(response, ClearCountersResponse):
    #     ... do something with the response
    #
    #
    # What follows is a listing of all the supported methods. Feel free to
    # comment, uncomment, or modify each result set to match with your ref.
    # ----------------------------------------------------------------------- # 

    # ----------------------------------------------------------------------- # 
    # information requests
    # ----------------------------------------------------------------------- #
    log.debug("Running ReadDeviceInformationRequest")
    rq = ReadDeviceInformationRequest(unit=UNIT)
    rr = client.execute(rq)
    print(rr)
    # assert(rr == None)              # not supported by reference
    # assert (rr.function_code < 0x80)  # test that we are not an error
    # assert (rr.information[0] == b'Pymodbus')  # test the vendor name
    # assert (rr.information[1] == b'PM')  # test the product code
    # assert (rr.information[2] == b'1.0')  # test the code revision

    log.debug("Running ReportSlaveIdRequest")
    rq = ReportSlaveIdRequest(unit=UNIT)
    rr = client.execute(rq)
    print(rr)
    # assert(rr == None)                        # not supported by reference
    # assert(rr.function_code < 0x80)           # test that we are not an error
    # assert(rr.identifier  == 0x00)            # test the slave identifier
    # assert(rr.status  == 0x00)                # test that the status is ok

    log.debug("Running ReadExceptionStatusRequest")
    rq = ReadExceptionStatusRequest(unit=UNIT)
    rr = client.execute(rq)
    print(rr)
    # assert(rr == None)                        # not supported by reference
    # assert(rr.function_code < 0x80)           # test that we are not an error
    # assert(rr.status == 0x55)                 # test the status code

    log.debug("Running GetCommEventCounterRequest")
    rq = GetCommEventCounterRequest(unit=UNIT)
    rr = client.execute(rq)
    print(rr)
    # assert(rr == None)                       # not supported by reference
    # assert(rr.function_code < 0x80)          # test that we are not an error
    # assert(rr.status == True)                # test the status code
    # assert(rr.count == 0x00)                 # test the status code

    log.debug("Running GetCommEventLogRequest")
    rq = GetCommEventLogRequest(unit=UNIT)
    rr = client.execute(rq)
    print(rr)
    # assert(rr == None)                       # not supported by reference
    # assert(rr.function_code < 0x80)          # test that we are not an error
    # assert(rr.status == True)                # test the status code
    # assert(rr.event_count == 0x00)           # test the number of events
    # assert(rr.message_count == 0x00)         # test the number of messages
    # assert(len(rr.events) == 0x00)           # test the number of events

    # ------------------------------------------------------------------------# 
    # diagnostic requests
    # ------------------------------------------------------------------------#
    log.debug("Running ReturnQueryDataRequest")
    rq = ReturnQueryDataRequest(unit=UNIT)
    rr = client.execute(rq)
    print(rr)
    # assert(rr == None)                      # not supported by reference
    # assert(rr.message[0] == 0x0000)         # test the resulting message

    log.debug("Running RestartCommunicationsOptionRequest")
    rq = RestartCommunicationsOptionRequest(unit=UNIT)
    rr = client.execute(rq)
    print(rr)
    # assert(rr == None)                     # not supported by reference
    # assert(rr.message == 0x0000)           # test the resulting message
#.........这里部分代码省略.........
开发者ID:morlandi,项目名称:pymodbus,代码行数:103,代码来源:synchronous_client_ext.py


注:本文中的pymodbus.client.sync.ModbusSerialClient.execute方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。