Skip to content

Commit ece4c2a

Browse files
authored
Merge pull request #18 from Windham-High-School/6-http-rx-response
Fixed rx framework, header concat
2 parents 78701ab + 7eb71a8 commit ece4c2a

File tree

1 file changed

+17
-6
lines changed

1 file changed

+17
-6
lines changed

servercom/implementations/circuitpy.py

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -218,6 +218,7 @@ def radio(self):
218218
return wifi.radio
219219

220220
def rx_bytes(self) -> bytes:
221+
total_length: int = None
221222
response = b""
222223
while True:
223224
buf = bytearray(256)
@@ -228,12 +229,21 @@ def rx_bytes(self) -> bytes:
228229
recvd = 0
229230
else:
230231
raise
231-
response += buf
232+
response += bytes(buf).replace(b'\x00', b'')
232233
del buf
233234
collect()
234235
if self.v:
235236
print(f"Received {recvd} bytes")
236-
if recvd == 0:
237+
if response.endswith(b'\r\n\r\n'):
238+
header_chunks = response.split(b'\r\n')
239+
for header in header_chunks:
240+
if header.startswith(b'Content-Length: '):
241+
total_length = len(response) + int(header.split(b' ')[1])
242+
break
243+
if recvd == 0 or (
244+
total_length is not None and \
245+
len(response) >= total_length
246+
):
237247
del recvd
238248
collect()
239249
break
@@ -267,8 +277,8 @@ def _do_request(
267277
f"{method} {path} HTTP/1.1\r\n" +
268278
"Host: api.local\r\n" +
269279
"Connection: close\r\n" +
270-
f"Authorization: Basic {auth_str}" +
271-
'\r\n'.join(headers) + "\r\n"
280+
f"Authorization: Basic {auth_str}\r\n" +
281+
'\r\n'.join(headers)
272282
)
273283
del auth_str
274284
collect()
@@ -283,7 +293,8 @@ def _do_request(
283293
f"Content-Length: {len(body)}\r\n" +
284294
f"\r\n{body}\r\n"
285295
)
286-
req_text += '\r\n'
296+
else:
297+
req_text += '\r\n\r\n'
287298

288299
if self.v:
289300
print("Sending request...")
@@ -302,7 +313,7 @@ def _do_request(
302313
collect()
303314
if self.v:
304315
print("Receiving response...")
305-
self.wrapped_socket.setblocking(False)
316+
self.wrapped_socket.settimeout(self.conf.TIMEOUT)
306317
response = self.rx_bytes()
307318
except Exception as e:
308319
if self.v:

0 commit comments

Comments
 (0)