api_client.py 7.2 KB

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