api_client.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  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. nfc_reader_type: str | None = None,
  60. nfc_connection: str | None = None,
  61. has_backlight: bool = False,
  62. ) -> dict | None:
  63. while True:
  64. result = await self._post(
  65. "/devices/register",
  66. {
  67. "device_id": device_id,
  68. "hostname": hostname,
  69. "ip_address": ip_address,
  70. "firmware_version": firmware_version,
  71. "has_nfc": has_nfc,
  72. "has_scale": has_scale,
  73. "tare_offset": tare_offset,
  74. "calibration_factor": calibration_factor,
  75. "nfc_reader_type": nfc_reader_type,
  76. "nfc_connection": nfc_connection,
  77. "has_backlight": has_backlight,
  78. },
  79. )
  80. if result is not None:
  81. logger.info("Registered with backend as %s", device_id)
  82. return result
  83. logger.warning("Registration failed, retrying in %.0fs...", self._backoff)
  84. await asyncio.sleep(self._backoff)
  85. self._backoff = min(self._backoff * 2, self._max_backoff)
  86. async def heartbeat(
  87. self,
  88. device_id: str,
  89. nfc_ok: bool,
  90. scale_ok: bool,
  91. uptime_s: int,
  92. ip_address: str | None = None,
  93. firmware_version: str | None = None,
  94. nfc_reader_type: str | None = None,
  95. nfc_connection: str | None = None,
  96. ) -> dict | None:
  97. result = await self._post(
  98. f"/devices/{device_id}/heartbeat",
  99. {
  100. "nfc_ok": nfc_ok,
  101. "scale_ok": scale_ok,
  102. "uptime_s": uptime_s,
  103. "ip_address": ip_address,
  104. "firmware_version": firmware_version,
  105. "nfc_reader_type": nfc_reader_type,
  106. "nfc_connection": nfc_connection,
  107. },
  108. )
  109. if result and self._buffer:
  110. await self._flush_buffer()
  111. return result
  112. async def tag_scanned(
  113. self,
  114. device_id: str,
  115. tag_uid: str,
  116. tray_uuid: str | None = None,
  117. sak: int | None = None,
  118. tag_type: str | None = None,
  119. ) -> dict | None:
  120. return await self._post(
  121. "/nfc/tag-scanned",
  122. {
  123. "device_id": device_id,
  124. "tag_uid": tag_uid,
  125. "tray_uuid": tray_uuid,
  126. "sak": sak,
  127. "tag_type": tag_type,
  128. },
  129. )
  130. async def tag_removed(self, device_id: str, tag_uid: str) -> dict | None:
  131. return await self._post(
  132. "/nfc/tag-removed",
  133. {
  134. "device_id": device_id,
  135. "tag_uid": tag_uid,
  136. },
  137. )
  138. async def update_tare(self, device_id: str, tare_offset: int) -> dict | None:
  139. return await self._post(
  140. f"/devices/{device_id}/calibration/set-tare",
  141. {"tare_offset": tare_offset},
  142. )
  143. async def scale_reading(
  144. self, device_id: str, weight_grams: float, stable: bool, raw_adc: int | None = None
  145. ) -> dict | None:
  146. return await self._post(
  147. "/scale/reading",
  148. {
  149. "device_id": device_id,
  150. "weight_grams": weight_grams,
  151. "stable": stable,
  152. "raw_adc": raw_adc,
  153. },
  154. )
  155. async def write_tag_result(
  156. self, device_id: str, spool_id: int, tag_uid: str, success: bool, message: str | None = None
  157. ) -> dict | None:
  158. return await self._post(
  159. "/nfc/write-result",
  160. {
  161. "device_id": device_id,
  162. "spool_id": spool_id,
  163. "tag_uid": tag_uid,
  164. "success": success,
  165. "message": message,
  166. },
  167. )
  168. async def report_update_status(self, device_id: str, status: str, message: str = "") -> dict | None:
  169. return await self._post(
  170. f"/devices/{device_id}/update-status",
  171. {"status": status, "message": message},
  172. )