72 lines
1.8 KiB
Python
72 lines
1.8 KiB
Python
#!/usr/bin/env python3
|
|
import cv2
|
|
import os
|
|
import sys
|
|
import requests
|
|
import json
|
|
from urllib.parse import urlparse, parse_qs
|
|
from pyzbar.pyzbar import decode as decode_qr
|
|
|
|
SERVER_URL = os.getenv("SERVER_URL", "http://localhost:8080")
|
|
API_ENDPOINT = f"{SERVER_URL}/api/v1/bales"
|
|
|
|
|
|
def extract_type_from_url(url):
|
|
parsed = urlparse(url)
|
|
params = parse_qs(parsed.query)
|
|
if "type" in params:
|
|
return params["type"][0]
|
|
return parsed.path.split("=")[-1] if "=" in parsed.path else None
|
|
|
|
|
|
def scan_and_send():
|
|
cap = cv2.VideoCapture(0)
|
|
|
|
if not cap.isOpened():
|
|
print("Error: Cannot open camera", file=sys.stderr)
|
|
sys.exit(1)
|
|
|
|
print("Scanning for QR codes... Press 'q' to quit")
|
|
print(f"Server: {SERVER_URL}")
|
|
|
|
while True:
|
|
ret, frame = cap.read()
|
|
if not ret:
|
|
print("Failed to grab frame")
|
|
break
|
|
|
|
qr_codes = decode_qr(frame)
|
|
|
|
for qr in qr_codes:
|
|
url_data = qr.data.decode("utf-8")
|
|
print(f"Found QR: {url_data}")
|
|
|
|
try:
|
|
bale_type = extract_type_from_url(url_data)
|
|
|
|
if not bale_type:
|
|
print("Error: type not found in QR")
|
|
continue
|
|
|
|
response = requests.post(f"{API_ENDPOINT}?type={bale_type}", timeout=5)
|
|
|
|
if response.status_code in (200, 201):
|
|
print(f"OK: Bale created - {response.json()}")
|
|
else:
|
|
print(f"Error: {response.status_code} - {response.text}")
|
|
|
|
except Exception as e:
|
|
print(f"Request error: {e}")
|
|
|
|
cv2.imshow("QR Scanner", frame)
|
|
|
|
if cv2.waitKey(1) & 0xFF == ord("q"):
|
|
break
|
|
|
|
cap.release()
|
|
cv2.destroyAllWindows()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
scan_and_send()
|