config.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. """Configuration loader for SpoolBuddy daemon."""
  2. import os
  3. from dataclasses import dataclass
  4. from pathlib import Path
  5. import yaml
  6. CONFIG_PATH = Path(os.environ.get("SPOOLBUDDY_CONFIG", "/etc/spoolbuddy/config.yaml"))
  7. @dataclass
  8. class Config:
  9. backend_url: str = "http://localhost:5000"
  10. api_key: str = ""
  11. device_id: str = ""
  12. hostname: str = ""
  13. nfc_poll_interval: float = 0.3
  14. scale_read_interval: float = 0.1
  15. scale_report_interval: float = 1.0
  16. heartbeat_interval: float = 10.0
  17. stability_threshold: float = 2.0
  18. stability_window: float = 1.0
  19. tare_offset: int = 0
  20. calibration_factor: float = 1.0
  21. @classmethod
  22. def load(cls) -> "Config":
  23. cfg = cls()
  24. # Load from YAML if exists
  25. if CONFIG_PATH.exists():
  26. with open(CONFIG_PATH) as f:
  27. data = yaml.safe_load(f) or {}
  28. for key, val in data.items():
  29. if hasattr(cfg, key):
  30. setattr(cfg, key, val)
  31. # Environment overrides
  32. env_map = {
  33. "SPOOLBUDDY_BACKEND_URL": "backend_url",
  34. "SPOOLBUDDY_API_KEY": "api_key",
  35. "SPOOLBUDDY_DEVICE_ID": "device_id",
  36. "SPOOLBUDDY_HOSTNAME": "hostname",
  37. }
  38. for env_key, attr in env_map.items():
  39. val = os.environ.get(env_key)
  40. if val:
  41. setattr(cfg, attr, val)
  42. # Default device_id from MAC address
  43. if not cfg.device_id:
  44. cfg.device_id = _get_mac_id()
  45. # Default hostname from system
  46. if not cfg.hostname:
  47. import socket
  48. cfg.hostname = socket.gethostname()
  49. return cfg
  50. def _get_mac_id() -> str:
  51. """Generate a device ID from the primary network interface MAC address."""
  52. try:
  53. for iface in Path("/sys/class/net").iterdir():
  54. if iface.name == "lo":
  55. continue
  56. addr_file = iface / "address"
  57. if addr_file.exists():
  58. mac = addr_file.read_text().strip().replace(":", "")
  59. if mac and mac != "000000000000":
  60. return f"sb-{mac}"
  61. except Exception:
  62. pass
  63. import uuid
  64. return f"sb-{uuid.uuid4().hex[:12]}"