Python实现模拟Modbus Master遍历测试Modbus Slave IP是否连通

项目需求,又来搞一下python。


需要模拟Modbus Master连接底层设备,测试所有配置的工厂的IP是否通,其实就是模拟Modbus Master和Modbus Slave之间的通信。因为底层设备不稳定,需要每天测一遍所有IP,共差不多200个IP,当然要自动化脚本实现。突然很理解之前的Manager对自动化的热衷。


# encoding: utf-8 

import sys
import struct
import modbus_tk.defines as cst
import modbus_tk.modbus
import modbus_tk.modbus_tcp
import string
import time
import threading
import logging
import logging.handlers
import socket

# 对logging级别的分类
# 默认的等级是WARNING,也就是说logging函数在没有特别配置的前提下只追踪比WARNING程度更严重的异常
# LEVELS={'notset':logging.DEBUG,  
  
#         'debug':logging.DEBUG,  
  
#         'info':logging.INFO,  
  
#         'warning':logging.WARNING,  
  
#         'error':logging.ERROR,  
  
#         'critical':logging.CRITICAL} 


# define the log file, file mode and logging level
logging.basicConfig(filename='testIP.log', filemode="w", level=logging.debug)

# 通过modbus_tk封装的logger,控制台和文本都会有输出,而logging输出只将log输出到文本,控制台不会有打印
fmt = '%(asctime)s - %(filename)s:%(lineno)s - %(name)s - %(message)s'
logger = modbus_tk.utils.create_logger(name="console", record_format=fmt)

class MyThread1(threading.Thread):
    
    def __init__(self, name, counter, host):
        threading.Thread.__init__(self)
        self.name = name
        self.counter = counter
        self.host = host
    def run(self):
        #print "Starting " + self.name

        # 连接MODBUS TCP从机,host参数为slave的IP地址
        master = modbus_tk.modbus_tcp.TcpMaster(host=self.host)
        master.set_timeout(3.0)
        try:
            # 读保持寄存器
            # logger.info(master.execute(1, cst.READ_HOLDING_REGISTERS, 0, 26))
            # logger.info(self.host + " is connected")
            # 此处用logging,防止控制台大面积打印,把所有内容都打印到log文件,只把exception打印到控制台
            logging.info(master.execute(1, cst.READ_HOLDING_REGISTERS, 0, 26))
            logging.info(self.host + " is connected")
        except socket.timeout:   # connection timeout exception
            logger.info((self.host + " is not connected=========="))
        except Exception, e:   # 捕获除了连接异常之外的其它异常
            print repr(e)
            logger.info(self.host + "===============Exception====================")
        finally:
            print "Exiting " + self.name


# 启用多线程,可同时对for循环中的每个IP地址进行连接测试,而避免如果一个IP连接不通则整个for循环就中途停止
for i in range(100, 125):
    hostIP = "192.168.251." + str(i)
    thread1 = MyThread1("Thread-"+str(i), (i-99), hostIP)
    thread1.start()

for i in range(130, 150):
    hostIP = "192.168.251." + str(i)
    thread1 = MyThread1("Thread-"+str(i), (i-99), hostIP)
    thread1.start()

for i in range(10, 35):
    hostIP = "192.168.251." + str(i)
    thread1 = MyThread1("Thread-"+str(i), (i-99), hostIP)
    thread1.start()

for i in range(60, 72):
    hostIP = "192.168.251." + str(i)
    thread1 = MyThread1("Thread-"+str(i), (i-99), hostIP)
    thread1.start()

for i in range(40, 49):
    hostIP = "192.168.251." + str(i)
    thread1 = MyThread1("Thread-"+str(i), (i-99), hostIP)
    thread1.start()

for i in range(50, 56):
    hostIP = "192.168.251." + str(i)
    thread1 = MyThread1("Thread-"+str(i), (i-99), hostIP)
    thread1.start()

for i in range(75, 97):
    hostIP = "192.168.251." + str(i)
    thread1 = MyThread1("Thread-"+str(i), (i-99), hostIP)
    thread1.start()


注释已经很详细啦,现在忘性大~

再说明一点,和Modbus相关的代码其实就下面这三行,其他都是用来实现遍历,多进程和日志打印。

master = modbus_tk.modbus_tcp.TcpMaster( host= self.host)
master.set_timeout( 3.0)
master.execute( 1, cst.READ_HOLDING_REGISTERS, 0, 26)



你可能感兴趣的:(modbus,python)