• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python hooks.call_hooks函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中modbus_tk.hooks.call_hooks函数的典型用法代码示例。如果您正苦于以下问题:Python call_hooks函数的具体用法?Python call_hooks怎么用?Python call_hooks使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



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

示例1: handle_request

    def handle_request(self, query, request):
        """
        when a request is received, handle it and returns the response pdu
        """
        request_pdu = ""
        try:
            #extract the pdu and the slave id
            (slave_id, request_pdu) = query.parse_request(request)

            #get the slave and let him executes the action
            if slave_id == 0:
                #broadcast
                for key in self._slaves:
                    self._slaves[key].handle_request(request_pdu, broadcast=True)
                return
            else:
                slave = self.get_slave(slave_id)
                response_pdu = slave.handle_request(request_pdu)
                #make the full response
                response = query.build_response(response_pdu)
                return response
        except Exception as excpt:
            call_hooks("modbus.Databank.on_error", (self, excpt, request_pdu))
            LOGGER.error("handle request failed: " + str(excpt))

        #If the request was not handled correctly, return a server error response
        func_code = 1
        if len(request_pdu) > 0:
            (func_code, ) = struct.unpack(">B", request_pdu[0])
        return struct.pack(">BB", func_code+0x80, defines.SLAVE_DEVICE_FAILURE)
开发者ID:apalkoff,项目名称:modbus-tk,代码行数:30,代码来源:modbus.py


示例2: _do_run

    def _do_run(self):
        """main function of the server"""
        try:
            #check the status of every socket
            response = ""
            request = ""
            read_bytes = "dummy"
            while read_bytes:
                read_bytes = self._serial.read(128)
                request += read_bytes

            #parse the request
            if request:
                retval = call_hooks("modbus_rtu.RtuServer.after_read", (self, request))
                if retval is not None:
                    request = retval
                response = self._handle(request)

                #send back the response
                retval = call_hooks("modbus_rtu.RtuServer.before_write", (self, response))
                if retval is not None:
                    response = retval

                if response:
                    self._serial.write(response)
                    time.sleep(self.get_timeout())

        except Exception as excpt:
            LOGGER.error("Error while handling request, Exception occurred: %s", excpt)
            call_hooks("modbus_rtu.RtuServer.on_error", (self, excpt))
开发者ID:pyplab,项目名称:modbus-tk,代码行数:30,代码来源:modbus_rtu.py


示例3: _write_multiple_coils

    def _write_multiple_coils(self, request_pdu):
        """execute modbus function 15"""
        call_hooks("modbus.Slave.handle_write_multiple_coils_request", (self, request_pdu))
        # get the starting address and the number of items from the request pdu
        (starting_address, quantity_of_x, byte_count) = struct.unpack(">HHB", request_pdu[1:6])

        expected_byte_count = quantity_of_x / 8
        if (quantity_of_x % 8) > 0:
            expected_byte_count += 1

        if (quantity_of_x <= 0) or (quantity_of_x > 1968) or (byte_count != expected_byte_count):
            # maximum allowed size is 1968 coils
            raise ModbusError(defines.ILLEGAL_DATA_VALUE)

        # look for the block corresponding to the request
        block, offset = self._get_block_and_offset(defines.COILS, starting_address, quantity_of_x)

        count = 0
        for i in xrange(byte_count):
            if count >= quantity_of_x:
                break
            fmt = "B" if self.unsigned else "b"
            (byte_value,) = struct.unpack(">" + fmt, request_pdu[6 + i])
            for j in xrange(8):
                if count >= quantity_of_x:
                    break

                if byte_value & (1 << j):
                    block[offset + i * 8 + j] = 1
                else:
                    block[offset + i * 8 + j] = 0

                count += 1
        return struct.pack(">HH", starting_address, count)
开发者ID:matrixx567,项目名称:modbus-tk,代码行数:34,代码来源:modbus.py


示例4: _do_close

 def _do_close(self):
     """Close the connection with the Modbus Slave"""
     if self._sock:
         call_hooks("modbus_tcp.TcpMaster.before_close", (self, ))
         self._sock.close()
         call_hooks("modbus_tcp.TcpMaster.after_close", (self, ))
         self._sock = None
开发者ID:4rc4n4,项目名称:modbus-tk-1,代码行数:7,代码来源:modbus_tcp.py


示例5: _do_open

 def _do_open(self):
     """Connect to the Modbus slave"""
     if self._sock:
         self._sock.close()
     self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     self.set_timeout(self.get_timeout())
     self._sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
     call_hooks("modbus_tcp.TcpMaster.before_connect", (self, ))
     self._sock.connect((self._host, self._port))
     call_hooks("modbus_tcp.TcpMaster.after_connect", (self, ))
开发者ID:ljean,项目名称:modbus-tk,代码行数:10,代码来源:modbus_tcp.py


示例6: _write_single_register

    def _write_single_register(self, request_pdu):
        """execute modbus function 6"""
        call_hooks("modbus.Slave.handle_write_single_register_request", (self, request_pdu))

        fmt = "H" if self.unsigned else "h"
        (data_address, value) = struct.unpack(">H" + fmt, request_pdu[1:5])
        block, offset = self._get_block_and_offset(defines.HOLDING_REGISTERS, data_address, 1)
        block[offset] = value
        # returns echo of the command
        return request_pdu[1:]
开发者ID:matrixx567,项目名称:modbus-tk,代码行数:10,代码来源:modbus.py


示例7: _write_single_coil

    def _write_single_coil(self, request_pdu):
        """execute modbus function 5"""

        call_hooks("modbus.Slave.handle_write_single_coil_request", (self, request_pdu))
        (data_address, value) = struct.unpack(">HH", request_pdu[1:5])
        block, offset = self._get_block_and_offset(defines.COILS, data_address, 1)
        if value == 0:
            block[offset] = 0
        elif value == 0xff00:
            block[offset] = 1
        else:
            raise ModbusError(defines.ILLEGAL_DATA_VALUE)
        # returns echo of the command
        return request_pdu[1:]
开发者ID:ljean,项目名称:modbus-tk,代码行数:14,代码来源:modbus.py


示例8: _handle

    def _handle(self, request):
        LOGGER.debug(self.get_log_buffer('-->', request))

        query = self._make_query()
        retval = call_hooks('modbus.Server.before_handle_request', (self, request))
        if retval:
            request = retval
        response = self._databank.handle_request(query, request)
        retval = call_hooks('modbus.Server.after_handle_request', (self, response))
        if retval:
            response = retval
        if response:
            LOGGER.debug(self.get_log_buffer('<--', response))
        return response
开发者ID:emdem,项目名称:ModbusSim,代码行数:14,代码来源:modbussim.py


示例9: handle_request

    def handle_request(self, request_pdu, broadcast=False):
        """
        parse the request pdu, makes the corresponding action
        and returns the response pdu
        """
        # thread-safe
        with self._data_lock:
            try:
                retval = call_hooks("modbus.Slave.handle_request", (self, request_pdu))
                if retval is not None:
                    return retval

                # get the function code
                (function_code,) = struct.unpack(">B", request_pdu[0])

                # check if the function code is valid. If not returns error response
                if function_code not in self._fn_code_map:
                    raise ModbusError(defines.ILLEGAL_FUNCTION)

                # if read query is broadcasted raises an error
                cant_be_broadcasted = (
                    defines.READ_COILS,
                    defines.READ_DISCRETE_INPUTS,
                    defines.READ_INPUT_REGISTERS,
                    defines.READ_HOLDING_REGISTERS,
                )
                if broadcast and (function_code in cant_be_broadcasted):
                    raise ModbusInvalidRequestError("Function %d can not be broadcasted" % function_code)

                # execute the corresponding function
                response_pdu = self._fn_code_map[function_code](request_pdu)
                if response_pdu:
                    if broadcast:
                        call_hooks("modbus.Slave.on_handle_broadcast", (self, response_pdu))
                        LOGGER.debug("broadcast: %s", get_log_buffer("!!", response_pdu))
                        return ""
                    else:
                        return struct.pack(">B", function_code) + response_pdu
                raise Exception("No response for function %d" % function_code)

            except ModbusError, excpt:
                LOGGER.debug(str(excpt))
                call_hooks("modbus.Slave.on_exception", (self, function_code, excpt))
                return struct.pack(">BB", function_code + 128, excpt.get_exception_code())
开发者ID:matrixx567,项目名称:modbus-tk,代码行数:44,代码来源:modbus.py


示例10: handle_request

 def handle_request(self, query, request):
     request_pdu = ''
     try:
         (slave_id, request_pdu) = query.parse_request(request)
         if slave_id == 0:
             for key in self._slaves:
                 self._slaves[key].handle_request(request_pdu,
                                                  broadcast=True)
             return
         else:
             slave = self.get_slave(slave_id)
             response_pdu = slave.handle_request(request_pdu)
             response = query.build_response(response_pdu)
             return response
     except Exception as e:
         call_hooks('modbus.Databank.on_error', (self, e, request_pdu))
         LOGGER.error('handle_request failed: ' + str(e))
     except:
         LOGGER.error('handle_request failed: unknown exception')
开发者ID:emdem,项目名称:ModbusSim,代码行数:19,代码来源:modbussim.py


示例11: _send

    def _send(self, request):
        """Send request to the slave"""
        retval = call_hooks("modbus_rtu.RtuMaster.before_send", (self, request))
        if retval is not None:
            request = retval

        self._serial.flushInput()
        self._serial.flushOutput()

        self._serial.write(request)
开发者ID:zerox1212,项目名称:WebModbus,代码行数:10,代码来源:modbus_rtu.py


示例12: _write_multiple_registers

    def _write_multiple_registers(self, request_pdu):
        """execute modbus function 16"""
        call_hooks("modbus.Slave.handle_write_multiple_registers_request", (self, request_pdu))
        # get the starting address and the number of items from the request pdu
        (starting_address, quantity_of_x, byte_count) = struct.unpack(">HHB", request_pdu[1:6])

        if (quantity_of_x <= 0) or (quantity_of_x > 123) or (byte_count != (quantity_of_x * 2)):
            # maximum allowed size is 123 registers in one reading
            raise ModbusError(defines.ILLEGAL_DATA_VALUE)

        # look for the block corresponding to the request
        block, offset = self._get_block_and_offset(defines.HOLDING_REGISTERS, starting_address, quantity_of_x)

        count = 0
        for i in xrange(quantity_of_x):
            count += 1
            fmt = "H" if self.unsigned else "h"
            block[offset + i] = struct.unpack(">" + fmt, request_pdu[6 + 2 * i : 8 + 2 * i])[0]

        return struct.pack(">HH", starting_address, count)
开发者ID:matrixx567,项目名称:modbus-tk,代码行数:20,代码来源:modbus.py


示例13: _handle

    def _handle(self, request):
        """handle a received sentence"""

        if self._verbose:
            LOGGER.debug(get_log_buffer("-->", request))

        # gets a query for analyzing the request
        query = self._make_query()

        retval = call_hooks("modbus.Server.before_handle_request", (self, request))
        if retval:
            request = retval

        response = self._databank.handle_request(query, request)
        retval = call_hooks("modbus.Server.after_handle_request", (self, response))
        if retval:
            response = retval

        if response and self._verbose:
            LOGGER.debug(get_log_buffer("<--", response))
        return response
开发者ID:matrixx567,项目名称:modbus-tk,代码行数:21,代码来源:modbus.py


示例14: _send

 def _send(self, request):
     """Send request to the slave"""
     retval = call_hooks("modbus_tcp.TcpMaster.before_send", (self, request))
     if retval is not None:
         request = retval
     try:
         flush_socket(self._sock, 3)
     except Exception as msg:
         #if we can't flush the socket successfully: a disconnection may happened
         #try to reconnect
         LOGGER.error('Error while flushing the socket: {0}'.format(msg))
         self._do_open()
     self._sock.send(request)
开发者ID:ljean,项目名称:modbus-tk,代码行数:13,代码来源:modbus_tcp.py


示例15: _do_run

    def _do_run(self):
        """main function of the server"""
        try:
            # check the status of every socket
            request = utils.to_data('')
            if self._block_on_first_byte:
                # do a blocking read for first byte
                self._serial.timeout = None
                try:
                    read_bytes = self._serial.read(1)
                    request += read_bytes
                except Exception as e:
                    self._serial.close()
                    self._serial.open()
                self._serial.timeout = self._timeout

            # Read rest of the request
            while True:
                try:
                    read_bytes = self._serial.read(128)
                    if not read_bytes:
                        break
                except Exception as e:
                    self._serial.close()
                    self._serial.open()
                    break
                request += read_bytes

            # parse the request
            if request:

                retval = call_hooks("modbus_rtu.RtuServer.after_read", (self, request))
                if retval is not None:
                    request = retval

                response = self._handle(request)

                # send back the response
                retval = call_hooks("modbus_rtu.RtuServer.before_write", (self, response))
                if retval is not None:
                    response = retval

                if response:
                    if self._serial.in_waiting > 0:
                        # Most likely master timed out on this request and started a new one
                        # for which we already received atleast 1 byte
                        LOGGER.warning("Not sending response because there is new request pending")
                    else:
                        self._serial.write(response)
                        self._serial.flush()
                        time.sleep(self.get_timeout())

                call_hooks("modbus_rtu.RtuServer.after_write", (self, response))

        except Exception as excpt:
            LOGGER.error("Error while handling request, Exception occurred: %s", excpt)
            call_hooks("modbus_rtu.RtuServer.on_error", (self, excpt))
开发者ID:ljean,项目名称:modbus-tk,代码行数:57,代码来源:modbus_rtu.py


示例16: _send

    def _send(self, request):
        """Send request to the slave"""
        retval = call_hooks("modbus_rtu.RtuMaster.before_send", (self, request))
        if retval is not None:
            request = retval

        self._serial.reset_input_buffer()
        self._serial.reset_output_buffer()

        self._serial.write(request)
        self._serial.flush()

        # Read the echo data, and discard it
        if self.handle_local_echo:
            self._serial.read(len(request))
开发者ID:ljean,项目名称:modbus-tk,代码行数:15,代码来源:modbus_rtu.py


示例17: _recv

    def _recv(self, expected_length=-1):
        """Receive the response from the slave"""
        response = ""
        read_bytes = "dummy"
        while read_bytes:
            read_bytes = self._serial.read(expected_length if expected_length > 0 else 1)
            response += read_bytes
            if expected_length >= 0 and len(response) >= expected_length:
                #if the expected number of byte is received consider that the response is done
                #improve performance by avoiding end-of-response detection by timeout
                break

        retval = call_hooks("modbus_rtu.RtuMaster.after_recv", (self, response))
        if retval is not None:
            return retval
        return response
开发者ID:pyplab,项目名称:modbus-tk,代码行数:16,代码来源:modbus_rtu.py


示例18: _recv

 def _recv(self, expected_length=-1):
     """
     Receive the response from the slave
     Do not take expected_length into account because the length of the response is
     written in the mbap. Used for RTU only
     """
     response = to_data('')
     length = 255
     while len(response) < length:
         rcv_byte = self._sock.recv(1)
         if rcv_byte:
             response += rcv_byte
             if len(response) == 6:
                 to_be_recv_length = struct.unpack(">HHH", response)[2]
                 length = to_be_recv_length + 6
         else:
             break
     retval = call_hooks("modbus_tcp.TcpMaster.after_recv", (self, response))
     if retval is not None:
         return retval
     return response
开发者ID:ljean,项目名称:modbus-tk,代码行数:21,代码来源:modbus_tcp.py


示例19: _recv

    def _recv(self, expected_length=-1):
        """Receive the response from the slave"""
        response = utils.to_data("")
        start_time = time.time() if self.use_sw_timeout else 0
        while True:
            read_bytes = self._serial.read(expected_length if expected_length > 0 else 1)
            if self.use_sw_timeout:
                read_duration = time.time() - start_time
            else:
                read_duration = 0
            if (not read_bytes) or (read_duration > self._serial.timeout):
                break
            response += read_bytes
            if expected_length >= 0 and len(response) >= expected_length:
                # if the expected number of byte is received consider that the response is done
                # improve performance by avoiding end-of-response detection by timeout
                break

        retval = call_hooks("modbus_rtu.RtuMaster.after_recv", (self, response))
        if retval is not None:
            return retval
        return response
开发者ID:ljean,项目名称:modbus-tk,代码行数:22,代码来源:modbus_rtu.py


示例20: _read_coils

 def _read_coils(self, request_pdu):
     """handle read coils modbus function"""
     call_hooks("modbus.Slave.handle_read_coils_request", (self, request_pdu))
     return self._read_digital(defines.COILS, request_pdu)
开发者ID:matrixx567,项目名称:modbus-tk,代码行数:4,代码来源:modbus.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python model.authenticate函数代码示例发布时间:2022-05-27
下一篇:
Python modbus_tk.LOGGER类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap