如何获得modbus_tk主站的IP?

时间:2016-10-25 03:44:17

标签: python modbus modbus-tk

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

slave.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))
''''''
''''''

0 个答案:

没有答案