updata file
This commit is contained in:
26
ReadMe.txt
Normal file
26
ReadMe.txt
Normal file
@@ -0,0 +1,26 @@
|
||||
|
||||
|
||||
|
||||
2023.4.7
|
||||
实现文件上传下载到开发板,经实验发现强制设置网卡速率为10M时上传文件卡死
|
||||
只要关闭自动协商,设置为100m也会延长传输时间
|
||||
实现udp命令批量发送
|
||||
get(),put()函数加入异常捕获
|
||||
shell命令格式化输出,支持交互式命令
|
||||
2023.4.11
|
||||
ftp.py get函数可以扫描文件夹
|
||||
2023.4.16
|
||||
updata.py 实现文件批量传输,发送升级小板的命令
|
||||
2023.4.17
|
||||
实现进度条显示、mcu在线状态查询
|
||||
2023.4.18
|
||||
可以手动添加ip地址
|
||||
可以发送设备树文件
|
||||
2023.4.20
|
||||
文件发送完成后发送sync指令
|
||||
2023.5.11
|
||||
上传文件添加进度信号
|
||||
打包为exe文件
|
||||
D:\Python\Python38-32\Scripts\pyinstaller.exe -F updata.py
|
||||
使用新的图标
|
||||
可以手动添加文件
|
306
ftp.py
Normal file
306
ftp.py
Normal file
@@ -0,0 +1,306 @@
|
||||
|
||||
|
||||
import paramiko
|
||||
from ftplib import FTP
|
||||
import os
|
||||
import threading
|
||||
import udp
|
||||
import sys
|
||||
import time
|
||||
import stat
|
||||
from PyQt5.QtCore import *
|
||||
|
||||
STR_RED="\033[1;31m"
|
||||
STR_BLUE="\033[1;34m"
|
||||
STR_END="\033[0m"
|
||||
|
||||
|
||||
|
||||
|
||||
# 获得文件绝对路径
|
||||
def getpath():
|
||||
path=os.path.abspath(sys.argv[0])
|
||||
list_str=path.split("\\")
|
||||
return path.replace(list_str[-1],"")
|
||||
|
||||
|
||||
|
||||
class myftp(QObject):
|
||||
local_path=getpath()+'file'
|
||||
# print(local_path)
|
||||
remot_path='/home/root'
|
||||
# 进度信号,ip,1~100
|
||||
rate_signal =pyqtSignal([str,int])
|
||||
# 结束信号,ip,成败,描述
|
||||
end_signal = pyqtSignal([str,bool,str])
|
||||
def __init__(self,ip,user,password):
|
||||
QObject.__init__(self)
|
||||
self.ip=ip
|
||||
self.ssh = paramiko.SSHClient()
|
||||
# 加入受信主机列表
|
||||
self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
self.ssh.connect(ip, 22, user, password,timeout=10)
|
||||
# 实例化一个 sftp对象,指定连接的通道
|
||||
self.sftp=self.ssh.open_sftp()
|
||||
self.invoke = self.ssh.invoke_shell()
|
||||
|
||||
def send_cmd(self,cmd,inputs=[],sleep_s=0.5):
|
||||
# print("send cmd:",cmd)
|
||||
console=""
|
||||
input_list=[]
|
||||
input_list=inputs.copy()
|
||||
self.invoke.send(cmd+'\n') # \n很重要,相当于回车
|
||||
time.sleep(sleep_s)
|
||||
while True:
|
||||
out=self.invoke.recv(9999).decode("utf-8") # 提取数据然后解码
|
||||
if(len(out)>0):
|
||||
# print(out)
|
||||
console+=out
|
||||
else:
|
||||
break
|
||||
if(len(input_list)>0):
|
||||
send_str=input_list.pop(0)
|
||||
# print(self.ip,"|"+send_str)
|
||||
self.invoke.send(send_str+'\n')
|
||||
time.sleep(0.5)
|
||||
else:
|
||||
break
|
||||
console='\n'+console
|
||||
console=console.replace('\n','\n\t|')
|
||||
print(self.ip,console)
|
||||
# print("send cmd end")
|
||||
|
||||
def get_file(self,path,src_list):
|
||||
lo_path=self.local_path+"\\"
|
||||
if(len(path)>0):
|
||||
lo_path=lo_path+path+"\\"
|
||||
if not os.path.exists(lo_path):
|
||||
os.makedirs(lo_path)
|
||||
for i in src_list:
|
||||
file_name=i.split('/')
|
||||
try:
|
||||
# print(file_name[-1])
|
||||
if(len(file_name[-1])>0):
|
||||
self.sftp.get(remotepath=i, localpath=lo_path+file_name[-1])
|
||||
else:
|
||||
file_list=self.scan_dir(i)
|
||||
# self.sftp.get(remotepath=i, localpath=lo_path[0:-1])
|
||||
self.get_file(path,file_list)
|
||||
except Exception as r:
|
||||
print(lo_path,"|"+str(r))
|
||||
print(STR_RED,lo_path,"|get ",i,"failed.",STR_END)
|
||||
return
|
||||
print(STR_BLUE,lo_path,"|get ",i,"success.",STR_END)
|
||||
def scan_dir(self,remotdir):
|
||||
# list=self.sftp.listdir(remotdir)
|
||||
attrs=self.sftp.listdir_attr(remotdir)
|
||||
file_list=[]
|
||||
for attr in attrs:
|
||||
if not stat.S_ISDIR(attr.st_mode):
|
||||
file_list.append(remotdir+attr.filename)
|
||||
# print(file_list)
|
||||
return file_list
|
||||
# 关闭连接
|
||||
def close(self):
|
||||
self.ssh.close()
|
||||
|
||||
def put_cb(self,sent:int,all:int):
|
||||
# (sended*100/data.size()+((index-1)*100))/get_addrs().size()
|
||||
self.put_rate=sent*100//all
|
||||
rate=(self.put_rate+(self.index)*100)//self.len_files
|
||||
self.rate_signal.emit(self.ip,rate)
|
||||
# print("sent={d1},all={d2}".format(d1=sent,d2=all))
|
||||
# print("rate=",rate)
|
||||
|
||||
# 添加进度和结束信号,供qt显示
|
||||
def put_file(self,prefix,dst_list,src_list):
|
||||
if not os.path.exists(self.local_path):
|
||||
self.end_signal.emit(self.ip,False,"local path is not exists.")
|
||||
return
|
||||
self.len_files=len(dst_list)
|
||||
self.index=0
|
||||
for i in dst_list:
|
||||
self.put_rate=0
|
||||
file_name=i.split('/')
|
||||
temp_path=self.remot_path+'/'+file_name[-1]
|
||||
src_path=""
|
||||
if(len(src_list)==0):
|
||||
src_path=self.local_path+'\\'+file_name[-1]
|
||||
else:
|
||||
src_path=src_list[self.index]
|
||||
if os.path.exists(src_path):
|
||||
|
||||
self.send_cmd("rm "+i)
|
||||
# self.sftp.chmod(i.replace(file_name[-1],""),777)
|
||||
self.send_cmd("chmod "+"777 "+i.replace(file_name[-1],""))
|
||||
try:
|
||||
self.sftp.put(localpath=src_path, remotepath=i,callback=self.put_cb)
|
||||
except Exception as r:
|
||||
print(prefix,"|"+str(r))
|
||||
print(STR_RED,prefix,"|put ",i,"failed.",STR_END)
|
||||
self.end_signal.emit(self.ip,False,str(r)+"|"+i)
|
||||
return
|
||||
self.index+=1
|
||||
print(STR_BLUE,prefix,"|put ",i,"success.",STR_END)
|
||||
# self.sftp.chmod(i,777)
|
||||
self.send_cmd("chmod "+"777 "+i)
|
||||
# self.rate_signal.emit(self.ip,self.index*100//self.len_files)
|
||||
else:
|
||||
print(STR_RED,prefix,"|file:"+src_path +" not exist.",STR_END)
|
||||
self.end_signal.emit(self.ip,False,"file:"+src_path +" not exist.")
|
||||
return
|
||||
self.end_signal.emit(self.ip,True,"success")
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# 从虚拟机下载文件
|
||||
def load_file(ip,src_list):
|
||||
print("load file from:",ip)
|
||||
# ftp=myftp(ip,"andy","123456")
|
||||
ftp=myftp(ip,"bitman","123456")
|
||||
ftp.get_file("",src_list)
|
||||
ftp.close()
|
||||
print("load file end.")
|
||||
|
||||
|
||||
# 保存文件到开发板
|
||||
def save_file(ip,restart:bool,dst_list,src_list):
|
||||
try:
|
||||
ftp=myftp(ip,"root","")
|
||||
if(restart==True):
|
||||
print(ip,"|stop app.")
|
||||
ftp.send_cmd("systemctl stop atk-qtapp-start.service")
|
||||
ftp.put_file(ip,dst_list,src_list)
|
||||
if(restart==True):
|
||||
print(ip,"|start app.")
|
||||
ftp.send_cmd("systemctl restart atk-qtapp-start.service")
|
||||
ftp.send_cmd("sync")
|
||||
ftp.close()
|
||||
# print(ip,"|save file end.")
|
||||
except Exception as r:
|
||||
print(STR_RED,ip,"|"+str(r),STR_END)
|
||||
|
||||
|
||||
# 从开发板加载文件
|
||||
def get_file(ip,path,get_list):
|
||||
# print("load file from:",ip)
|
||||
ftp=myftp(ip,"root","")
|
||||
ftp.get_file(path,get_list)
|
||||
ftp.close()
|
||||
# print("load file end.")
|
||||
|
||||
def send_cmd(ip,cmd_list):
|
||||
ftp=myftp(ip,"root","")
|
||||
for i in cmd_list:
|
||||
ftp.send_cmd(i[0],i[1])
|
||||
ftp.close()
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# 定义要从虚拟机下载的文件
|
||||
src_list=[]
|
||||
# src_list.append("/home/bitman/linux/nfs/stm32mp157d-atk.dtb")
|
||||
# src_list.append("/home/bitman/linux/nfs/QDesktop-fb")
|
||||
# src_list.append("/home/bitman/QtWorkSpace/tcp_tr_can/checker_ye_cfg08.json")
|
||||
src_list.append("/home/bitman/linux/nfs/")
|
||||
|
||||
# 定义要保存到开发板的文件
|
||||
dst_list=[]
|
||||
# 第一次拷贝设备树会因为权限问题不能运行
|
||||
# dst_list.append("/run/media/mmcblk2p2/stm32mp157d-atk.dtb")
|
||||
# dst_list.append("/usr/local/QDesktop-fb")
|
||||
# dst_list.append("/home/root/config/checker_app_pre.sh")
|
||||
# dst_list.append("/home/root/config/cfg.json")
|
||||
# dst_list.append("/home/root/config/checker_ye_cfg11.json")
|
||||
dst_list.append("/home/root/config/judge.lua")
|
||||
# dst_list.append("/home/root/config/JQChecker_0008.bin")
|
||||
|
||||
|
||||
# 定义要从开发板获取的文件
|
||||
get_list=[]
|
||||
# get_list.append("/home/root/comm_log/comm_log.csv")
|
||||
get_list.append("/home/root/log/debug_log.txt")
|
||||
# get_list.append("/home/root/config/checker_app_pre.sh")
|
||||
# get_list.append("/home/root/config/cfg.json")
|
||||
# get_list.append("/home/root/config/judge.lua")
|
||||
|
||||
# 定义命令
|
||||
|
||||
cmd_list=[]
|
||||
# cmd_list.append(("/usr/sbin/useradd -d / -g wheel andy",[]))
|
||||
# cmd_list.append(("passwd andy",["123456","123456"]))
|
||||
cmd_list.append(("rm ~/config/checker_app_pre.sh",[]))
|
||||
# cmd_list.append(("ls ~/config/",[]))
|
||||
# cmd_list.append(("ls /usr/local/",[]))
|
||||
|
||||
|
||||
|
||||
# 自动扫描从机地址,然后升级文件
|
||||
|
||||
# python .\ftp.py get 从开发板下载文件
|
||||
# python .\ftp.py save 保存文件到开发板
|
||||
# python .\ftp.py cmd 发送命令列表
|
||||
|
||||
def run():
|
||||
if(len(sys.argv)<2):
|
||||
print("argv too less")
|
||||
return
|
||||
print(sys.argv[0])
|
||||
cmd=sys.argv[1]
|
||||
|
||||
ip_list=[]
|
||||
u=udp.myudp(1,255)
|
||||
u.find("192.168.80")
|
||||
ip_list=u.dst_ip_list
|
||||
if(len(ip_list)==0):
|
||||
# ip_list.append(("192.168.80.120","local_id_1"))
|
||||
ip_list.append(("192.168.80.81","local_id_1"))
|
||||
ip_list.append(("192.168.80.82","local_id_2"))
|
||||
ip_list.append(("192.168.80.83","local_id_3"))
|
||||
ip_list.append(("192.168.80.84","local_id_4"))
|
||||
ip_list.append(("192.168.80.85","local_id_5"))
|
||||
ip_list.append(("192.168.80.86","local_id_6"))
|
||||
ip_list.append(("192.168.80.87","local_id_7"))
|
||||
ip_list.append(("192.168.80.88","local_id_8"))
|
||||
print("find ip_list as:")
|
||||
print(ip_list)
|
||||
threads = []
|
||||
|
||||
if(cmd=="save"):
|
||||
# load_file("192.168.80.188",src_list)
|
||||
print('put file to ip_list.')
|
||||
for i in ip_list:
|
||||
t = threading.Thread(target=save_file, args=(i[0],True,dst_list ))
|
||||
threads.append(t)
|
||||
t.start()
|
||||
elif(cmd=="get"):
|
||||
print("get file from ip_list.")
|
||||
for i in ip_list:
|
||||
t = threading.Thread(target=get_file, args=(i[0],i[1],get_list ))
|
||||
threads.append(t)
|
||||
t.start()
|
||||
elif(cmd=="cmd"):
|
||||
print("send cmd to ip_list")
|
||||
for i in ip_list:
|
||||
t = threading.Thread(target=send_cmd, args=(i[0],cmd_list ))
|
||||
threads.append(t)
|
||||
t.start()
|
||||
elif(cmd=="load"):
|
||||
load_file("192.168.80.188",src_list)
|
||||
#等待所有线程任务结束。
|
||||
for t in threads:
|
||||
t.join()
|
||||
|
||||
print("all task were end.")
|
||||
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run()
|
1
memory_pic.py
Normal file
1
memory_pic.py
Normal file
File diff suppressed because one or more lines are too long
33
pic_2py.py
Normal file
33
pic_2py.py
Normal file
@@ -0,0 +1,33 @@
|
||||
import base64
|
||||
|
||||
def pictopy(picture_names, py_name):
|
||||
"""
|
||||
将图像文件转换为py文件
|
||||
:param picture_name:
|
||||
:return:
|
||||
"""
|
||||
write_data = []
|
||||
for picture_name in picture_names:
|
||||
filename = picture_name.replace('.', '_')
|
||||
open_pic = open("%s" % picture_name, 'rb')
|
||||
b64str = base64.b64encode(open_pic.read())
|
||||
open_pic.close()
|
||||
# 注意这边b64str一定要加上.decode()
|
||||
write_data.append('%s = "%s"\n' % (filename, b64str.decode()))
|
||||
|
||||
f = open('%s.py' % py_name, 'w+')
|
||||
for data in write_data:
|
||||
f.write(data)
|
||||
f.close()
|
||||
|
||||
|
||||
# pics = ["logo_2.png", "logo.ico"] 中的图片存放在PicToPy.py同一目录中,运行完成后,
|
||||
# 会在当前路径看到一个memory_pic.py文件
|
||||
# pics = ["logo_2.png", "subway.ico"]
|
||||
pics = ["icon.ico"]
|
||||
pictopy(pics, 'memory_pic') # 将pics里面的图片写到 memory_pic.py 中
|
||||
print("ok")
|
||||
|
||||
|
||||
|
||||
|
166
udp.py
Normal file
166
udp.py
Normal file
@@ -0,0 +1,166 @@
|
||||
|
||||
import socket
|
||||
import threading
|
||||
from PyQt5.QtCore import *
|
||||
|
||||
|
||||
|
||||
STR_RED="\033[1;31m"
|
||||
STR_BLUE="\033[1;34m"
|
||||
STR_YELLOW="\033[1;33m"
|
||||
STR_END="\033[0m"
|
||||
|
||||
|
||||
class myudp(QObject):
|
||||
dst_ip_list=[]
|
||||
# 进度信号,ip,1~100
|
||||
rate_signal =pyqtSignal([str,int])
|
||||
# 结束信号,ip,成败,描述
|
||||
end_signal = pyqtSignal([str,bool,str])
|
||||
# 数据信号,有的命令有返回数据
|
||||
data_signal = pyqtSignal([str,str])
|
||||
|
||||
def __init__(self,start,end):
|
||||
QObject.__init__(self)
|
||||
self.start=start
|
||||
self.end=end
|
||||
def test_comm(self,ip):
|
||||
# 1.创建socket套接字
|
||||
udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # AF_INET表示使用ipv4,默认不变,SOCK_DGRAM表示使用UDP通信协议
|
||||
# 2.绑定端口port
|
||||
local_addr = ("", 0) # 默认本机任何ip ,指定端口号7878
|
||||
udp.bind(local_addr) # 绑定端口
|
||||
udp.settimeout(1.5)
|
||||
# 3.收发数据
|
||||
send_data = "whos\n"
|
||||
udp.sendto(send_data.encode("utf-8"), (ip, 7777)) # 编码成全球统一数据格式,用元组表示接收方ip和port
|
||||
try:
|
||||
recv_data = udp.recvfrom(1024) # 定义单次最大接收字节数
|
||||
recv_msg = recv_data[0] # 接收的元组形式的数据有两个元素,第一个为发送信息
|
||||
send_addr = recv_data[1] # 元组第二个元素为发信息方的ip以及port
|
||||
# print ("收到的信息为:", recv_msg.decode("utf-8")) # 默认从windows发出的数据解码要用”gbk”,保证中文不乱码
|
||||
# print ("发送方地址为:", str(send_addr)) # 强转为字符串输出地址,保证不乱码
|
||||
str=recv_msg.decode("utf-8").replace("\n","|")
|
||||
list=str.split(",")
|
||||
str=list[1].replace(":","_")
|
||||
self.dst_ip_list.append((send_addr[0],str))
|
||||
except Exception as reason:
|
||||
pass
|
||||
# print(str(reason))
|
||||
# 5.关闭套接字
|
||||
udp.close()
|
||||
|
||||
# 查找从机
|
||||
def find(self,ip_prefix):
|
||||
self.dst_ip_list.clear()
|
||||
threads = []
|
||||
print("find ip {} to {}".format(self.start,self.end))
|
||||
for i in range(self.start,self.end):
|
||||
ip=ip_prefix+".{}".format(i)
|
||||
# print(ip)
|
||||
# 需要注意的一点是,当创建的元组中只有一个字符串类型的元素时,该元素后面必须要加一个逗号,,否则 Python 解释器会将它视为字符串
|
||||
t = threading.Thread(target=self.test_comm, args=(ip,))
|
||||
threads.append(t)
|
||||
t.start()
|
||||
|
||||
#等待所有线程任务结束。
|
||||
for t in threads:
|
||||
t.join()
|
||||
# 去重
|
||||
self.dst_ip_list=list(set(self.dst_ip_list))
|
||||
|
||||
# 发送命令,recv_num返回次数
|
||||
def send(self,ip,cmd,recv_num,timeout):
|
||||
resoult=True
|
||||
udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
local_addr = ("", 0)
|
||||
udp.bind(local_addr)
|
||||
udp.settimeout(timeout)
|
||||
udp.sendto(cmd.encode("utf-8"), (ip, 7777))
|
||||
try:
|
||||
index=0
|
||||
while index<recv_num:
|
||||
recv_data = udp.recvfrom(1024)
|
||||
recv_msg = recv_data[0]
|
||||
send_addr = recv_data[1]
|
||||
out=recv_msg.decode("utf-8")
|
||||
out_list=out.split(",")
|
||||
ret_list=out_list[0].split(":")
|
||||
if(ret_list[0]=="ack"):
|
||||
index+=1
|
||||
if(ret_list[1]=="1"):
|
||||
out=("\n"+out).replace("\n",STR_YELLOW+"|"+STR_BLUE)
|
||||
out=out+STR_END
|
||||
elif(ret_list[1]=="0"):
|
||||
out=("\n"+out).replace("\n",STR_YELLOW+"|"+STR_RED)
|
||||
out=out+STR_END
|
||||
resoult=False
|
||||
elif(ret_list[0]=="data"):
|
||||
index+=1
|
||||
self.data_signal.emit(ip,out[5:])
|
||||
elif(ret_list[0]=="rate"):
|
||||
rate=int(ret_list[1])
|
||||
self.rate_signal.emit(ip,rate)
|
||||
else:
|
||||
out=("\n"+out).replace("\n",STR_YELLOW+"|"+STR_END)
|
||||
if(ret_list[0]!="rate"):
|
||||
print(send_addr[0],out)
|
||||
except Exception as reason:
|
||||
print(STR_RED,ip,"|"+str(reason),STR_END)
|
||||
resoult=False
|
||||
udp.close()
|
||||
return resoult
|
||||
|
||||
# 发送命令列表
|
||||
def send_list(self,ip,cmd_list):
|
||||
for i in range(len(cmd_list)):
|
||||
resoult=self.send(ip,cmd_list[i][0],cmd_list[i][1],cmd_list[i][2])
|
||||
if(resoult!=True):
|
||||
err_str="cmd="+cmd_list[i][0]+" filed."
|
||||
print(STR_RED,ip,"|"+err_str,STR_END)
|
||||
self.end_signal.emit(ip,False,err_str)
|
||||
return
|
||||
# self.rate_signal.emit(ip,(i*100)//len(cmd_list))
|
||||
self.end_signal.emit(ip,True,"success")
|
||||
|
||||
# 广播命令,在find之后调用,str 要发送的数据,recv_num,返回次数
|
||||
def bordcast(self,cmd_list):
|
||||
threads = []
|
||||
print("bordcast:",cmd_list)
|
||||
print("ip_list:",self.dst_ip_list)
|
||||
for i in self.dst_ip_list:
|
||||
ip=i[0]
|
||||
t = threading.Thread(target=self.send_list, args=(ip,cmd_list))
|
||||
threads.append(t)
|
||||
t.start()
|
||||
|
||||
for t in threads:
|
||||
t.join()
|
||||
|
||||
|
||||
|
||||
|
||||
# 定义自动发送的命令列表,命令,返回次数,超时
|
||||
cmd_list=[]
|
||||
# cmd_list.append(("local setlog filefilter tcp_client",1,1))
|
||||
# cmd_list.append(("mcu scheme 1,2,3,4,5,6,7,8,9,10",1,30))
|
||||
cmd_list.append(("mcu bootinfo 1,2,3,4,5,6,7,8,9,10",1,5))
|
||||
# cmd_list.append(("mcu start 10",2,37))
|
||||
# cmd_list.append(("mcu updata 1,2,3,4,5,6,7,8,9,10",1,900))
|
||||
cmd_list.append(("whos",1,2))
|
||||
# cmd_list.append(("mcu updata 10 /home/root/config/JQChecker_0008.bin",1,900))
|
||||
|
||||
|
||||
# 扫描从机ip地址
|
||||
# 返回元组列表,ip,local_id
|
||||
def main():
|
||||
udp=myudp(1,255)
|
||||
udp.find("192.168.80")
|
||||
print(udp.dst_ip_list)
|
||||
udp.bordcast(cmd_list)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
|
571
updata.py
Normal file
571
updata.py
Normal file
@@ -0,0 +1,571 @@
|
||||
|
||||
import udp
|
||||
import ftp
|
||||
import sys
|
||||
import os
|
||||
import shutil
|
||||
from PyQt5.QtCore import *
|
||||
from PyQt5.QtGui import *
|
||||
from PyQt5.QtWidgets import *
|
||||
import threading
|
||||
import time
|
||||
import portalocker
|
||||
import encodings.idna
|
||||
import base64
|
||||
import memory_pic
|
||||
import ctypes
|
||||
ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID("myappid")
|
||||
|
||||
STR_RED="\033[1;31m"
|
||||
STR_BLUE="\033[1;34m"
|
||||
STR_END="\033[0m"
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
class progress_box(QObject):
|
||||
|
||||
rate_signal =pyqtSignal([int])
|
||||
|
||||
def __init__(self) -> None:
|
||||
QObject.__init__(self)
|
||||
|
||||
def init(self,father:QDialog,text:str,x:int):
|
||||
# print("text=",text)
|
||||
self.lable = QLabel(father)
|
||||
self.lable.setObjectName(u"label")
|
||||
self.lable.setGeometry(QRect(40, x, 120, 15))
|
||||
self.lable.setText(text)
|
||||
self.stat = QLabel(father)
|
||||
self.stat.setObjectName(u"label")
|
||||
self.stat.setGeometry(QRect(500, x+20, 120, 15))
|
||||
self.stat.setText("进行中...")
|
||||
self.p=QProgressBar(father)
|
||||
self.p.setValue(0)
|
||||
self.p.setGeometry(QRect(40,x+20,450,20))
|
||||
self.rate_signal.connect(self.p.setValue)
|
||||
def set_rate(self,text:str,rate:int):
|
||||
if(text==self.lable.text()):
|
||||
# print(text)
|
||||
self.rate_signal.emit(rate)
|
||||
def set_txt(self,text:str,ack:bool,stat:int):
|
||||
if(text==self.lable.text()):
|
||||
self.stat.setText(stat)
|
||||
|
||||
|
||||
|
||||
class data_box(QObject):
|
||||
def __init__(self) -> None:
|
||||
QObject.__init__(self)
|
||||
|
||||
def init(self,father:QDialog,title:str,text:str,x:int):
|
||||
# print("text=",text)
|
||||
self.lable = QLabel(father)
|
||||
self.lable.setObjectName(u"label")
|
||||
self.lable.setGeometry(QRect(40, x, 120, 20))
|
||||
self.lable.setText(title)
|
||||
self.text = QLabel(father)
|
||||
self.text.setObjectName(u"text")
|
||||
self.text.setGeometry(QRect(40,x+20,450,30))
|
||||
self.text.setText(text)
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
class updata_dlg(QObject):
|
||||
# 进度信号,ip,1~100
|
||||
rate_signal =pyqtSignal([str,int])
|
||||
# 结束信号,ip,成败,描述
|
||||
end_signal = pyqtSignal([str,bool,str])
|
||||
|
||||
|
||||
def __init__(self):
|
||||
QObject.__init__(self)
|
||||
self.app = QApplication(sys.argv)
|
||||
self.widget = QWidget()
|
||||
self.widget.resize(703, 409)
|
||||
self.widget.setWindowTitle("批检仪程序升级")
|
||||
self.widget.setWindowFlags(Qt.WindowStaysOnTopHint)
|
||||
self.file_list_init()
|
||||
self.slave_list_init()
|
||||
self.save_but_init()
|
||||
self.cmd_but_init()
|
||||
self.refresh_but_init()
|
||||
self.sstate_but_init()
|
||||
self.hand_but_init()
|
||||
self.addfile_but_init()
|
||||
self.ip_prefix_init()
|
||||
self.ip_hand_init()
|
||||
self.widget.destroyed.connect(self.quit)
|
||||
self.scan_file()
|
||||
self.scan_slave()
|
||||
|
||||
Logo = QPixmap()
|
||||
Logo.loadFromData(base64.b64decode(memory_pic.icon_ico))
|
||||
icon = QIcon()
|
||||
icon.addPixmap(Logo, QIcon.Normal, QIcon.Off)
|
||||
self.widget.setWindowIcon(icon)
|
||||
|
||||
|
||||
def quit(self):
|
||||
# 程序退出
|
||||
qApp.exit(1)
|
||||
# 初始化文件列表
|
||||
def file_list_init(self):
|
||||
self.file_list = QListWidget(self.widget)
|
||||
self.file_list.setObjectName(u"file_list")
|
||||
self.file_list.setGeometry(QRect(25, 250, 531, 141))
|
||||
self.file_list.setFrameShape(QFrame.Box)
|
||||
self.file_list.setMidLineWidth(1)
|
||||
self.file_list.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
|
||||
self.file_list.setSelectionMode(QAbstractItemView.MultiSelection)
|
||||
self.file_list_label = QLabel(self.widget)
|
||||
self.file_list_label.setObjectName(u"label")
|
||||
self.file_list_label.setGeometry(QRect(30, 230, 200, 15))
|
||||
self.file_list_label.setText("默认文件列表:")
|
||||
|
||||
# 初始化从机列表
|
||||
def slave_list_init(self):
|
||||
self.slave_list = QListWidget(self.widget)
|
||||
self.slave_list.setObjectName(u"slave_list")
|
||||
self.slave_list.setGeometry(QRect(25, 80, 531, 141))
|
||||
self.slave_list.setFrameShape(QFrame.Box)
|
||||
self.slave_list.setMidLineWidth(1)
|
||||
self.slave_list.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
|
||||
self.slave_list.setSelectionMode(QAbstractItemView.MultiSelection)
|
||||
self.slave_list.doubleClicked.connect(self.slave_list.editItem)
|
||||
self.slave_list_label = QLabel(self.widget)
|
||||
self.slave_list_label.setObjectName(u"label")
|
||||
self.slave_list_label.setGeometry(QRect(30, 60, 200, 15))
|
||||
self.slave_list_label.setText("在线主板列表:")
|
||||
|
||||
# 初始化手动添加IP按钮
|
||||
def hand_but_init(self):
|
||||
self.hand_but = QPushButton(self.widget)
|
||||
self.hand_but.setObjectName(u"hand_but")
|
||||
self.hand_but.setGeometry(QRect(590, 60, 93, 28))
|
||||
self.hand_but.setText("手动添加IP")
|
||||
self.hand_but.clicked.connect(self.hand_but_clicked)
|
||||
|
||||
# 初始化发送文件按钮
|
||||
def save_but_init(self):
|
||||
self.save_but = QPushButton(self.widget)
|
||||
self.save_but.setObjectName(u"save_but")
|
||||
self.save_but.setGeometry(QRect(590, 100, 93, 28))
|
||||
self.save_but.setText("发送文件")
|
||||
self.save_but.clicked.connect(self.save_but_clicked)
|
||||
|
||||
# 初始化发送命令按钮
|
||||
def cmd_but_init(self):
|
||||
self.cmd_but = QPushButton(self.widget)
|
||||
self.cmd_but.setObjectName(u"save_but")
|
||||
self.cmd_but.setGeometry(QRect(590, 140, 93, 28))
|
||||
self.cmd_but.setText("升级MCU")
|
||||
self.cmd_but.clicked.connect(self.cmd_but_clicked)
|
||||
|
||||
# 初始化刷新按钮
|
||||
def refresh_but_init(self):
|
||||
self.refresh_but = QPushButton(self.widget)
|
||||
self.refresh_but.setObjectName(u"save_but")
|
||||
self.refresh_but.setGeometry(QRect(590, 180, 93, 28))
|
||||
self.refresh_but.setText("刷新IP地址")
|
||||
self.refresh_but.clicked.connect(self.refresh_but_clicked)
|
||||
|
||||
# 初始化在线状态按钮
|
||||
def sstate_but_init(self):
|
||||
self.sstate_but = QPushButton(self.widget)
|
||||
self.sstate_but.setObjectName(u"sstate_but")
|
||||
self.sstate_but.setGeometry(QRect(590, 220, 93, 28))
|
||||
self.sstate_but.setText("MCU在线状态")
|
||||
self.sstate_but.clicked.connect(self.sstate_but_clicked)
|
||||
|
||||
# 初始化添加文件按钮
|
||||
def addfile_but_init(self):
|
||||
self.addfile_but = QPushButton(self.widget)
|
||||
self.addfile_but.setObjectName(u"addfile_but")
|
||||
self.addfile_but.setGeometry(QRect(590, 260, 93, 28))
|
||||
self.addfile_but.setText("添加文件")
|
||||
self.addfile_but.clicked.connect(self.addfile_but_clicked)
|
||||
|
||||
# ip前缀
|
||||
def ip_prefix_init(self):
|
||||
self.ip_prefix = QLineEdit(self.widget)
|
||||
self.ip_prefix.setObjectName(u"ip_prefix")
|
||||
self.ip_prefix.setGeometry(QRect(30, 30, 113, 21))
|
||||
self.ip_prefix.setText("192.168.80")
|
||||
self.ip_prefix_label = QLabel(self.widget)
|
||||
self.ip_prefix_label.setObjectName(u"label")
|
||||
self.ip_prefix_label.setGeometry(QRect(30, 10, 72, 15))
|
||||
self.ip_prefix_label.setText("IP前缀")
|
||||
|
||||
# 手动添加ip
|
||||
def ip_hand_init(self):
|
||||
self.ip_hand = QLineEdit(self.widget)
|
||||
self.ip_hand.setObjectName(u"ip_hand")
|
||||
self.ip_hand.setGeometry(QRect(300, 30, 120, 21))
|
||||
ip=self.ip_prefix.text()
|
||||
self.ip_hand.setText(ip+".81")
|
||||
self.ip_hand_label = QLabel(self.widget)
|
||||
self.ip_hand_label.setObjectName(u"ip_hand_label")
|
||||
self.ip_hand_label.setGeometry(QRect(300, 10, 120, 15))
|
||||
self.ip_hand_label.setText("手动添加IP地址")
|
||||
|
||||
# 显示消息框
|
||||
def show_msg(self,msg:str):
|
||||
m=QMessageBox(self.widget)
|
||||
m.setText(msg)
|
||||
m.setWindowTitle("提示")
|
||||
m.show()
|
||||
|
||||
# 找到已选择的文件
|
||||
def get_selected_file_by_type(self,type:str):
|
||||
file_list=[]
|
||||
items=self.file_list.selectedItems()
|
||||
for i in items:
|
||||
if(i.text()[-len(type):]==type):
|
||||
file_list.append(i.text())
|
||||
if(len(file_list)!=1):
|
||||
self.show_msg("请选择一个并且只选择一个 "+type+" 文件")
|
||||
return ""
|
||||
return file_list[0]
|
||||
|
||||
# 获取已选择的文件列表
|
||||
def get_selected_fils(self):
|
||||
file_list=[]
|
||||
items=self.file_list.selectedItems()
|
||||
if(len(items)==0):
|
||||
self.show_msg("请选择至少一个文件")
|
||||
return []
|
||||
have_elf=False
|
||||
have_bin=False
|
||||
have_lua=False
|
||||
for i in items:
|
||||
if(i.text()[-4:]==".elf"):
|
||||
if(have_elf==True):
|
||||
self.show_msg("只可选择一个 .elf 文件")
|
||||
return []
|
||||
have_elf=True
|
||||
if(i.text()[-4:]==".bin"):
|
||||
if(have_bin==True):
|
||||
self.show_msg("只可选择一个 .bin 文件")
|
||||
return []
|
||||
have_bin=True
|
||||
if(i.text()[-4:]==".lua"):
|
||||
if(have_lua==True):
|
||||
self.show_msg("只可选择一个 .lua 文件")
|
||||
return []
|
||||
have_lua=True
|
||||
file_list.append(i.text())
|
||||
return file_list
|
||||
|
||||
def get_selected_slave(self):
|
||||
slave_list=[]
|
||||
items=self.slave_list.selectedItems()
|
||||
if(len(items)==0):
|
||||
self.show_msg("请选择至少一个ip地址")
|
||||
return []
|
||||
for i in items:
|
||||
str_list=i.text().split(",")
|
||||
slave_list.append((str_list[0],str_list[1]))
|
||||
return slave_list
|
||||
|
||||
# 根据文件列表生成目标列表
|
||||
def build_dst_list(self,file_list):
|
||||
dst_list=[]
|
||||
for i in file_list:
|
||||
if(i[-4:]==".elf"):
|
||||
dst_list.append("/usr/local/QDesktop-fb")
|
||||
elif(i[-4:]==".dtb"):
|
||||
dst_list.append("/run/media/mmcblk2p2/"+i)
|
||||
elif(i.find("checker_ye_cfg")>=0):
|
||||
dst_list.append("/home/root/config/"+"checker_ye_cfg.json")
|
||||
elif(i[-4:]==".lua"):
|
||||
dst_list.append("/home/root/config/"+"judge.lua")
|
||||
else:
|
||||
dst_list.append("/home/root/config/"+i)
|
||||
return dst_list
|
||||
|
||||
def hand_but_clicked(self):
|
||||
print("hand_but clicked.")
|
||||
ip=self.ip_hand.text()
|
||||
self.slave_list.addItem(ip+",local_id_0")
|
||||
|
||||
# 发送文件按钮按下
|
||||
def save_but_clicked(self):
|
||||
print("save_but_clicked.")
|
||||
path = self.getpath()+"file\\"
|
||||
file_list=self.get_selected_fils()
|
||||
if(len(file_list)==0):
|
||||
return
|
||||
dst_list=self.build_dst_list(file_list)
|
||||
for i in range(len(file_list)):
|
||||
file_list[i]=path+file_list[i]
|
||||
for i in zip(file_list,dst_list):
|
||||
print("file:",i[0],i[1])
|
||||
slave_list=self.get_selected_slave()
|
||||
if(len(slave_list)==0):
|
||||
return
|
||||
print("slaves:",slave_list)
|
||||
w=QDialog(self.widget)
|
||||
w.resize(703-100, len(slave_list)*40+20)
|
||||
w.setWindowTitle("上传文件")
|
||||
self.updata(slave_list,dst_list,file_list)
|
||||
self.creat_progress(w,slave_list)
|
||||
w.show()
|
||||
|
||||
# 创建进度条
|
||||
def creat_progress(self,father:QDialog,ip_list:list):
|
||||
self.probar_list=[]
|
||||
for i in range(len(ip_list)):
|
||||
p=progress_box()
|
||||
p.init(father,ip_list[i][0],+i*40)
|
||||
self.rate_signal.connect(p.set_rate)
|
||||
self.end_signal.connect(p.set_txt)
|
||||
self.probar_list.append(p)
|
||||
|
||||
# 发送命令按钮按下
|
||||
def cmd_but_clicked(self):
|
||||
print("cmd_but clicked.")
|
||||
slave_list=self.get_selected_slave()
|
||||
if(len(slave_list)==0):
|
||||
return
|
||||
print("slaves:",slave_list)
|
||||
file=self.get_selected_file_by_type(".bin")
|
||||
if(len(file)==0):
|
||||
return
|
||||
print("file:",file)
|
||||
w=QDialog(self.widget)
|
||||
w.resize(703-100, len(slave_list)*40+20)
|
||||
w.setWindowTitle("升级mcu")
|
||||
self.updata_mcu(slave_list,file)
|
||||
self.creat_progress(w,slave_list)
|
||||
w.show()
|
||||
|
||||
def refresh_but_clicked(self):
|
||||
print("refresh_but clicked.")
|
||||
self.slave_list.clear()
|
||||
self.scan_slave()
|
||||
|
||||
def sstate_but_clicked(self):
|
||||
print("sstate_but clicked.")
|
||||
slave_list=self.get_selected_slave()
|
||||
if(len(slave_list)==0):
|
||||
return
|
||||
self.data_list=[]
|
||||
self.comm_test(slave_list)
|
||||
|
||||
def addfile_but_clicked(self):
|
||||
print("addfile_but clicked")
|
||||
fileName,fileType = QFileDialog.getOpenFileNames(None, "选取文件", os.getcwd(),
|
||||
"主板程序(*.elf);;小板程序(*.bin);;检测方案(*.json);;判定脚本(*.lua);;任意文件(*)")
|
||||
print(fileName,fileType)
|
||||
path=self.getpath()+"file\\"
|
||||
for i in fileName:
|
||||
shutil.copy(i,path+i.split("/")[-1])
|
||||
self.scan_file()
|
||||
|
||||
|
||||
# 开始运行
|
||||
def run(self):
|
||||
self.widget.show()
|
||||
sys.exit(self.app.exec())
|
||||
|
||||
# 扫描文件
|
||||
def scan_file(self):
|
||||
self.file_list.clear()
|
||||
self.file_list.addItems(self.find_type([".sh",".elf",".bin",".lua",".json",".dtb"]))
|
||||
|
||||
# 扫描从机
|
||||
def scan_slave(self):
|
||||
u=udp.myudp(1,255)
|
||||
ip_prefix=self.ip_prefix.text()
|
||||
u.find(ip_prefix)
|
||||
ip_list=u.dst_ip_list
|
||||
if(len(ip_list)==0):
|
||||
ret=QMessageBox.question(self.widget,"提示","未扫描到从机,是否自动添加?",QMessageBox.Yes|QMessageBox.No)
|
||||
if(ret==QMessageBox.Yes):
|
||||
ip_list.append((ip_prefix+".81","local_id_1"))
|
||||
ip_list.append((ip_prefix+".82","local_id_2"))
|
||||
ip_list.append((ip_prefix+".83","local_id_3"))
|
||||
ip_list.append((ip_prefix+".84","local_id_4"))
|
||||
ip_list.append((ip_prefix+".85","local_id_5"))
|
||||
ip_list.append((ip_prefix+".86","local_id_6"))
|
||||
ip_list.append((ip_prefix+".87","local_id_7"))
|
||||
ip_list.append((ip_prefix+".88","local_id_8"))
|
||||
list_str=[]
|
||||
for i in u.dst_ip_list:
|
||||
list_str.append(i[0]+','+i[1])
|
||||
self.slave_list.addItems(list_str)
|
||||
|
||||
# 扫描指定类型的文件
|
||||
def find_type(self,types:list):
|
||||
path = self.getpath()+"file\\"
|
||||
if not os.path.exists(path):
|
||||
os.makedirs(path)
|
||||
list=os.listdir(path)
|
||||
file_list=[]
|
||||
for t in types:
|
||||
for i in list:
|
||||
if(len(t)>0):
|
||||
if(i[-len(t):]==t):
|
||||
file_list.append(i)
|
||||
else:
|
||||
file_list.append(i)
|
||||
return file_list
|
||||
|
||||
# 获得文件绝对路径
|
||||
def getpath(self):
|
||||
path=os.path.abspath(sys.argv[0])
|
||||
list_str=path.split("\\")
|
||||
return path.replace(list_str[-1],"")
|
||||
|
||||
# 调用此函数开始升级
|
||||
def updata(self,ip_list,dst_list,src_list):
|
||||
t = threading.Thread(target=self.updata_thread, args=(ip_list,dst_list,src_list))
|
||||
# t = threading.Thread(target=self.thread_test, args=(ip_list,dst_list,src_list))
|
||||
t.start()
|
||||
|
||||
# 开始升级mcu
|
||||
def updata_mcu(self,ip_list,file):
|
||||
u=udp.myudp(1,255)
|
||||
u.dst_ip_list=ip_list
|
||||
u.rate_signal.connect(self.rate_slot)
|
||||
u.end_signal.connect(self.end_slot)
|
||||
updata_cmd="mcu updata 1,2,3,4,5,6,7,8,9,10 "
|
||||
updata_cmd+="/home/root/config/"+file
|
||||
cmd_list=[]
|
||||
cmd_list.append((updata_cmd,1,900))
|
||||
t = threading.Thread(target=u.bordcast, args=(cmd_list,))
|
||||
t.start()
|
||||
|
||||
# 小板通信测试
|
||||
def comm_test(self,ip_list):
|
||||
u=udp.myudp(1,255)
|
||||
u.dst_ip_list=ip_list
|
||||
# u.rate_signal.connect(self.rate_slot)
|
||||
# u.end_signal.connect(self.end_slot)
|
||||
u.data_signal.connect(self.data_slot)
|
||||
updata_cmd="mcu comm_test"
|
||||
cmd_list=[]
|
||||
cmd_list.append((updata_cmd,2,5))# 两次返回,五秒超时
|
||||
t = threading.Thread(target=u.bordcast, args=(cmd_list,))
|
||||
t.start()
|
||||
|
||||
|
||||
# 测试线程
|
||||
def thread_test(self,ip_list,dst_list,src_list):
|
||||
for i in range(100):
|
||||
for ip in ip_list:
|
||||
self.rate_slot(ip[0],i+1)
|
||||
time.sleep(0.02)
|
||||
|
||||
def updata_thread(self,ip_list,dst_list,src_list):
|
||||
threads=[]
|
||||
for i in ip_list:
|
||||
t = threading.Thread(target=self.save_file, args=(i[0],True,dst_list ,src_list))
|
||||
threads.append(t)
|
||||
t.start()
|
||||
#等待所有线程任务结束。
|
||||
for t in threads:
|
||||
t.join()
|
||||
|
||||
def end_slot(self,ip,ack,err):
|
||||
# print(ip,ack,err)
|
||||
if(ack==False):
|
||||
self.show_msg(ip+":"+err)
|
||||
else:
|
||||
self.end_signal.emit(ip,True,"完成")
|
||||
|
||||
|
||||
def rate_slot(self,ip,rate):
|
||||
# print("rate signal:",ip,rate)
|
||||
self.rate_signal.emit(ip,rate)
|
||||
|
||||
def data_slot(self,ip,text):
|
||||
self.data_list.append((ip,text))
|
||||
# 全部返回完时显示数据
|
||||
slave_len=len(self.get_selected_slave())
|
||||
if(len(self.data_list)>=slave_len):
|
||||
w=QDialog(self.widget)
|
||||
w.resize(703-150, slave_len*50+20)
|
||||
w.setWindowTitle("返回数据展示")
|
||||
self.creat_databoxs(w,self.data_list)
|
||||
w.show()
|
||||
|
||||
# 创建数据显示
|
||||
def creat_databoxs(self,father:QDialog,data_list:list):
|
||||
self.datab_list=[]
|
||||
for i in range(len(data_list)):
|
||||
p=data_box()
|
||||
p.init(father,data_list[i][0],data_list[i][1],+i*50)
|
||||
self.datab_list.append(p)
|
||||
|
||||
|
||||
def save_file(self,ip,restart:bool,dst_list,src_list):
|
||||
try:
|
||||
f=ftp.myftp(ip,"root","")
|
||||
# f.end_signal.connect(self.end_slot)
|
||||
f.rate_signal.connect(self.rate_slot)
|
||||
if(restart==True):
|
||||
print(ip,"|stop app.")
|
||||
f.send_cmd("systemctl stop atk-qtapp-start.service")
|
||||
f.put_file(ip,dst_list,src_list)
|
||||
if(restart==True):
|
||||
print(ip,"|start app.")
|
||||
f.send_cmd("systemctl restart atk-qtapp-start.service")
|
||||
f.send_cmd("sync",sleep_s=3)
|
||||
f.close()
|
||||
self.end_signal.emit(ip,True,"完成")
|
||||
# print(ip,"|save file end.")
|
||||
except Exception as r:
|
||||
err_str=str(r)
|
||||
print(STR_RED,ip,"|"+"try exception "+err_str,STR_END)
|
||||
# self.end_slot(ip,False,err_str)
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
class locker():
|
||||
def _get_lock(self):
|
||||
file_name = os.path.basename(__file__)
|
||||
# linux等平台依然使用标准的/var/run,其他nt等平台使用当前目录
|
||||
if os.name == "posix":
|
||||
lock_file_name = f"/var/run/{file_name}.pid"
|
||||
else:
|
||||
lock_file_name = f"{file_name}.pid"
|
||||
self.fd = open(lock_file_name, "w")
|
||||
try:
|
||||
portalocker.lock(self.fd, portalocker.LOCK_EX | portalocker.LOCK_NB)
|
||||
# 将当前进程号写入文件
|
||||
# 如果获取不到锁上一步就已经异常了,所以不用担心覆盖
|
||||
self.fd.writelines(str(os.getpid()))
|
||||
# 写入的数据太少,默认会先被放在缓冲区,我们强制同步写入到文件
|
||||
self.fd.flush()
|
||||
except:
|
||||
print(f"{file_name} have another instance running.")
|
||||
exit(1)
|
||||
|
||||
def __init__(self):
|
||||
self._get_lock()
|
||||
|
||||
# 和fcntl有点区别,portalocker释放锁直接有unlock()方法
|
||||
# 还是一样,其实并不需要在最后自己主动释放锁
|
||||
def __del__(self):
|
||||
portalocker.unlock(self.fd)
|
||||
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
lock=locker()
|
||||
dlg=updata_dlg()
|
||||
dlg.run()
|
||||
|
Reference in New Issue
Block a user