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


Python ModbusSerialClient.write_coils方法代码示例

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


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

示例1: run_sync_client

# 需要导入模块: from pymodbus.client.sync import ModbusSerialClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusSerialClient import write_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)
#.........这里部分代码省略.........
开发者ID:bashwork,项目名称:pymodbus,代码行数:103,代码来源:synchronous_client.py

示例2: __init__

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

#.........这里部分代码省略.........
        
        
        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
        
        else:
            return ValueError
            
    
    def __writeData(self, reg, addr, data, encoding):
        """Write data to the MODBUS slave
        
        Called by 'dataHandler' in modbusClient.py
        
        Arguments:
        :param reg:      Modbus register to access (15 or 16)
        :param addr:     Address to start writing to
        :param data:     List of data to write to the device
        :param encoding: States whether data should be encoded first
        :type reg:       int
        :type addr:      int
        :type length:    int
        :type encoding: int
        
        :return:         success or failure exception
        """
        if reg == 15:
            try:
                co = self.client.write_coils(addr,data,unit=0x01)
            except ConnectionException:
                return ConnectionException
            
            if co.function_code != reg:
                return ModbusIOException
        
        elif reg == 16:
            if encoding == 1:
                data = self.__encodeData(data)
            
            try:
                hr = self.client.write_registers(addr,data,unit=0x01)
            except ConnectionException:
                return ConnectionException
            
            if hr.function_code != reg:
                return ModbusIOException
            
        else:
            return ValueError
        
    
    def __encodeData(self, data):
        """Encode data to 32bit float
        
        Function encodes a list of data passed to it into a 32 bit float
        packet that can be written directly to the MODBUS server table.
        
        Arguments:
        :param data: Float to be encoded
        :type data: list
        """
        builder = BinaryPayloadBuilder(endian=Endian.Little)
        try:
            for i in range(0,len(data)):
                builder.add_32bit_float(data[i])
        except TypeError:
            builder.add_32bit_float(data)
        return builder.to_registers()

    def __decodeData(self, data):
        """Decode MODBUS data to float
        
        Function decodes a list of MODBUS 32bit float data passed to it
        into its respective list of floats.
        
        Arguments:
        :param data: Data to be decoded
        :type data: list
        """
        returnData = [0]*(len(data)/2)
        decoder = BinaryPayloadDecoder.fromRegisters(data, endian=Endian.Little)
        for i in range(0,len(data)/2):
            returnData[i] = round(decoder.decode_32bit_float(),2)
        return returnData
开发者ID:FlaminMad,项目名称:processControl,代码行数:104,代码来源:modbusClient.py

示例3: byteswap

# 需要导入模块: from pymodbus.client.sync import ModbusSerialClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusSerialClient import write_coils [as 别名]
while True:
    result = client.read_input_registers(100, 6, unit=1)
    if result:
        #result.registers[0] = byteswap(result.registers[0])
        #result.registers[1] = byteswap(result.registers[1])
        #result.registers[2] = byteswap(result.registers[2])
        #result.registers[3] = byteswap(result.registers[3])
        #result.registers[4] = byteswap(result.registers[4])
        #result.registers[5] = byteswap(result.registers[5])
        decoder = BinaryPayloadDecoder.fromRegisters(result.registers, endian=Endian.Big)
        decoded = {
            'voltage': decoder.decode_32bit_float(),
            'pt100': decoder.decode_32bit_float(),
            'freq': decoder.decode_32bit_float()
        }
        print decoded
    client.write_coils(100, (1, 1, 1, 1, 1, 1), unit=1)
    result = client.read_discrete_inputs(100, 4, unit=1)

    print result.bits
    encoder = BinaryPayloadBuilder(endian=Endian.Big)
    encoder.add_32bit_float(20)
    encoder.add_32bit_float(80)
    buf = encoder.build()
    #buf[0] = charswap(buf[0])
    #buf[1] = charswap(buf[1])
    #buf[2] = charswap(buf[2])
    #buf[3] = charswap(buf[3])
    client.write_registers(100, buf, unit=1, skip_encode=True)
    #break
开发者ID:gastonfeng,项目名称:jlinkpy,代码行数:32,代码来源:kc1110.py

示例4: DemeterClient

# 需要导入模块: from pymodbus.client.sync import ModbusSerialClient [as 别名]
# 或者: from pymodbus.client.sync.ModbusSerialClient import write_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>"
#.........这里部分代码省略.........
开发者ID:szaffarano,项目名称:demeter,代码行数:103,代码来源:utils.py


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