Files
kimandClaude Sonnet 5.5 d6c7a3694d feat(scripts): SQ29(GP4225) 와이파이 미니 카메라 MJPEG 수신기
앱(DV Sports Camera) 캡처·라이브러리 분석으로 프로토콜을 확인:
UDP 20001 FDWN 제어, UDP 20000 JHCMD 하트비트, UDP 10900 JPEG 조각 수신.
프레임을 조립해 /stream.mjpg, /snapshot.jpg, /status로 제공한다.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-11 09:50:59 +09:00

159 lines
6.4 KiB
Python

#!/usr/bin/env python3
"""SQ29 계열 와이파이 미니 카메라(GeneralPlus GP4225, 앱: DV Sports Camera) 수신기.
카메라는 자체 AP(SQ29-xxxx, 192.168.33.1)를 내고 한 번에 한 기기만 받는다.
이 서버(동글)가 그 AP에 붙은 상태에서 실행한다.
python3 sq29_camera.py # HTTP 8765: /stream.mjpg, /snapshot.jpg
python3 sq29_camera.py --port 8765 --cam 192.168.33.1
프로토콜(앱 캡처+라이브러리 분석으로 확인):
UDP 20001 -> 카메라 FDWN 제어(초기화, 상태폴링 0.25s, 시각 동기화)
UDP 20000 -> 카메라 JHCMD d0 01 하트비트 0.5s
UDP 10900 <- 카메라 JPEG 조각: [fid_lo fid_hi total idx 01/04 14 00 00] + 페이로드
방화벽: ufw가 켜져 있으면 동글에서 오는 UDP를 허용해야 한다.
sudo ufw allow in on <wlan동글> from 192.168.33.1
"""
import argparse
import socket
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
H = lambda h: bytes.fromhex(h.replace(" ", ""))
class Sq29:
def __init__(self, cam="192.168.33.1"):
self.cam = cam
self.frame = None # 마지막 완성 JPEG
self.seq = 0
self.cv = threading.Condition()
self.stop = False
self.fps = 0.0
def _sock(self, port):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(("0.0.0.0", port))
s.settimeout(0.5)
return s
def _timesync(self):
t = time.localtime()
y, mo, d, hh, mm, ss = t.tm_year % 100, t.tm_mon, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec
return H("46 44 57 4e 20 00 01 00 10 00") + bytes([y, mo, d, 0, mm, ss, hh, 0, 0x52, 0x91, y, mo, d, hh, mm, ss])
def _control(self, tx):
send = lambda b, p: tx.sendto(b, (self.cam, p))
poll = H("46 44 57 4e 00 00 01 00 00 00")
send(H("46 44 57 4e 20 00 2c 00 08 00 01 00 00 00 00 00 00 00"), 20001); time.sleep(0.03)
send(poll, 20001); time.sleep(0.18)
send(H("46 44 57 4e 01 00 01 00 01 00 00"), 20001); time.sleep(0.07)
send(poll, 20001)
send(self._timesync(), 20001)
send(H("46 44 57 4e 01 00 01 00 01 00 00"), 20001)
for _ in range(3):
send(b"JHCMD\xd0\x01", 20000); time.sleep(0.02)
send(H("46 44 57 4e 20 00 50 00 00 00"), 20001)
lp = lh = lt = 0.0
while not self.stop:
n = time.time()
if n - lp >= 0.25: send(poll, 20001); lp = n
if n - lh >= 0.5: send(b"JHCMD\xd0\x01", 20000); lh = n
if n - lt >= 60: send(self._timesync(), 20001); lt = n
time.sleep(0.05)
def _video(self):
v = self._sock(10900)
parts, cur, total, t_last, n_fr, t_fps = {}, None, 0, 0.0, 0, time.time()
while not self.stop:
try:
d, _ = v.recvfrom(65535)
except socket.timeout:
continue
if len(d) < 9:
continue
fid = d[0] | d[1] << 8
if fid != cur:
cur, total, parts = fid, d[2], {}
parts[d[3]] = d[8:]
if len(parts) == total:
jpg = b"".join(parts[i] for i in range(total))
if jpg[:2] == b"\xff\xd8" and jpg[-2:] == b"\xff\xd9":
with self.cv:
self.frame, self.seq = jpg, self.seq + 1
self.cv.notify_all()
n_fr += 1
parts = {}
if time.time() - t_fps >= 2:
self.fps = n_fr / (time.time() - t_fps)
n_fr, t_fps = 0, time.time()
def start(self):
tx = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
c = self._sock(20001) # 카메라가 20001로 상태를 보내므로 수신 소켓을 열어 둔다(방화벽/버퍼 소진용)
def drain():
while not self.stop:
try: c.recvfrom(2048)
except socket.timeout: pass
for fn in (lambda: self._control(tx), self._video, drain):
threading.Thread(target=fn, daemon=True).start()
def make_handler(cam):
class Handler(BaseHTTPRequestHandler):
def log_message(self, *a): pass
def do_GET(self):
if self.path.startswith("/snapshot.jpg"):
with cam.cv:
cam.cv.wait_for(lambda: cam.frame is not None, 5)
jpg = cam.frame
if jpg is None:
self.send_error(503, "no frame"); return
self.send_response(200); self.send_header("Content-Type", "image/jpeg")
self.send_header("Content-Length", str(len(jpg))); self.end_headers(); self.wfile.write(jpg)
elif self.path.startswith("/stream.mjpg"):
self.send_response(200)
self.send_header("Content-Type", "multipart/x-mixed-replace; boundary=frame")
self.end_headers()
last = -1
try:
while True:
with cam.cv:
if not cam.cv.wait_for(lambda: cam.seq != last, 5):
continue
jpg, last = cam.frame, cam.seq
self.wfile.write(b"--frame\r\nContent-Type: image/jpeg\r\nContent-Length: %d\r\n\r\n" % len(jpg))
self.wfile.write(jpg); self.wfile.write(b"\r\n")
except (BrokenPipeError, ConnectionResetError):
pass
elif self.path.startswith("/status"):
body = ('{"fps": %.1f, "frames": %d}' % (cam.fps, cam.seq)).encode()
self.send_response(200); self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body))); self.end_headers(); self.wfile.write(body)
else:
self.send_error(404)
return Handler
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--cam", default="192.168.33.1")
ap.add_argument("--port", type=int, default=8765)
ap.add_argument("--bind", default="127.0.0.1")
a = ap.parse_args()
cam = Sq29(a.cam); cam.start()
srv = ThreadingHTTPServer((a.bind, a.port), make_handler(cam))
print(f"SQ29 http://{a.bind}:{a.port}/stream.mjpg /snapshot.jpg /status", flush=True)
try:
srv.serve_forever()
except KeyboardInterrupt:
pass
cam.stop = True
if __name__ == "__main__":
main()