api_client.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  1. """HTTP client for communicating with Bambuddy backend."""
  2. import asyncio
  3. import logging
  4. from collections import deque
  5. import httpx
  6. logger = logging.getLogger(__name__)
  7. MAX_BUFFER_SIZE = 100
  8. class APIClient:
  9. def __init__(self, backend_url: str, api_key: str):
  10. self._base = backend_url.rstrip("/") + "/api/v1/spoolbuddy"
  11. self._headers = {"X-API-Key": api_key} if api_key else {}
  12. self._client = httpx.AsyncClient(timeout=10.0, headers=self._headers)
  13. self._backoff = 1.0
  14. self._max_backoff = 30.0
  15. self._buffer: deque[dict] = deque(maxlen=MAX_BUFFER_SIZE)
  16. self._connected = False
  17. async def close(self):
  18. await self._client.aclose()
  19. async def _post(self, path: str, data: dict) -> dict | None:
  20. try:
  21. resp = await self._client.post(f"{self._base}{path}", json=data)
  22. resp.raise_for_status()
  23. self._backoff = 1.0
  24. self._connected = True
  25. return resp.json()
  26. except Exception as e:
  27. if self._connected:
  28. logger.warning("Backend connection lost: %s", e)
  29. self._connected = False
  30. self._buffer.append({"path": path, "data": data})
  31. return None
  32. async def _get(self, path: str) -> dict | None:
  33. try:
  34. resp = await self._client.get(f"{self._base}{path}")
  35. resp.raise_for_status()
  36. return resp.json()
  37. except Exception as e:
  38. logger.warning("GET %s failed: %s", path, e)
  39. return None
  40. async def _flush_buffer(self):
  41. while self._buffer:
  42. item = self._buffer[0]
  43. try:
  44. resp = await self._client.post(f"{self._base}{item['path']}", json=item["data"])
  45. resp.raise_for_status()
  46. self._buffer.popleft()
  47. except Exception:
  48. break
  49. async def register_device(
  50. self,
  51. device_id: str,
  52. hostname: str,
  53. ip_address: str,
  54. firmware_version: str | None = None,
  55. has_nfc: bool = True,
  56. has_scale: bool = True,
  57. tare_offset: int = 0,
  58. calibration_factor: float = 1.0,
  59. ) -> dict | None:
  60. while True:
  61. result = await self._post(
  62. "/devices/register",
  63. {
  64. "device_id": device_id,
  65. "hostname": hostname,
  66. "ip_address": ip_address,
  67. "firmware_version": firmware_version,
  68. "has_nfc": has_nfc,
  69. "has_scale": has_scale,
  70. "tare_offset": tare_offset,
  71. "calibration_factor": calibration_factor,
  72. },
  73. )
  74. if result is not None:
  75. logger.info("Registered with backend as %s", device_id)
  76. return result
  77. logger.warning("Registration failed, retrying in %.0fs...", self._backoff)
  78. await asyncio.sleep(self._backoff)
  79. self._backoff = min(self._backoff * 2, self._max_backoff)
  80. async def heartbeat(
  81. self, device_id: str, nfc_ok: bool, scale_ok: bool, uptime_s: int, ip_address: str | None = None
  82. ) -> dict | None:
  83. result = await self._post(
  84. f"/devices/{device_id}/heartbeat",
  85. {
  86. "nfc_ok": nfc_ok,
  87. "scale_ok": scale_ok,
  88. "uptime_s": uptime_s,
  89. "ip_address": ip_address,
  90. },
  91. )
  92. if result and self._buffer:
  93. await self._flush_buffer()
  94. return result
  95. async def tag_scanned(
  96. self,
  97. device_id: str,
  98. tag_uid: str,
  99. tray_uuid: str | None = None,
  100. sak: int | None = None,
  101. tag_type: str | None = None,
  102. ) -> dict | None:
  103. return await self._post(
  104. "/nfc/tag-scanned",
  105. {
  106. "device_id": device_id,
  107. "tag_uid": tag_uid,
  108. "tray_uuid": tray_uuid,
  109. "sak": sak,
  110. "tag_type": tag_type,
  111. },
  112. )
  113. async def tag_removed(self, device_id: str, tag_uid: str) -> dict | None:
  114. return await self._post(
  115. "/nfc/tag-removed",
  116. {
  117. "device_id": device_id,
  118. "tag_uid": tag_uid,
  119. },
  120. )
  121. async def update_tare(self, device_id: str, tare_offset: int) -> dict | None:
  122. return await self._post(
  123. f"/devices/{device_id}/calibration/set-tare",
  124. {"tare_offset": tare_offset},
  125. )
  126. async def scale_reading(
  127. self, device_id: str, weight_grams: float, stable: bool, raw_adc: int | None = None
  128. ) -> dict | None:
  129. return await self._post(
  130. "/scale/reading",
  131. {
  132. "device_id": device_id,
  133. "weight_grams": weight_grams,
  134. "stable": stable,
  135. "raw_adc": raw_adc,
  136. },
  137. )