chore(led-driver): add http_poll client and UDP/mDNS test helpers
Made-with: Cursor
This commit is contained in:
68
src/http_poll.py
Normal file
68
src/http_poll.py
Normal file
@@ -0,0 +1,68 @@
|
||||
"""Minimal HTTP/1.1 POST JSON client for driver long-poll (MicroPython)."""
|
||||
|
||||
import json
|
||||
import socket
|
||||
|
||||
|
||||
def _send_all(sock, data):
|
||||
n = 0
|
||||
while n < len(data):
|
||||
m = sock.send(data[n:])
|
||||
if m <= 0:
|
||||
raise OSError("socket send failed")
|
||||
n += m
|
||||
|
||||
|
||||
def _read_http_json_body(sock, max_headers=8192):
|
||||
buf = b""
|
||||
while b"\r\n\r\n" not in buf:
|
||||
chunk = sock.recv(256)
|
||||
if not chunk:
|
||||
break
|
||||
buf += chunk
|
||||
if len(buf) > max_headers:
|
||||
raise OSError("response headers too large")
|
||||
if b"\r\n\r\n" not in buf:
|
||||
raise OSError("incomplete response headers")
|
||||
head, rest = buf.split(b"\r\n\r\n", 1)
|
||||
cl = None
|
||||
for line in head.split(b"\r\n"):
|
||||
if line.lower().startswith(b"content-length:"):
|
||||
try:
|
||||
cl = int(line.split(b":", 1)[1].strip())
|
||||
except (ValueError, IndexError):
|
||||
cl = None
|
||||
if cl is None:
|
||||
body = rest
|
||||
else:
|
||||
body = rest
|
||||
while len(body) < cl:
|
||||
chunk = sock.recv(min(2048, cl - len(body)))
|
||||
if not chunk:
|
||||
break
|
||||
body += chunk
|
||||
return json.loads(body.decode("utf-8"))
|
||||
|
||||
|
||||
def http_driver_poll(host, port, payload_dict, timeout_s=40.0):
|
||||
"""
|
||||
POST ``/driver/v1/poll`` with JSON body; return parsed JSON (expects ``{"lines": [...]}``).
|
||||
"""
|
||||
path = "/driver/v1/poll"
|
||||
body_bytes = json.dumps(payload_dict).encode("utf-8")
|
||||
host_s = str(host)
|
||||
req_head = (
|
||||
"POST %s HTTP/1.1\r\nHost: %s\r\nContent-Type: application/json\r\nContent-Length: %d\r\nConnection: close\r\n\r\n"
|
||||
% (path, host_s, len(body_bytes))
|
||||
).encode("utf-8")
|
||||
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
try:
|
||||
sock.settimeout(timeout_s)
|
||||
sock.connect((host_s, int(port)))
|
||||
_send_all(sock, req_head + body_bytes)
|
||||
return _read_http_json_body(sock)
|
||||
finally:
|
||||
try:
|
||||
sock.close()
|
||||
except Exception:
|
||||
pass
|
||||
Reference in New Issue
Block a user