-
Notifications
You must be signed in to change notification settings - Fork 11
/
FWUploadThread.py
334 lines (286 loc) · 13.4 KB
/
FWUploadThread.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
#!/usr/bin/python
from PyQt5.QtCore import QThread, pyqtSignal
from wizsocket.TCPClient import TCPClient
from WIZUDPSock import WIZUDPSock
from WIZMSGHandler import WIZMSGHandler
from WIZMakeCMD import SECURITY_DEVICE
from constants import Opcode, SockState
from utils import logger
import binascii
import time
import threading
idle_state = 1
datasent_state = 2
FW_PACKET_SIZE = 1024
# FW_PACKET_SIZE = 2048
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, mn_list):
QThread.__init__(self)
self.logger = logger
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
self.mn_list = mn_list
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):
self.logger.info('timer1 timeout')
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', Opcode.OP_FWUP, 2)
elif 'UDP' in self.sock_type:
self.wizmsghangler = WIZMSGHandler(
self.conf_sock, cmd_list, 'udp', Opcode.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])
cmd_list.append([command, str(self.filesize)])
self.logger.debug(f'sendCmd() cmd_list => {cmd_list}')
if 'TCP' in self.sock_type:
self.wizmsghangler = WIZMSGHandler(
self.conf_sock, cmd_list, 'tcp', Opcode.OP_FWUP, 2)
elif 'UDP' in self.sock_type:
self.wizmsghangler = WIZMSGHandler(
self.conf_sock, cmd_list, 'udp', Opcode.OP_FWUP, 2)
# 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 != '':
break
self.msleep(500)
self.uploading_size.emit(2)
def run(self):
self.setparam()
# wiz2000/wiz510ssl: not use 'AB' command
if self.mn_list in SECURITY_DEVICE:
self.logger.info(f'Security device firmware upload: {self.mn_list}')
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 != '' and self.resp is not None:
resp = self.resp.decode('utf-8')
# print('resp', resp)
params = resp.split(':')
self.logger.info(f'Dest IP: {params[0]}, Dest Port num: {int(params[1])}')
self.serverip = params[0]
self.serverport = int(params[1])
self.uploading_size.emit(3)
else:
params = None
self.logger.warning('No response from device. Check the network or device status.')
self.error_flag.emit(-1)
self.error_noresponse = -1
try:
if params is not None:
self.client = TCPClient(2, params[0], int(params[1]))
except Exception as e:
self.logger.error(str(e))
try:
if self.error_noresponse < 0:
pass
else:
# print("%r\r\n" % self.client.state)
while True:
if self.retrycheck > 6:
break
self.retrycheck += 1
if self.client.state == SockState.SOCK_CLOSE:
if self.timer1 is not None:
self.timer1.cancel()
# cur_state = self.client.state
try:
self.client.open()
# self.logger.debug('1 : %r' % self.client.getsockstate())
# print("%r\r\n" % self.client.state)
if self.client.state == SockState.SOCK_OPEN:
self.logger.info('[%r] is OPEN' % (self.serverip))
# print('[%r] client.working_state == %r' % (self.serverip, self.client.working_state))
self.msleep(500)
except Exception as e:
self.logger.error(str(e))
elif self.client.state == SockState.SOCK_OPEN:
self.uploading_size.emit(4)
# cur_state = self.client.state
try:
self.client.connect()
# self.logger.debug('2 : %r' % self.client.getsockstate())
if self.client.state == SockState.SOCK_CONNECT:
self.logger.info('[%r] is CONNECTED' % (self.serverip))
# print('[%r] client.working_state == %r' % (self.serverip, self.client.working_state))
except Exception as e:
print(e)
elif self.client.state == SockState.SOCK_CONNECT:
# if self.client.working_state == idle_state:
# self.logger.debug('3 : %r' % self.client.getsockstate())
try:
self.uploading_size.emit(5)
while self.remainbytes != 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
# print('FW_PACKET_SIZE bytes sent from at %r' % (self.curr_ptr))
self.logger.info('[%s] FW_PACKET_SIZE bytes sent from at %r' % (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)
# print('Last %r byte sent from at %r ' % (self.remainbytes, self.curr_ptr))
self.logger.info('[%s] Last %r byte sent from at %r' % (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(3.0, self.myTimer)
self.timer1.start()
elif self.client.working_state == datasent_state:
# self.logger.debug('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:
self.logger.error('ERROR: No response from device. Stop FW upload...')
self.client.close()
self.upload_result.emit(-1)
self.terminate()
if self.istimeout == 1:
self.logger.warning('Timeout occured')
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:
self.logger.error(str(e))
response = ""
break
self.logger.info('retrycheck: %d' % self.retrycheck)
if self.retrycheck > 6 or self.error_noresponse < 0:
self.logger.error(f'Device [{self.dest_mac}] firmware upload failed.')
self.upload_result.emit(-1)
elif self.error_noresponse >= 0:
self.uploading_size.emit(8)
self.logger.info(f'Device [{self.dest_mac}] firmware upload success!')
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)
self.logger.error(str(e))
finally:
pass
def sock_close(self):
# 기존 연결 fin
if self.tcp_sock is not None:
if self.tcp_sock.state != SockState.SOCK_CLOSE:
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 == SockState.SOCK_CLOSE:
self.tcp_sock.shutdown()
# cur_state = self.tcp_sock.state
try:
self.tcp_sock.open()
if self.tcp_sock.state == SockState.SOCK_OPEN:
self.logger.info('[%r] is OPEN' % (serverip))
time.sleep(0.5)
except Exception as e:
self.logger.error(str(e))
elif self.tcp_sock.state == SockState.SOCK_OPEN:
# cur_state = self.tcp_sock.state
try:
self.tcp_sock.connect()
if self.tcp_sock.state == SockState.SOCK_CONNECT:
self.logger.info('[%r] is CONNECTED' % (serverip))
except Exception as e:
self.logger.error(str(e))
elif self.tcp_sock.state == SockState.SOCK_CONNECT:
break
if retrynum > 6:
self.logger.info('Device [%s] TCP connection failed.' % (serverip))
return None
else:
self.logger.info('Device [%s] TCP connected' % (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:
self.logger.info(f'Upload with TCP unicast: ip: {self.ip_addr}, port: {self.port}')
self.conf_sock = self.tcpConnection(self.ip_addr, self.port)
if self.conf_sock is None:
# self.isConnected = False
self.logger.warning('TCP connection failed!: %s' % self.conf_sock)
self.error_flag.emit(-2)
self.terminate()
else:
self.isConnected = True