def connect_over_tcp(serverip, port, logger): retrynum = 0 tcp_sock = TCPClient(2, serverip, port) # logger.info('sock state: %r' % (tcp_sock.state)) while True: if retrynum > 6: break retrynum += 1 if tcp_sock.state == SOCK_CLOSE_STATE: # tcp_sock.shutdown() cur_state = tcp_sock.state try: tcp_sock.open() if tcp_sock.state == SOCK_OPEN_STATE: logger.info(f"[{serverip}] is OPEN") time.sleep(0.2) except Exception as e: logger.error(e) elif tcp_sock.state == SOCK_OPEN_STATE: cur_state = tcp_sock.state try: tcp_sock.connect() if tcp_sock.state == SOCK_CONNECT_STATE: logger.info("[%r] is CONNECTED" % (serverip)) except Exception as e: logger.error(e) elif tcp_sock.state == SOCK_CONNECT_STATE: break if retrynum > 6: logger.info("Device [%s] TCP connection failed.\r\n" % (serverip)) return None else: logger.info("Device [%s] TCP connected\r\n" % (serverip)) return tcp_sock
class FWUploadThread(QThread): uploading_size = pyqtSignal(int) upload_result = pyqtSignal(int) error_flag = pyqtSignal(int) def __init__(self, conf_sock, dest_mac, idcode, set_pw, filename, filesize, ipaddr, port, dev_name): QThread.__init__(self) self.dest_mac = None self.bin_filename = filename self.fd = None self.data = None self.client = None self.timer1 = None self.istimeout = 0 self.serverip = None self.serverport = None self.sentbyte = 0 self.dest_mac = dest_mac self.idcode = idcode self.error_noresponse = 0 self.retrycheck = 0 # if wiz2000 self.dev_name = dev_name self.set_pw = set_pw self.filesize = filesize self.remainbytes = self.filesize self.conf_sock = conf_sock self.sock_type = '%s' % self.conf_sock # socket config (for TCP unicast) self.ip_addr = ipaddr self.port = port self.tcp_sock = None def setparam(self): self.fd = open(self.bin_filename, "rb") self.data = self.fd.read(-1) self.curr_ptr = 0 self.fd.close() def myTimer(self): # sys.stdout.write('timer1 timeout\r\n') self.istimeout = 1 def jumpToApp(self): cmd_list = [] # boot mode change: App boot mode cmd_list.append(["MA", self.dest_mac]) cmd_list.append(["PW", self.idcode]) cmd_list.append(["AB", ""]) if 'TCP' in self.sock_type: self.wizmsghangler = WIZMSGHandler(self.conf_sock, cmd_list, 'tcp', OP_FWUP, 2) elif 'UDP' in self.sock_type: self.wizmsghangler = WIZMSGHandler(self.conf_sock, cmd_list, 'udp', OP_FWUP, 2) self.resp = self.wizmsghangler.run() self.uploading_size.emit(1) self.msleep(1000) def sendCmd(self, command): cmd_list = [] self.resp = None # Send FW UPload request message cmd_list.append(["MA", self.dest_mac]) cmd_list.append(["PW", self.idcode]) if 'WIZ2000' in self.dev_name: cmd_list.append(["AP", self.set_pw.decode()]) cmd_list.append([command, str(self.filesize)]) print('sendCmd() cmd_list ===> ', cmd_list) if 'TCP' in self.sock_type: self.wizmsghangler = WIZMSGHandler(self.conf_sock, cmd_list, 'tcp', OP_FWUP, 2) elif 'UDP' in self.sock_type: self.wizmsghangler = WIZMSGHandler(self.conf_sock, cmd_list, 'udp', OP_FWUP, 2) sys.stdout.write("sendCmd(): %s\r\n" % cmd_list) # if no reponse from device, retry for several times. for i in range(4): # self.resp = self.wizmsghangler.parseresponse() self.resp = self.wizmsghangler.run() if self.resp is not '': break self.msleep(500) self.uploading_size.emit(2) def run(self): self.setparam() # wiz2000: not use 'AB' command print('===============>> FW upload', self.dev_name) if 'WIZ2000' in self.dev_name: print('wiz2000 FW upload', self.dev_name) pass else: self.jumpToApp() if 'UDP' in self.sock_type: pass elif 'TCP' in self.sock_type: self.sock_close() self.SocketConfig() self.sendCmd('FW') if self.resp is not '' and self.resp is not None: resp = self.resp.decode('utf-8') # print('resp', resp) params = resp.split(':') sys.stdout.write('Dest IP: %s, Dest Port num: %r\r\n' % (params[0], int(params[1]))) self.serverip = params[0] self.serverport = int(params[1]) self.uploading_size.emit(3) else: print( 'No response from device. Check the network or device status.') self.error_flag.emit(-1) self.error_noresponse = -1 try: self.client = TCPClient(2, params[0], int(params[1])) except: pass try: if self.error_noresponse < 0: pass else: # sys.stdout.write("%r\r\n" % self.client.state) while True: if self.retrycheck > 6: break self.retrycheck += 1 if self.client.state is SOCK_CLOSE_STATE: if self.timer1 is not None: self.timer1.cancel() cur_state = self.client.state try: self.client.open() # sys.stdout.write('1 : %r\r\n' % self.client.getsockstate()) # sys.stdout.write("%r\r\n" % self.client.state) if self.client.state is SOCK_OPEN_STATE: sys.stdout.write('[%r] is OPEN\r\n' % (self.serverip)) # sys.stdout.write('[%r] client.working_state is %r\r\n' % (self.serverip, self.client.working_state)) self.msleep(500) except Exception as e: sys.stdout.write('%r\r\n' % e) elif self.client.state is SOCK_OPEN_STATE: self.uploading_size.emit(4) cur_state = self.client.state try: self.client.connect() # sys.stdout.write('2 : %r' % self.client.getsockstate()) if self.client.state is SOCK_CONNECT_STATE: sys.stdout.write('[%r] is CONNECTED\r\n' % (self.serverip)) # sys.stdout.write('[%r] client.working_state is %r\r\n' % (self.serverip, self.client.working_state)) except Exception as e: sys.stdout.write('%r\r\n' % e) elif self.client.state is SOCK_CONNECT_STATE: # if self.client.working_state == idle_state: # sys.stdout.write('3 : %r' % self.client.getsockstate()) try: self.uploading_size.emit(5) while self.remainbytes is not 0: if self.client.working_state == idle_state: if self.remainbytes >= FW_PACKET_SIZE: msg = bytearray(FW_PACKET_SIZE) msg[:] = self.data[self.curr_ptr:self. curr_ptr + FW_PACKET_SIZE] self.client.write(msg) self.sentbyte = FW_PACKET_SIZE # sys.stdout.write('FW_PACKET_SIZE bytes sent from at %r\r\n' % (self.curr_ptr)) sys.stdout.write( '[%s] FW_PACKET_SIZE bytes sent from at %r\r\n' % (self.serverip, self.curr_ptr)) self.curr_ptr += FW_PACKET_SIZE self.remainbytes -= FW_PACKET_SIZE else: self.uploading_size.emit(6) msg = bytearray(self.remainbytes) msg[:] = self.data[self.curr_ptr:self. curr_ptr + self.remainbytes] self.client.write(msg) # sys.stdout.write('Last %r byte sent from at %r \r\n' % (self.remainbytes, self.curr_ptr)) sys.stdout.write( '[%s] Last %r byte sent from at %r \r\n' % (self.serverip, self.remainbytes, self.curr_ptr)) self.curr_ptr += self.remainbytes self.remainbytes = 0 self.sentbyte = self.remainbytes self.client.working_state = datasent_state self.timer1 = threading.Timer( 2.0, self.myTimer) self.timer1.start() elif self.client.working_state == datasent_state: # sys.stdout.write('4 : %r' % self.client.getsockstate()) response = self.client.readbytes(2) if response is not None: if int(binascii.hexlify(response), 16): self.client.working_state = idle_state self.timer1.cancel() self.istimeout = 0 else: print( 'ERROR: No response from device. Stop FW upload...' ) self.client.close() self.upload_result.emit(-1) self.terminate() if self.istimeout is 1: self.istimeout = 0 self.client.working_state = idle_state self.client.close() self.upload_result.emit(-1) self.terminate() self.uploading_size.emit(7) except Exception as e: sys.stdout.write('%r\r\n' % e) response = "" break print('retrycheck: %d' % self.retrycheck) if self.retrycheck > 6 or self.error_noresponse < 0: sys.stdout.write('Device [%s] firmware upload fail.\r\n' % (self.dest_mac)) self.upload_result.emit(-1) elif self.error_noresponse >= 0: self.uploading_size.emit(8) sys.stdout.write('Device [%s] firmware upload success!\r\n' % (self.dest_mac)) self.upload_result.emit(1) # send FIN packet self.msleep(500) self.client.shutdown() if 'TCP' in self.sock_type: self.conf_sock.shutdown() except Exception as e: self.error_flag.emit(-3) sys.stdout.write('%r\r\n' % e) finally: pass def sock_close(self): # 기존 연결 fin if self.tcp_sock is not None: if self.tcp_sock.state is not SOCK_CLOSE_STATE: self.tcp_sock.shutdown() if self.conf_sock is not None: self.conf_sock.shutdown() def tcpConnection(self, serverip, port): retrynum = 0 self.tcp_sock = TCPClient(2, serverip, port) print('sock state: %r' % (self.tcp_sock.state)) while True: if retrynum > 6: break retrynum += 1 if self.tcp_sock.state is SOCK_CLOSE_STATE: self.tcp_sock.shutdown() cur_state = self.tcp_sock.state try: self.tcp_sock.open() if self.tcp_sock.state is SOCK_OPEN_STATE: print('[%r] is OPEN' % (serverip)) time.sleep(0.5) except Exception as e: sys.stdout.write('%r\r\n' % e) elif self.tcp_sock.state is SOCK_OPEN_STATE: cur_state = self.tcp_sock.state try: self.tcp_sock.connect() if self.tcp_sock.state is SOCK_CONNECT_STATE: print('[%r] is CONNECTED' % (serverip)) except Exception as e: sys.stdout.write('%r\r\n' % e) elif self.tcp_sock.state is SOCK_CONNECT_STATE: break if retrynum > 6: sys.stdout.write('Device [%s] TCP connection failed.\r\n' % (serverip)) return None else: sys.stdout.write('Device [%s] TCP connected\r\n' % (serverip)) return self.tcp_sock def SocketConfig(self): # Broadcast if 'UDP' in self.sock_type: self.conf_sock = WIZUDPSock(5000, 50001) self.conf_sock.open() # TCP unicast elif 'TCP' in self.sock_type: print('upload_unicast: ip: %r, port: %r' % (self.ip_addr, self.port)) self.conf_sock = self.tcpConnection(self.ip_addr, self.port) if self.conf_sock is None: # self.isConnected = False print('TCP connection failed!: %s' % self.conf_sock) self.error_flag.emit(-3) self.terminate() else: self.isConnected = True
class FWUploadThread(threading.Thread): # initialization def __init__(self, idcode, conf_sock, sock_type): threading.Thread.__init__(self) self.dest_mac = None self.bin_filename = None self.fd = None self.data = None self.client = None self.timer1 = None self.istimeout = 0 self.serverip = None self.serverport = None self.idcode = idcode self.sentbyte = 0 self.sock_type = sock_type self.conf_sock = conf_sock conf_sock.open() self.wizmsghangler = WIZMSGHandler(conf_sock) def setparam(self, dest_mac, binaryfile): self.dest_mac = dest_mac self.bin_filename = binaryfile self.fd = open(self.bin_filename, "rb") self.data = self.fd.read(-1) self.remainbytes = len(self.data) self.curr_ptr = 0 sys.stdout.write("\nFirmware file size: %r\n\n" % len(self.data)) def myTimer(self): # sys.stdout.write('timer1 timeout\r\n') self.istimeout = 1 def jumpToApp(self): cmd_list = [] # boot mode change: App boot mode print("[%s] Jump to app boot mode" % self.dest_mac) cmd_list.append(["MA", self.dest_mac]) cmd_list.append(["PW", self.idcode]) cmd_list.append(["AB", ""]) self.wizmsghangler.makecommands(cmd_list, OP_FWUP) if self.sock_type == "udp": self.wizmsghangler.sendcommands() else: self.wizmsghangler.sendcommandsTCP() if self.conf_sock != None: self.conf_sock.shutdown() time.sleep(1) # print('jumpToApp cmd_list: %s' % cmd_list) # def run(self): def sendCmd(self, command): cmd_list = [] self.resp = None # Send FW UPload request message cmd_list.append(["MA", self.dest_mac]) cmd_list.append(["PW", self.idcode]) cmd_list.append([command, str(len(self.data))]) # sys.stdout.write("cmd_list: %s\r\n" % cmd_list) self.wizmsghangler.makecommands(cmd_list, OP_FWUP) # if no reponse from device, retry for several times. for i in range(3): if self.sock_type == "udp": self.wizmsghangler.sendcommands() else: self.wizmsghangler.sendcommandsTCP() self.resp = self.wizmsghangler.parseresponse() if self.resp != "": break time.sleep(1) def run(self): if self.resp != "": resp = self.resp.decode("utf-8") # print('resp', resp) params = resp.split(":") sys.stdout.write("Dest IP: %s, Dest Port num: %r\r\n" % (params[0], int(params[1]))) self.serverip = params[0] self.serverport = int(params[1]) # network reachable check os.system("ping " + ("-n 1 " if sys.platform.lower() == "win32" else "-c 1 ") + self.serverip) ping_reponse = os.system( "ping " + ("-n 1 " if sys.platform.lower() == "win32" else "-c 1 ") + self.serverip ) # ping_reponse = os.system('ping -n 1 ' + params[0]) if ping_reponse == 0: print("Device[%s] network OK" % self.dest_mac) else: print( "<Ping Error>: Device[%s]: %s is unreachable.\n\tRefer --multiset or --ip options to set IP address." % (self.dest_mac, self.serverip) ) sys.exit(0) else: print("@@@@@ Device[%s]: No response from device. Check the network or device status." % (self.dest_mac)) sys.exit(0) try: self.client = TCPClient(2, params[0], int(params[1])) except: pass self.retrycheck = 0 try: # sys.stdout.write("%r\r\n" % self.client.state) while True: if self.retrycheck > 20: break self.retrycheck += 1 if self.client.state == SOCK_CLOSE_STATE: if self.timer1 != None: self.timer1.cancel() cur_state = self.client.state try: self.client.open() # sys.stdout.write('1 : %r\r\n' % self.client.getsockstate()) # sys.stdout.write("%r\r\n" % self.client.state) if self.client.state == SOCK_OPEN_STATE: # sys.stdout.write('[%r] is OPEN\r\n' % (self.serverip)) sys.stdout.write("[%r] is OPEN | %s\r\n" % (self.serverip, self.bin_filename)) # sys.stdout.write('[%r] client.working_state is %r\r\n' % (self.serverip, self.client.working_state)) time.sleep(0.1) except Exception as e: print(e) elif self.client.state == SOCK_OPEN_STATE: cur_state = self.client.state # time.sleep(2) try: self.client.connect() # sys.stdout.write('2 : %r' % self.client.getsockstate()) if self.client.state == SOCK_CONNECT_STATE: # sys.stdout.write('[%r] is CONNECTED\r\n' % (self.serverip)) sys.stdout.write("[%r] is CONNECTED | %s\r\n" % (self.serverip, self.bin_filename)) # sys.stdout.write('[%r] client.working_state is %r\r\n' % (self.serverip, self.client.working_state)) # time.sleep(1) except Exception as e: print(e) elif self.client.state == SOCK_CONNECT_STATE: # if self.client.working_state == idle_state: # sys.stdout.write('3 : %r' % self.client.getsockstate()) try: while self.remainbytes != 0: if self.client.working_state == idle_state: if self.remainbytes >= 1024: msg = bytearray(1024) msg[:] = self.data[self.curr_ptr : self.curr_ptr + 1024] self.client.write(msg) self.sentbyte = 1024 # sys.stdout.write('1024 bytes sent from at %r\r\n' % (self.curr_ptr)) sys.stdout.write( "[%s] 1024 bytes sent from at %r\r\n" % (self.serverip, self.curr_ptr) ) self.curr_ptr += 1024 self.remainbytes -= 1024 else: msg = bytearray(self.remainbytes) msg[:] = self.data[self.curr_ptr : self.curr_ptr + self.remainbytes] self.client.write(msg) # sys.stdout.write('Last %r byte sent from at %r \r\n' % (self.remainbytes, self.curr_ptr)) sys.stdout.write( "[%s] Last %r byte sent from at %r \r\n" % (self.serverip, self.remainbytes, self.curr_ptr) ) self.curr_ptr += self.remainbytes self.remainbytes = 0 self.sentbyte = self.remainbytes self.client.working_state = datasent_state self.timer1 = threading.Timer(2.0, self.myTimer) self.timer1.start() elif self.client.working_state == datasent_state: # sys.stdout.write('4 : %r' % self.client.getsockstate()) response = self.client.readbytes(2) if response != None: if int(binascii.hexlify(response), 16): self.client.working_state = idle_state self.timer1.cancel() self.istimeout = 0 else: print( f"ERROR: Device[{self.dest_mac}]: No response from device. Stop FW upload..." ) self.client.close() sys.exit(0) if self.istimeout == 1: self.istimeout = 0 self.client.working_state = idle_state self.client.close() sys.exit(0) except Exception as e: print(e) response = "" break if self.retrycheck > 20: print(f"Device [{self.dest_mac}] firmware upload fail. (file: {self.bin_filename})\r\n") else: print(f"Device [{self.dest_mac}] firmware upload success! (file: {self.bin_filename})\r\n") # for send FIN packet time.sleep(1) self.client.shutdown() except (KeyboardInterrupt, SystemExit): print(e) finally: pass
class TCPClientThread(threading.Thread): def __init__(self, serverip, serverport, trycount): threading.Thread.__init__(self) self.serverip = serverip self.serverport = serverport # self.f = fd self.timer1 = None self.istimeout = 0 self.totaltrycount = 0 self.successcount = 0 self.failcount = 0 self.trycount = trycount self.client = None def stop(self): if self.client is not None: self.client.close() self.client = None if self.timer1 is not None: if self.timer1.is_alive(): self.timer1.cancel() # sys.stdout.write('thread for %r ' % self.serverip) sys.stdout.write('thread for %s:%s ' % (self.serverip, self.serverport)) sys.stdout.write('is shutdowning\r\n') # if not self.f.closed: if self.totaltrycount > 0: logstr = "======================================\r\n" logstr = logstr + '[' + self.serverip + ':' + \ str(self.serverport) + '] stopped at ' + strftime("%d %b %Y %H:%M:%S", localtime()) + '\r\n' logstr = logstr + 'Total try: ' + str(self.totaltrycount) + '\r\n' logstr = logstr + 'Success count: ' + str( self.successcount) + '\r\n' logstr = logstr + 'Fail count: ' + str(self.failcount) + '\r\n' logstr = logstr + 'Success Rate: ' + "{0:.1f}".format( float(self.successcount) / float(self.totaltrycount) * 100) + '%\r\n' logstr = logstr + '======================================\r\n' sys.stdout.write(logstr) else: logstr = "======================================\r\n" logstr = logstr + '[' + self.serverip + ':' + \ str(self.serverport) + '] stopped at ' + strftime("%d %b %Y %H:%M:%S", localtime()) + '\r\n' logstr = logstr + 'Connection Failed\r\n' logstr = logstr + '======================================\r\n' sys.stdout.write(logstr) # self.f.write(logstr) # if sys.version_info < (2, 9): # self._Thread__stop() def myTimer(self): sys.stdout.write('timer1 timeout\r\n') self.istimeout = 1 def run(self): SOCK_CLOSE_STATE = 1 SOCK_OPENTRY_STATE = 2 SOCK_OPEN_STATE = 3 SOCK_CONNECTTRY_STATE = 4 SOCK_CONNECT_STATE = 5 idle_state = 1 datasent_state = 2 sys.stdout.write('thread for %r ' % self.serverip) sys.stdout.write('is starting\r\n') # TCPClient instance creation try: self.client = TCPClient(2, self.serverip, self.serverport) except: self.stop() # time.sleep(2) # filename = self.serverip + '_log.txt' # print(filename) IsTimeout = 0 # self.f = open(filename, 'w+') # self.f = fd try: while True: if self.client.state is SOCK_CLOSE_STATE: if self.timer1 is not None: self.timer1.cancel() cur_state = self.client.state self.client.open() # sys.stdout.write('1 : %r' % self.client.getsockstate()) if self.client.state is SOCK_OPEN_STATE: sys.stdout.write('[%r] is OPEN\r\n' % (self.serverip)) # sys.stdout.write('[%s:%s] is OPEN\r\n' % (self.serverip, self.serverport)) # sys.stdout.write('[%r] client.working_state is %r\r\n' % (self.serverip, self.client.working_state)) time.sleep(1) elif self.client.state is SOCK_OPEN_STATE: cur_state = self.client.state self.client.connect() # sys.stdout.write('2 : %r' % self.client.getsockstate()) if self.client.state is SOCK_CONNECT_STATE: sys.stdout.write('[%r] is CONNECTED\r\n' % (self.serverip)) # sys.stdout.write('[%s:%s] is CONNECTED\r\n' % (self.serverip, self.serverport)) # sys.stdout.write('[%r] client.working_state is %r\r\n' % (self.serverip, self.client.working_state)) time.sleep(1) elif self.client.state is SOCK_CONNECT_STATE: if self.client.working_state == idle_state: # sys.stdout.write('3 : %r' % self.client.getsockstate()) try: if self.trycount is not -1 and self.totaltrycount >= self.trycount: break # self.client.write(msg) self.client.write(msg) logmsg = msg.decode() logstr = '[' + self.serverip + '] sent ' + logmsg + '\r\n' sys.stdout.write(logstr) # self.f.write(logstr) self.client.working_state = datasent_state self.istimeout = 0 self.totaltrycount += 1 self.timer1 = threading.Timer(2.0, self.myTimer) self.timer1.start() # sys.stdout.write('timer 1 started\r\n') except Exception as e: time.sleep(2) sys.stdout.write('===> 3 %r\r\n' % e) elif self.client.working_state == datasent_state: # sys.stdout.write('4 : %r' % self.client.getsockstate()) # minimum delay time.sleep(0.05) # time.sleep(1.5) response = self.client.readline() if (response != ""): logstr = '[' + self.serverip + '] received ' + response.decode( ) + '\r\n' sys.stdout.write(logstr) sys.stdout.flush() # self.f.write(logstr) self.timer1.cancel() # sys.stdout.write('timer 1 cancelled\r\n') self.istimeout = 0 if (msg in response): logstr = '[' + self.serverip + ']' + strftime( " %d %b %Y %H:%M:%S", localtime()) + ': success, ' self.successcount += 1 # sys.stdout.write(logstr) # self.f.write(logstr) else: logstr = '[' + self.serverip + ']' + strftime( " %d %b %Y %H:%M:%S", localtime()) + ': fail by broken data, ' # sys.stdout.write(logstr) self.failcount += 1 # self.f.write(logstr) logstr = logstr + 'success rate : ' \ + "{0:.2f}".format(float(self.successcount) / float(self.totaltrycount) * 100) + '%, [' \ + str(self.successcount) + '/' + str(self.totaltrycount) + ']\r\n' sys.stdout.write(logstr) # self.f.write(logstr) time.sleep(0.1) self.client.working_state = idle_state if self.istimeout is 1: # self.timer1.cancel() self.istimeout = 0 logstr = '[' + self.serverip + ']' + strftime( " %d %b %Y %H:%M:%S", localtime()) + ': fail by timeout, ' # sys.stdout.write(logstr) self.failcount += 1 # self.f.write(logstr) logstr = logstr + ' success rate : ' \ + "{0:.2f}".format(float(self.successcount) / float(self.totaltrycount) * 100) + '% [' \ + str(self.successcount) + '/' + str(self.totaltrycount) + ']\r\n' sys.stdout.write(logstr) # self.f.write(logstr) # time.sleep(3) self.client.working_state = idle_state self.client.close() response = "" # time.sleep(5) # cur_state = self.client.state # self.client.close() # if self.client.state is SOCK_CLOSE_STATE: # sys.stdout.write('[%r] is CLOSED\r\n' % (self.serverip)) # time.sleep(2) except (KeyboardInterrupt, SystemExit): sys.stdout.write('Keyboard interrupt occured!') sys.exit(0) finally: self.stop()
class FWUploadThread(threading.Thread): # initialization # def __init__(self, log_level): def __init__(self): threading.Thread.__init__(self) self.dest_mac = None self.bin_filename = None self.fd = None self.data = None self.client = None self.timer1 = None self.istimeout = 0 self.serverip = None self.serverport = None self.sentbyte = 0 conf_sock = WIZUDPSock(5000, 50001) conf_sock.open() self.wizmsghangler = WIZMSGHandler(conf_sock) def setparam(self, dest_mac, binaryfile): self.dest_mac = dest_mac self.bin_filename = binaryfile self.fd = open(self.bin_filename, "rb") self.data = self.fd.read(-1) self.remainbytes = len(self.data) self.curr_ptr = 0 sys.stdout.write("Firmware file size: %r\n\n" % len(self.data)) def myTimer(self): # sys.stdout.write('timer1 timeout\r\n') self.istimeout = 1 def jumpToApp(self): cmd_list = [] # boot mode change: App boot mode cmd_list.append(["MA", self.dest_mac]) cmd_list.append(["PW", " "]) cmd_list.append(["AB", ""]) self.wizmsghangler.makecommands(cmd_list, OP_FWUP) self.wizmsghangler.sendcommands() def run(self): cmd_list = [] # Send FW UPload request message cmd_list.append(["MA", self.dest_mac]) cmd_list.append(["PW", " "]) cmd_list.append(["FW", str(len(self.data))]) # sys.stdout.write("cmd_list: %s\r\n" % cmd_list) self.wizmsghangler.makecommands(cmd_list, OP_FWUP) self.wizmsghangler.sendcommands() resp = self.wizmsghangler.parseresponse() if resp is not '': resp = resp.decode('utf-8') # print('resp', resp) params = resp.split(':') sys.stdout.write('Dest IP: %s, Dest Port num: %r\r\n' % (params[0], int(params[1]))) self.serverip = params[0] self.serverport = int(params[1]) # # network reachable check # os.system("ping " + ("-n 1 " if sys.platform.lower()=="win32" else "-c 1 ") + self.serverip) # ping_reponse = os.system("ping " + ("-n 1 " if sys.platform.lower()=="win32" else "-c 1 ") + self.serverip) # # ping_reponse = os.system('ping -n 1 ' + params[0]) # if ping_reponse == 0: # print('Device[%s] network OK' % self.dest_mac) # else: # print('<ERROR>: Device[%s]: %s is unreachable.\n\tRefer --multiset or --ip options to set IP address.' % (self.dest_mac, self.serverip)) # sys.exit(0) else: print( 'No response from device. Check the network or device status.') sys.exit(0) try: self.client = TCPClient(2, params[0], int(params[1])) except: pass try: # sys.stdout.write("%r\r\n" % self.client.state) while True: if self.client.state is SOCK_CLOSE_STATE: if self.timer1 is not None: self.timer1.cancel() cur_state = self.client.state try: self.client.open() # sys.stdout.write('1 : %r\r\n' % self.client.getsockstate()) # sys.stdout.write("%r\r\n" % self.client.state) if self.client.state is SOCK_OPEN_STATE: sys.stdout.write('[%r] is OPEN\r\n' % (self.serverip)) # sys.stdout.write('[%r] client.working_state is %r\r\n' % (self.serverip, self.client.working_state)) time.sleep(0.5) except Exception as e: sys.stdout.write('%r\r\n' % e) elif self.client.state is SOCK_OPEN_STATE: cur_state = self.client.state # time.sleep(2) try: self.client.connect() # sys.stdout.write('2 : %r' % self.client.getsockstate()) if self.client.state is SOCK_CONNECT_STATE: sys.stdout.write('[%r] is CONNECTED\r\n' % (self.serverip)) # sys.stdout.write('[%r] client.working_state is %r\r\n' % (self.serverip, self.client.working_state)) # time.sleep(1) except Exception as e: sys.stdout.write('%r\r\n' % e) elif self.client.state is SOCK_CONNECT_STATE: # if self.client.working_state == idle_state: # sys.stdout.write('3 : %r' % self.client.getsockstate()) try: while self.remainbytes is not 0: if self.client.working_state == idle_state: if self.remainbytes >= 1024: msg = bytearray(1024) msg[:] = self.data[self. curr_ptr:self.curr_ptr + 1024] self.client.write(msg) self.sentbyte = 1024 # sys.stdout.write('1024 bytes sent from at %r\r\n' % (self.curr_ptr)) sys.stdout.write( '[%s] 1024 bytes sent from at %r\r\n' % (self.serverip, self.curr_ptr)) self.curr_ptr += 1024 self.remainbytes -= 1024 else: msg = bytearray(self.remainbytes) msg[:] = self.data[self. curr_ptr:self.curr_ptr + self.remainbytes] self.client.write(msg) # sys.stdout.write('Last %r byte sent from at %r \r\n' % (self.remainbytes, self.curr_ptr)) sys.stdout.write( '[%s] Last %r byte sent from at %r \r\n' % (self.serverip, self.remainbytes, self.curr_ptr)) self.curr_ptr += self.remainbytes self.remainbytes = 0 self.sentbyte = self.remainbytes self.client.working_state = datasent_state self.timer1 = threading.Timer( 2.0, self.myTimer) self.timer1.start() elif self.client.working_state == datasent_state: # sys.stdout.write('4 : %r' % self.client.getsockstate()) response = self.client.readbytes(2) if response is not None: if int(binascii.hexlify(response), 16): self.client.working_state = idle_state self.timer1.cancel() self.istimeout = 0 else: print( 'ERROR: No response from device. Stop FW upload...' ) self.client.close() sys.exit(0) if self.istimeout is 1: self.istimeout = 0 self.client.working_state = idle_state self.client.close() sys.exit(0) except Exception as e: sys.stdout.write('%r\r\n' % e) response = "" break sys.stdout.write('Device [%s] firmware upload success!\r\n' % (self.dest_mac)) # for send FIN packet time.sleep(2.5) self.client.shutdown() except (KeyboardInterrupt, SystemExit): sys.stdout.write('%r\r\n' % e) finally: pass