python对于ota的应用_【python】OTA升级服务端程序,TCP连接,带文档

[Python] 纯文本查看 复制代码import socketserver

import time

import os

import re

class MyTcpHandler(socketserver.BaseRequestHandler):

def handle(self):

step=0

filepath = 'null'

filesize = 0

files = None

conbuf = None

limit = None

cnt = 0

while True:

try:

data = self.request.recv(1024)

print(data)

if not data: break # 此行代码针对linux系统

recvstr = data.decode(encoding="utf-8")

if step == 0:#判断设备名

if recvstr.find('device')==-1:

self.request.send(b"cmderr:1")#未匹配到指令

else:

modestr = recvstr[recvstr.find('#')+1:]

oldver = re.sub(r'\D', "", modestr)

filename = re.sub(r'\d', "", modestr)

print ('ver'+oldver+' name='+filename)

print()

for i in range(50):

if os.path.exists(os.path.abspath('.')+'\\bin\\'+filename+str(int(oldver)+i+1)+'.bin')==True:

filepath = os.path.abspath('.')+'\\bin\\'+filename+str(int(oldver)+i+1)+'.bin'

print(os.path.abspath('.')+'\\bin\\'+filename+str(int(oldver)+i+1)+'.bin')

if filepath == 'null':

self.request.send(b"cmderr:3")#未匹配到指令

else:

step=1

newver = "newver:"+re.sub(r'\D', "", filepath)

self.request.send(newver.encode(encoding="utf-8"))

#打开文件

filesize = os.path.getsize(filepath)

files = open(filepath,'rb')

elif step ==1:#判断auto还是control

if recvstr.find('auto')!=-1:

step=10

filesizestr = str(filesize)

limit = int(filesize/1024) + 1

self.request.send(filesizestr.encode(encoding="utf-8"))

elif recvstr.find('control')!=-1:

step=20

filesizestr = str(filesize)

self.request.send(filesizestr.encode(encoding="utf-8"))

limit = int(filesize/1024) + 1

cnt = 0

else:

self.request.send(b"cmderr:1")#未匹配到指令

elif step ==10:#自动模式

if recvstr.find('start')==-1:

self.request.send(b"cmderr:1")#未匹配到指令

continue

delayms = 1000/ (int(re.sub(r'\D', "", recvstr)))

for i in range(limit):

buf = files.read(1024)

self.request.send(buf)

print('发送数据包:%d/%d' %(i+1,limit))

time.sleep(delayms/1000)

files.close()

print('传输结束')

break #传输结束

elif step ==20:#手动模式

if cnt >= limit:

self.request.send(b"endoffile")

files.close()

print('传输结束')

break

if recvstr.find('next')!=-1:

cnt = cnt + 1

conbuf = files.read(1024)

self.request.send(conbuf)

print('控制传输:%d/%d'%(cnt,limit))

time.sleep(0.03)

elif recvstr.find('resend')!=-1:

if cnt == 0:

conbuf = files.read(1024)

cnt = cnt + 1

self.request.send(conbuf)

print('重新传输:%d/%d'%(cnt,limit))

time.sleep(0.03)

elif recvstr.find('exit')!=-1:

files.close()

print('客户端断开')

break

else:

self.request.send(b"cmderr:1")#未匹配到指令

else:

self.request.send(b"cmderr:-1")#未知错误

except ConnectionResetError:

break

self.request.close()

if __name__ == '__main__':

server = socketserver.ThreadingTCPServer(('0.0.0.0', 6666), MyTcpHandler)

server.serve_forever()

你可能感兴趣的:(python对于ota的应用)