def test(com, times, logfile): log("{} - test started.".format(nowtimestr()), "w") count = 0 plc.write_coil(1, 0xfc00, 1) set_port(comid, 115200, 8, 1, 'N') while count <= times: count += 1 x = isonline(com, True) if x is 1: logline = "{} - hmi online success. count = {}".format( nowtimestr(), count) log(logfile, logline) plc.write_coil(1, 0xfc00, 0) print("{} - hmi powered off".format(nowtimestr())) if x is 0: log("{} hmi online err.".format(nowtimestr())) break x = isonline(com, False) if x is 2: logline = "{} - hmi offline success. count = {}".format( nowtimestr(), count) log(logline) plc.write_coil(1, 0xfc00, 1) print("{} - hmi powered on".format(nowtimestr())) if x is 0: log("{} hmi offline err.".format(nowtimestr())) break log("{} - test finished.".format(nowtimestr()))
def isonline(com: str, flag: bool): test_count = 0 while test_count <= 5000: test_count += 1 try: hmiport = set_port(com, 115200, 8, 1, 'N') s = hmiport.readline() if s: if b'ngrok-----' in s: print(s) l = s.strip().split(b" ") if len(l) == 3: if l[1] == b' ngrok-----FD_ISSET( it1->first, &readSet )&&tempinfo->isconnect==1----' \ b'tempinfo->istype=3': if flag: loginfo = l[0][-12:-1].decode( ) + " hmi online = True" log(loginfo) return 1 if l[1] == b' ngrok-----err------------socklist.count(mainsock)!=0&&mainsock!=0': if not flag: loginfo = l[0][-12:-1].decode( ) + " hmi online = False" log(loginfo) return 2 except Exception as e: print("{} - read hmi port fail. testing stopped: {}".format( nowtimestr(), e)) break return 0
def start(): testcount = 0 errcount = 0 excepcount = 0 while testcount <= 10000: try: testcount += 1 hmi.write_register(1, 0, testcount) hmi.write_register(1, 1, errcount) data = data_generator() write(data) writedata = [[data[0]] * 100, [data[1]] * 100, [data[2]] * 100] time.sleep(5) set_power(0) time.sleep(5) set_power(1) time.sleep(10) readdata = read() result = compare(writedata, readdata) if result is True: pass else: errcount += 1 print( "{} - test result: {}. {} times error in {} times test. exception count={}" .format(nowtimestr(), result, errcount, testcount, excepcount)) except Exception as e: print("exception happens. {}".format(e)) excepcount += 1 continue
def main(mstplc, msthmi, station): err_count = 0 j = 0 while j <= 20000: j += 1 beijing_timestamp = get_beijing_timestamp() # 北京时间写入hmi timevalues = timestamp2timevalues(beijing_timestamp) device_timevalues = [0] + [0] * 5 beijing_timestamp = 0 try: msthmi.write_registers(station, 10, list(timevalues)) sleep(0.1) msthmi.write_coil(station, 10000, 1) sleep(5) mstplc.write_coil(1, 0xfc00, 0) sleep(5) mstplc.write_coil(1, 0xfc00, 1) sleep(10) # 读回对比 beijing_timestamp = get_beijing_timestamp() # 需要重新获取北京时间 device_timevalues = read_device_time_values(msthmi, station) except Exception as e: print(e) beijing_timestr = timestamp2timestr(beijing_timestamp) device_timestamp = get_device_timestamp(device_timevalues) device_timestr = timestamp2timestr(device_timestamp) err = device_timestamp - beijing_timestamp if err >= 5 or err <= -5: is_err = True else: is_err = False if is_err: err_count += 1 fmt_log = [ nowtimestr(), beijing_timestr, str(beijing_timestamp), device_timestr, str(device_timestamp), str(err), str(is_err), str(err_count), str(j) ] log = ", ".join(fmt_log) log = "".join([log, "\n"]) # print("" # "北京时间:{} -- 时间戳:{}\n" # "设备时间:{} -- 时间戳:{}" # "".format(beijing_timestr, beijing_timestamp, device_timestr, device_timestamp)) with open("hmi rtc test log.csv".format(station), "a", encoding="utf-8") as f: f.write(log) print(log)
def start_tst(): portpplc = ("COM9", 9600, 8, 1, "O") portphmi = ("COM7", 9600, 8, 1, "O") masterplc = ModbusRtu(portpplc) masterhmi = ModbusRtu(portphmi) station_id = 1 head = "{}, {}, {}, {}, {}, {}, {}, {}, {}\n".format( "logtime", "bj_time", "bj_timestamp", "dev_time", "dev_timestamp", "error(sec.dev-bj)", "is_error?", "err_count", "total_count") with open("hmi rtc test log.csv", "w", encoding="utf-8") as f: f.write("{} slave {} test log\n".format(nowtimestr(), station_id)) print("start logging") f.write(head) print(head) masterplc.write_coils(1, 0xfc00, [1, 1]) main(masterplc, masterhmi, station_id)
def check_penetration(app_plc): """ 利用PLCEditor通讯测试确认穿透是否成功, 测试准备:打开软件,移动窗口到屏幕右半边。 新建文件(勿保存),打开通讯测试对话框, 确认串口号 :param app_plc: 已绑定的PLCEditor App对象 :return: """ global count_fail global count_success global total_count global current_num win_comm = app_plc["通讯设置"] # win_comm["USB 连接(最好使用屏蔽良好的线缆)"].click() # sleep(1) win_comm["串口连接"].click() win_comm["COM端口ComboBox"].select( "{}-Virtual Serial Port 8 (Eltima Software)".format(portname)) win_comm["通讯测试"].click() if app_plc["Wecon PLC Editor"].exists(10): if app_plc["Wecon PLC Editor"]['与LX3V连接成功!'].exists(1): count_success += 1 elif app_plc["Wecon PLC Editor"]['无法与PLC通讯!'].exists(1): count_fail += 1 else: print("通讯测试信息异常") app_plc["Wecon PLC Editor"].print_control_identifiers() count_fail += 1 app_plc["Wecon PLC Editor"]["确定"].click() line = "{} 完成进度 {}/{},通讯成功次数 {}, 通讯失败次数 {}".format(nowtimestr(), current_num, total_count, count_success, count_fail) with open("盒子穿透次数记录.log", 'a') as f: f.write(line + "\n") print(line)
def get_beijing_timestamp(): """ 获取标准北京时间 """ url = "http://api.m.taobao.com/rest/api3.do?api=mtop.common.getTimestamp" # get方法返回数据格式: # {'ret': ['SUCCESS::接口调用成功'], 'v': '*', 'api': 'mtop.common.getTimestamp', 'data': {'t': '1545807646734'}} bj_timestamp = 0 try: get_data = req.get(url).json() if get_data["ret"][0] == "SUCCESS::接口调用成功": bj_timestamp = get_data["data"]["t"] bj_timestamp = float(bj_timestamp[:10] + "." + bj_timestamp[-3:]) # 注意,web获取的时间戳单位为毫秒 else: pass except Exception as e: print(nowtimestr()) print("error, get beijing time fail from url({}). detail: {}".format( url, e)) if debug: print("get the beijing timestamp:", bj_timestamp) return bj_timestamp
if __name__ == '__main__': ip = 'mqtt.v-box.net' # s = input("请输入ping指令目标ip(默认测试指令为ping {} -n 1):".format(ip)) print(""" This is a little tool to monitor network connectivity by running a single "ping" command. It will log some returned info to a .log file in current folder when started. """) s = input("Please type the domain or IP address to ping to(default, {}) and press ENTER to start:".format(ip)) if s == "": ping = "ping {} -n 1".format(ip) else: ping = "ping {} -n 1".format(s) with open("{}.log".format(ping), 'w', encoding='utf-8') as f: f.write(ping+'\n'+'start time: {}\n'.format(nowtimestr())) print('command: {}'.format(ping)) print('start time: {}'.format(nowtimestr())) while True: try: time.sleep(5) file = os.popen(ping) log = "" LINES = file.readlines() for line in LINES: line = line.strip() if line == '请求超时。' or line == 'Request timed out.': log = "{}, 超时".format(nowtimestr()) if line == '请求超时。' else "{}, timed out.".format(nowtimestr()) print(log) continue elif line.split(' ')[0] == '来自' or line.split(' ')[0] == 'Reply':
from pywinauto import application from time import sleep from mylog import mylog from make_time_formated import nowtimestr with open("log.txt", "w", encoding="utf-8") as f: f.write("测试记录\n") downloadexepath = input("请输入download.exe完整路径\n>") if downloadexepath[0] == '"' and downloadexepath[-1] == '"': pi_path = downloadexepath[1:-1] app = application.Application() app_plceditor = app.connect(title="Wecon PLC Editor - 软元件监视-1") win = app_plceditor["修改软元件值"] app_download = app.start(downloadexepath) mylog("{}, 测试开始".format(nowtimestr())) def start(): win["ON"].click() sleep(20) app_download.top_window()[r"更新HMI时间(&T)"].click() sleep(1) app_download.top_window()["是"].click() sleep(1) app_download.top_window()["确定"].click() sleep(3) win["OFF"].click() sleep(2) if __name__ == '__main__':
#!/usr/bin/python # -*- coding:utf-8 -*- # ----------------------------------------------------------- # File Name: hmi_auto_restart_via_plc # Author: fan # date: 2019/1/5 # 通过hmi串口是否有数据发出,判断hmi是否启动正常,若启动正常则下电hmi延时并重启hmi,继续测试;若hmi未启动则停止测试并报告问题 # ----------------------------------------------------------- from modbus_rtu_master import ModbusRtu import time from make_time_formated import nowtimestr from watchcom import set_port, open_port, close_port, read_correct print("{} - test started.".format(nowtimestr())) hmiport = set_port('com9', 115200, 8, 1, 'N') plcportporp = ("com7", 9600, 8, 1, "N") plc = ModbusRtu(plcportporp) plc.write_coil(1, 0xfc00, 1) print("{} - hmi powered on".format(nowtimestr())) readbytes = b'\x0201440AM008253\x03' or b'\x02014603R0519081\x03' i = 0 while i <= 20000: i += 1 x = 0 try: while x < 30: try: x = read_correct(hmiport, readbytes) if x: print("{} - read hmi port success. test times: {}".format(nowtimestr(), i)) x = 30 # 跳出循环
start_penetration() app_plc = application.Application() app_plc.connect(title="Wecon PLC Editor - 梯形图(写入)") print("正在检查通讯") check_penetration(app_plc) end_penetration() print("结束穿透,盒子将重启(60)") sleep(60) if __name__ == '__main__': count_success = 0 count_fail = 0 input("测试准备: 打开V-BOX配置工具,启用并配置好虚拟串口。\n" "将画面定位到盒子 - 远程下载,设置唯一一组串口设置记录。\n" "PLCEditor新建工程(勿保存文件),然后打开通讯口测试对话框\n" "按任意键继续...") portname = input("请输入虚拟串口编号(如COM22、COM43):\n") total_count = input("请输入测试次数:\n") with open("盒子穿透次数记录.log", 'w') as f: f.write("测试开始时间: {}\n".format(nowtimestr())) current_num = 1 while current_num <= int(total_count): try: main() except Exception as e: print(e) input() current_num += 1 input("测试结束,请确认数据,按任意键退出...")
print("提示:文件路径可通过拖动文件到光标处快速输入文件路径(引号可不删除。" "在WINDOWS 10系统上,可能需要以管理员身份运行程序并手动输入参数。)") pi_path = input("请输入PIStudio HMIEditor.exe文件路径\n:") project_path = input("请输入工程.pi文件路径\n:") n = input("请输入测试次数\n:") n = int(n) interval = input("请输入编译等待时间(秒)\n:") interval = int(interval) if pi_path[0] == '"' and pi_path[-1] == '"': pi_path = pi_path[1:-1] if project_path[0] == '"' and project_path[-1] == '"': project_path = project_path[1:-1] mylog("{}, 开始测试".format(nowtimestr())) app = application.Application() app.start(pi_path) win = app.top_window() win.maximize() # 窗口最大化 # win.minimize() # 窗口最小化 sleep(5) click(*CLICK_LOCATION["打开工程"]) win_open = app["打开"] win_open[u'文件名(&N):Edit'].SetText(project_path) win_open['打开(&O)Button'].Click() sleep(3) win = app.top_window() i = 1 while i <= n: