0

我基于 modbus_tk(https://github.com/ljean/modbus-tk )编写了一个 slave.py(server )。然后,我用客户端工具连接slave,就OK了。现在,我想获得哪个主(客户端)访问我,我想获得源 IP 和端口。我在 TcpServer(server) 类 modbus_tcp.py 的函数 _do_run(self) 中找到关键点'client, address = self._sock.accept()'。我尝试了一些方法,但没有奏效。

奴隶.py

import modbus_tk
import modbus_tk.modbus_tcp as modbus_tcp
import modbus_tk.defines as mdef
import threading
import sys
from lxml import etree

logger = modbus_tk.utils.create_logger(name='console', record_format='%(message)s')
server = modbus_tcp.TcpServer(port=502,address='0.0.0.0')
class Modbus_server(object):
    def main(self):
        try:
            logger.info("running...")
            logger.info("enter 'quit' for closing the server")
            server.start()
            self.config_slaves()
            while True:
                cmd = sys.stdin.readline()
                if cmd.find('quit')==0:
                    #when input"quit",the program exit!
                    sys.stdout.write('bye-bye\r\n')
                    sys.exit(0) 
        finally:
            server.stop()
    #get slave configuration
    def config_slaves(self):
        dom = etree.parse('modbus.xml')
        slaves = dom.xpath('//modbus/slaves/*')
        try:
            for s in slaves:
                slave_id = int(s.attrib['id'])
                slave = server.add_slave(slave_id)
                logger.debug('Added slave with id %s.', slave_id)
                for b in s.xpath('./blocks/*'):
                    name = b.attrib['name']
                    request_type = eval('mdef.' + b.xpath('./type/text()')[0])
                    start_addr = int(b.xpath('./starting_address/text()')[0])
                    size = int(b.xpath('./size/text()')[0])
                    slave.add_block(name, request_type, start_addr, size)
                    logger.debug(
                        'Added block %s to slave %s. '
                        '(type=%s, start=%s, size=%s)',
                        name, slave_id, request_type, start_addr, size)
            logger.info('modbus initialized')
        except (Exception) as e:
            logger.info(e)
modbus=Modbus_server()
modbus.main()`

modbus_tcp.py

''''''
......
def _do_run(self):
        """called in a almost-for-ever loop by the server"""
        #check the status of every socket
        inputready = select.select(self._sockets, [], [], 1.0)[0]

        #handle data on each a socket
        for sock in inputready:
            try:
                if sock == self._sock:
                    # handle the server socket
                    client, address = self._sock.accept()
                    client.setblocking(0)

                    LOGGER.info("%s is connected with socket %d...", str(address), client.fileno())
                    self._sockets.append(client)
                    call_hooks("modbus_tcp.TcpServer.on_connect", (self, client, address))
''''''
''''''
4

0 回答 0