-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCommunicationController.py
More file actions
339 lines (289 loc) · 15.8 KB
/
CommunicationController.py
File metadata and controls
339 lines (289 loc) · 15.8 KB
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
335
336
337
338
import socket, queue as q, Message as ms, ControllerEvent as ev
import threading, select, random, time, os, copy
import ControllerCommand
serverIp = '127.0.0.1'
serverPort = 5683
clientPort = 25575
# Communication type by default CON
Com_Type = ms.Type.Confirmable
# default path were files would be stored
DownloadPath = "Downloads/"
class CommunicationController:
__ACK_TIMEOUT = 2 # s
__MAX_RETRANSMIT = 4
__ACK_RANDOM_FACTOR = 5
# Because no negotiation this time
__MAX_SZX = 6
__MAX_BLOCK = 1 << (__MAX_SZX + 4)
__msgIdValue = random.randint(0, 0xFFFF)
__tknValue = random.randint(0, 0XFFFF_FFFF)
def __init__(self, cmdQueue: q.Queue, eventQueue: q.Queue):
self.__sk = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
self.__sk.bind(('0.0.0.0', clientPort))
# Communication with GUI queues
self.__cmdQueue = cmdQueue
self.__eventQueue = eventQueue
# sender socket lock
self.__sendLock = threading.Lock()
#
self.__reqList = list()
#
self.__delayedReq = list()
self.__blockWiseReq = list()
self.__resQueue = q.Queue()
# (token, resourceName, (blocksID))
self.__recvBlock = list()
# (token , (blocksID))
self.__sentBlock = list()
def start(self):
threading.Thread(target=self.listen_for_command, daemon=True).start()
threading.Thread(target=self.receive_responses, daemon=True).start()
threading.Thread(target=self.resolve_response, daemon=True).start()
def send_request(self, message):
with self.__sendLock:
self.__sk.sendto(message, (serverIp, serverPort))
def refresh_lifetime(self):
while True:
for req in self.__reqList: # req is a tuple of request message, timestamp, timeout and retransmit count
if (time.time() - req[1]) > req[2]:
if req[3] > 0:
req[3] -= 1
req[2] *= self.__ACK_RANDOM_FACTOR
req[1] = time.time()
self.__sk.sendto(req[0], (serverIp, serverPort))
else:
self.__cmdQueue.put(
ev.ControllerEvent(ev.EventType.REQUEST_TIMEOUT, ms.Method(req[0].msgCode).name))
self.__reqList.remove(req)
def listen_for_command(self):
while True:
command = self.__cmdQueue.get()
msg: ms.Message = command.getDetails()
if type(command) is ControllerCommand.UploadFile:
file_path = command.extraData
file_size = os.path.getsize(file_path)
num = 0
if file_size > self.__MAX_BLOCK:
# split
szx = self.__MAX_SZX
while file_size > self.__MAX_BLOCK:
msgd = copy.deepcopy(msg)
msgd.addOption(ms.Options.BLOCK1, (((num << 1) + 1) << 3) + szx)
with open(file_path, 'rb') as f:
f.seek(num << (szx + 4))
msgd.addPayload(f.read(self.__MAX_BLOCK))
msgd.setMessageId(self.__msgIdValue)
self.__msgIdValue = self.__msgIdValue + 1
msgd.setToken(self.__tknValue)
self.send_request(msgd.encode())
self.__reqList.append((msgd, time.time(), self.__ACK_TIMEOUT, 4))
num = num + 1
file_size = file_size - self.__MAX_BLOCK
msg.addOption(ms.Options.BLOCK1, (((num << 1) | 0) << 3) | szx)
with open(file_path, 'rb') as f:
f.seek(num << (szx + 4))
msg.addPayload(f.read(self.__MAX_BLOCK))
msg.setMessageId(self.__msgIdValue)
self.__msgIdValue = self.__msgIdValue + 1
msg.setToken(self.__tknValue)
self.__tknValue = self.__tknValue + 1
self.send_request(msg.encode())
self.__reqList.append((msg, time.time(), self.__ACK_TIMEOUT, 4))
self.__cmdQueue.task_done()
continue
else:
with open(file_path, 'rb') as f:
msg.addPayload(f.read())
msg.setMessageId(self.__msgIdValue)
self.__msgIdValue = self.__msgIdValue + 1
msg.setToken(self.__tknValue)
self.__tknValue = self.__tknValue + 1
self.send_request(msg.encode())
self.__reqList.append((msg, time.time(), self.__ACK_TIMEOUT, 4))
self.__cmdQueue.task_done()
def receive_responses(self):
while True:
r, _, _ = select.select([self.__sk], [], [], 1)
if r:
data, _ = self.__sk.recvfrom(4096)
msg = ms.Message()
msg.decode(data)
self.__resQueue.put(msg)
def remove_req(self, req):
for msg in self.__reqList:
if req == msg[0]:
self.__reqList.remove(msg)
return
def resolve_response(self):
while True:
msg_resp: ms.Message = self.__resQueue.get()
self.__resQueue.task_done()
msg_req = None
# Searching to associate a response with a request
if msg_resp.tk_len == 0:
for msg in self.__reqList:
if msg_resp.msgId == msg[0].msgId:
msg_req = msg[0]
break
if msg_req is not None:
if msg_resp.msgType == ms.Type.Acknowledgement:
self.remove_req(msg_req)
self.__delayedReq.append(msg_req)
continue
else:
for msg in self.__reqList:
if msg_resp.token == msg[0].token:
msg_req = msg[0]
break
if msg_req is None: # Might be a response from a delayed request
for msg in self.__delayedReq:
if msg_resp.token == msg.token:
msg_req = msg
break
if msg_req is None:
continue # No matching request for this response (might be a duplicate from a resolved request)
# supposed req is always a method
if msg_req.msgClass != ms.Class.Method:
continue
# Creating events based on request - response types
if msg_resp.msgClass == ms.Class.Success:
if msg_req.msgCode == ms.Method.GET and msg_resp.msgCode == ms.Success.Content:
if int.from_bytes(msg_resp.getOptionVal(ms.Options.CONTENT_FORMAT),
"big") == ms.Content_Format.PLAIN_TEXT:
# Matching for a ListDirectory-event
file_list = list()
index = 0
data = msg_resp.getPayload()
while index < len(data):
val_len = (data[index] & 0xfe) >> 1
file_type = data[index] & 0x01
name = data[index + 1:index + 1 + val_len].decode("utf-8")
file_list.append((file_type, name))
index += 1 + val_len
uri = list()
for ur in msg_req.getOptionValList(ms.Options.URI_PATH):
uri.append(ur.decode("utf-8"))
self.__eventQueue.put(ev.ControllerEvent(ev.EventType.FILE_LIST, (file_list, uri)))
self.remove_req(msg_req)
continue
if int.from_bytes(msg_resp.getOptionVal(ms.Options.CONTENT_FORMAT),
"big") == ms.Content_Format.OCTET_STREAM:
# Matching for a FileDownloaded-event
location = list()
for lc in msg_req.getOptionValList(ms.Options.URI_PATH):
location.append(lc.decode("utf-8"))
if msg_resp.getOptionVal(ms.Options.BLOCK2) is None:
with open(os.path.join(DownloadPath, location[-1]), 'wb') as f:
f.write(msg_resp.getPayload())
f.close()
else:
# receive blocks
block2 = int.from_bytes(msg_resp.getOptionVal(ms.Options.BLOCK2), 'big')
szx = block2 & 0x7
m = (block2 & 0x8) >> 3
num = block2 >> 4
file_path = os.path.join(DownloadPath, location[-1])
if num == 0:
self.__recvBlock.append((msg_resp.token, file_path, list().append(0)))
else:
for trz in self.__recvBlock:
if trz[0] == msg_resp.token:
file_path = trz[1]
# trz[2].append(num)
break
if not os.path.exists(file_path):
with (open(file_path, 'w') as f):
pass
with open(file_path, 'r+b') as f:
f.seek(num << (szx + 4))
f.write(msg_resp.getPayload())
if m == 1:
num = num + 1
nextBlock = ms.Message(Com_Type, ms.Class.Method, ms.Method.GET)
nextBlock.token = msg_resp.token
nextBlock.msgId = self.__msgIdValue
self.__msgIdValue = self.__msgIdValue + 1
nextBlock.addOption(ms.Options.BLOCK2, (num << 4) + szx)
for op in msg_resp.getOptionValList(ms.Options.URI_PATH):
nextBlock.addOption(ms.Options.URI_PATH, op)
self.send_request(nextBlock.encode())
self.__reqList.append((nextBlock, time.time(), self.__ACK_TIMEOUT, 4))
self.remove_req(msg_req)
continue
self.__eventQueue.put(ev.ControllerEvent(ev.EventType.FILE_CONTENT, location[-1]))
self.remove_req(msg_req)
continue
if msg_req.msgCode == ms.Method.POST and (
msg_resp.msgCode == ms.Success.Created or msg_resp.msgCode == ms.Success.Changed):
location = list()
for lc in msg_resp.getOptionValList(ms.Options.LOCATION_PATH):
location.append(lc.decode("utf-8"))
# Matching for a FolderCreated-event
if int.from_bytes(msg_req.getOptionVal(ms.Options.CONTENT_FORMAT),
'big') == ms.Content_Format.PLAIN_TEXT:
event = ev.ControllerEvent(ev.EventType.FOLDER_CREATED, location)
self.__eventQueue.put(event)
self.remove_req(msg_req)
continue
# Matching for a FileUploaded-event
if int.from_bytes(msg_req.getOptionVal(ms.Options.CONTENT_FORMAT),
'big') == ms.Content_Format.OCTET_STREAM:
# if msg_resp.getOptionVal(ms.Options.BLOCK1) is None:
# for e in self.__sentBlock:
# if
# continue
#
# self.__sentBlock = list()
event = ev.ControllerEvent(ev.EventType.FILE_UPLOADED, location)
self.__eventQueue.put(event)
self.remove_req(msg_req)
continue
if msg_req.msgCode == ms.Method.PUT and msg_resp.msgCode == ms.Success.Changed:
# Matching for a FileRenamed-event
location = list()
for lc in msg_resp.getOptionValList(ms.Options.LOCATION_PATH):
location.append(lc.decode("utf-8"))
event = ev.ControllerEvent(ev.EventType.RESOURCE_CHANGED, location)
self.__eventQueue.put(event)
self.remove_req(msg_req)
continue
if msg_req.msgCode == ms.Method.DELETE and msg_resp.msgCode == ms.Success.Deleted:
# Matching for a FileDeleted-event
uri = list()
for ur in msg_req.getOptionValList(ms.Options.URI_PATH):
uri.append(ur.decode("utf-8"))
event = ev.ControllerEvent(ev.EventType.FILE_DELETED, uri)
self.__eventQueue.put(event)
self.remove_req(msg_req)
continue
if msg_req.msgCode == ms.Method.HEAD and msg_resp.msgCode == ms.Success.Content:
# Matching for a FileHeader-event
uri = list()
for ur in msg_resp.getOptionValList(ms.Options.URI_PATH):
uri.append(ur.decode("utf-8"))
event = ev.ControllerEvent(ev.EventType.FILE_HEADER,
(uri, msg_resp.getPayload().decode("utf-8")))
self.__eventQueue.put(event)
self.remove_req(msg_req)
continue
if msg_resp.msgClass == ms.Class.Client_Error or msg_resp.msgClass == ms.Class.Server_Error:
prompt = ""
if (msg_resp.getOptionVal(ms.Options.BLOCK1) is None) and (
msg_resp.getOptionVal(ms.Options.BLOCK2) is None):
err_msg = ms.Class(msg_resp.msgClass).name + ", "
if msg_resp.msgClass == ms.Class.Server_Error:
err_msg += ms.Server_Error(msg_resp.msgCode).name
else:
err_msg += ms.Client_Error(msg_resp.msgCode).name
prompt = ms.Method(msg_req.msgCode).name + " request error: " + err_msg
if msg_resp.getOptionVal(ms.Options.BLOCK2) is not None:
transaction = None
for trz in self.__recvBlock:
if trz[0] == msg_resp.token:
transaction = trz
break
if transaction is not None:
prompt = "Error while downloading " + transaction[1]
self.__recvBlock.remove(transaction)
self.__eventQueue.put(ev.ControllerEvent(ev.EventType.REQUEST_FAILED, prompt))
self.remove_req(msg_req)