settings.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  1. import json
  2. from pydantic import BaseModel, Field, field_validator
  3. class AppSettings(BaseModel):
  4. """Application settings schema."""
  5. auto_archive: bool = Field(default=True, description="Automatically archive prints when completed")
  6. save_thumbnails: bool = Field(default=True, description="Extract and save preview images from 3MF files")
  7. capture_finish_photo: bool = Field(
  8. default=True, description="Capture photo from printer camera when print completes"
  9. )
  10. default_filament_cost: float = Field(default=25.0, description="Default filament cost per kg")
  11. currency: str = Field(default="USD", description="Currency for cost tracking")
  12. energy_cost_per_kwh: float = Field(default=0.15, description="Electricity cost per kWh for energy tracking")
  13. energy_tracking_mode: str = Field(
  14. default="total",
  15. description="Energy display mode on stats: 'print' shows sum of per-print energy, 'total' shows lifetime plug consumption",
  16. )
  17. # Spoolman integration
  18. spoolman_enabled: bool = Field(default=False, description="Enable Spoolman integration for filament tracking")
  19. spoolman_url: str = Field(default="", description="Spoolman server URL (e.g., http://localhost:7912)")
  20. spoolman_sync_mode: str = Field(
  21. default="auto", description="Sync mode: 'auto' syncs immediately, 'manual' requires button press"
  22. )
  23. spoolman_disable_weight_sync: bool = Field(
  24. default=False,
  25. description="Disable remaining_weight sync. When enabled, only location is updated for existing spools.",
  26. )
  27. spoolman_report_partial_usage: bool = Field(
  28. default=True,
  29. description="Report Partial Usage for Failed Prints. When a print fails or is cancelled, report the estimated filament used up to that point based on layer progress.",
  30. )
  31. disable_filament_warnings: bool = Field(
  32. default=False,
  33. description="Disable insufficient filament warnings when printing or queueing prints",
  34. )
  35. prefer_lowest_filament: bool = Field(
  36. default=False,
  37. description="When multiple AMS spools match, prefer the one with lowest remaining filament",
  38. )
  39. # Updates
  40. check_updates: bool = Field(default=True, description="Automatically check for updates on startup")
  41. check_printer_firmware: bool = Field(default=True, description="Check for printer firmware updates from Bambu Lab")
  42. include_beta_updates: bool = Field(default=False, description="Include beta/prerelease versions in update checks")
  43. # Language
  44. language: str = Field(default="en", description="UI language (en, de, fr, ja, it, pt-BR)")
  45. notification_language: str = Field(default="en", description="Language for push notifications (en, de)")
  46. # Bed cooled notification threshold
  47. bed_cooled_threshold: float = Field(
  48. default=35.0, description="Bed temperature threshold for cooled notification (°C)"
  49. )
  50. # AMS threshold settings for humidity and temperature coloring
  51. ams_humidity_good: int = Field(default=40, description="Humidity threshold for good (green): <= this value")
  52. ams_humidity_fair: int = Field(
  53. default=60, description="Humidity threshold for fair (orange): <= this value, > is red"
  54. )
  55. ams_temp_good: float = Field(default=28.0, description="Temperature threshold for good (blue): <= this value")
  56. ams_temp_fair: float = Field(
  57. default=35.0, description="Temperature threshold for fair (orange): <= this value, > is red"
  58. )
  59. ams_history_retention_days: int = Field(default=30, description="Number of days to keep AMS sensor history data")
  60. # Queue auto-drying settings
  61. queue_drying_enabled: bool = Field(
  62. default=False, description="Automatically dry AMS filament between queued prints"
  63. )
  64. queue_drying_block: bool = Field(
  65. default=False,
  66. description="Block queue until drying completes (when disabled, prints take priority over drying)",
  67. )
  68. ambient_drying_enabled: bool = Field(
  69. default=False,
  70. description="Automatically dry AMS filament on idle printers when humidity exceeds threshold, regardless of queue",
  71. )
  72. drying_presets: str = Field(
  73. default="",
  74. description="JSON blob of drying presets per filament type (empty = use built-in defaults)",
  75. )
  76. # Auto-print G-code injection (#422)
  77. gcode_snippets: str = Field(
  78. default="",
  79. description="JSON: per-model G-code injection snippets {model: {start_gcode, end_gcode}}",
  80. )
  81. # Scheduled local backup (#884)
  82. local_backup_enabled: bool = Field(default=False, description="Enable scheduled local backups")
  83. local_backup_schedule: str = Field(default="daily", description="Backup frequency: hourly, daily, weekly")
  84. local_backup_time: str = Field(default="03:00", description="Time of day for daily/weekly backups (HH:MM, 24h)")
  85. local_backup_retention: int = Field(default=5, description="Number of backup files to keep (1-100)")
  86. local_backup_path: str = Field(default="", description="Backup output directory (empty = DATA_DIR/backups)")
  87. # Print modal settings
  88. per_printer_mapping_expanded: bool = Field(
  89. default=False, description="Expand custom filament mapping by default in print modal"
  90. )
  91. # Date/time display format
  92. date_format: str = Field(default="system", description="Date format: system, us, eu, iso")
  93. time_format: str = Field(default="system", description="Time format: system, 12h, 24h")
  94. # Default printer for operations
  95. default_printer_id: int | None = Field(default=None, description="Default printer ID for uploads, reprints, etc.")
  96. # Virtual Printer
  97. virtual_printer_enabled: bool = Field(default=False, description="Enable virtual printer for slicer uploads")
  98. virtual_printer_access_code: str = Field(default="", description="Access code for virtual printer authentication")
  99. virtual_printer_mode: str = Field(
  100. default="immediate",
  101. description="Mode: 'immediate' (archive now), 'review' (pending review), or 'print_queue' (add to print queue)",
  102. )
  103. # Dark mode theme settings
  104. dark_style: str = Field(default="classic", description="Dark mode style: classic, glow, vibrant")
  105. dark_background: str = Field(
  106. default="neutral", description="Dark mode background: neutral, warm, cool, oled, slate, forest"
  107. )
  108. dark_accent: str = Field(default="green", description="Dark mode accent: green, teal, blue, orange, purple, red")
  109. # Light mode theme settings
  110. light_style: str = Field(default="classic", description="Light mode style: classic, glow, vibrant")
  111. light_background: str = Field(default="neutral", description="Light mode background: neutral, warm, cool")
  112. light_accent: str = Field(default="green", description="Light mode accent: green, teal, blue, orange, purple, red")
  113. # FTP retry settings for unreliable WiFi connections
  114. ftp_retry_enabled: bool = Field(default=True, description="Enable automatic retry for FTP operations")
  115. ftp_retry_count: int = Field(default=3, description="Number of retry attempts for FTP operations (1-10)")
  116. ftp_retry_delay: int = Field(default=2, description="Seconds to wait between FTP retry attempts (1-30)")
  117. ftp_timeout: int = Field(default=30, description="FTP connection timeout in seconds (10-300)")
  118. # MQTT Relay settings for publishing events to external broker
  119. mqtt_enabled: bool = Field(default=False, description="Enable MQTT event publishing to external broker")
  120. mqtt_broker: str = Field(default="", description="MQTT broker hostname or IP address")
  121. mqtt_port: int = Field(default=1883, description="MQTT broker port (default 1883, TLS typically 8883)")
  122. mqtt_username: str = Field(default="", description="MQTT username for authentication (optional)")
  123. mqtt_password: str = Field(default="", description="MQTT password for authentication (optional)")
  124. mqtt_topic_prefix: str = Field(default="bambuddy", description="Topic prefix for all published messages")
  125. mqtt_use_tls: bool = Field(default=False, description="Use TLS/SSL encryption for MQTT connection")
  126. # External URL for notifications
  127. external_url: str = Field(
  128. default="", description="External URL where Bambuddy is accessible (for notification images)"
  129. )
  130. # Home Assistant integration for smart plug control
  131. ha_enabled: bool = Field(default=False, description="Enable Home Assistant integration for smart plug control")
  132. ha_url: str = Field(default="", description="Home Assistant URL (e.g., http://192.168.1.100:8123)")
  133. ha_token: str = Field(default="", description="Home Assistant Long-Lived Access Token")
  134. ha_url_from_env: bool = Field(default=False, description="Whether HA URL is set via HA_URL environment variable")
  135. ha_token_from_env: bool = Field(
  136. default=False, description="Whether HA token is set via HA_TOKEN environment variable"
  137. )
  138. ha_env_managed: bool = Field(
  139. default=False, description="Whether HA integration is fully managed by environment variables"
  140. )
  141. # File Manager / Library settings
  142. library_archive_mode: str = Field(
  143. default="ask",
  144. description="When printing from File Manager, create archive entry: 'always', 'never', or 'ask'",
  145. )
  146. library_disk_warning_gb: float = Field(
  147. default=5.0,
  148. description="Show warning when free disk space falls below this threshold (GB)",
  149. )
  150. # Camera view settings
  151. camera_view_mode: str = Field(
  152. default="window",
  153. description="Camera view mode: 'window' opens in new browser window, 'embedded' shows overlay on main screen",
  154. )
  155. # Preferred slicer application
  156. preferred_slicer: str = Field(
  157. default="bambu_studio",
  158. description="Preferred slicer: 'bambu_studio' or 'orcaslicer'",
  159. )
  160. # Prometheus metrics endpoint
  161. prometheus_enabled: bool = Field(default=False, description="Enable Prometheus metrics endpoint at /metrics")
  162. prometheus_token: str = Field(
  163. default="", description="Bearer token for Prometheus metrics authentication (optional)"
  164. )
  165. # Inventory low stock threshold
  166. low_stock_threshold: float = Field(
  167. default=20.0,
  168. ge=0.1,
  169. le=99.9,
  170. description="Low stock threshold percentage (%) for inventory filtering and display",
  171. )
  172. # User email notifications (requires Advanced Authentication)
  173. user_notifications_enabled: bool = Field(
  174. default=True,
  175. description="Enable user email notifications for print job events (requires Advanced Authentication)",
  176. )
  177. # Default print options
  178. default_bed_levelling: bool = Field(default=True, description="Default bed levelling option for new prints")
  179. default_flow_cali: bool = Field(default=False, description="Default flow calibration option for new prints")
  180. default_vibration_cali: bool = Field(
  181. default=True, description="Default vibration calibration option for new prints"
  182. )
  183. default_layer_inspect: bool = Field(
  184. default=False, description="Default first layer inspection option for new prints"
  185. )
  186. default_timelapse: bool = Field(default=False, description="Default timelapse option for new prints")
  187. # Staggered batch start for multi-printer jobs
  188. stagger_group_size: int = Field(
  189. default=2, ge=1, le=50, description="Number of printers to start simultaneously in staggered mode"
  190. )
  191. stagger_interval_minutes: int = Field(
  192. default=5, ge=1, le=60, description="Minutes between staggered printer groups"
  193. )
  194. # Plate-clear confirmation for queue scheduling
  195. require_plate_clear: bool = Field(
  196. default=False,
  197. description="Require per-printer plate-clear confirmation before starting queued prints on finished printers",
  198. )
  199. queue_shortest_first: bool = Field(
  200. default=False,
  201. description="Shortest Job First — scheduler prioritizes shorter print jobs over longer ones",
  202. )
  203. # LDAP authentication (#794)
  204. ldap_enabled: bool = Field(default=False, description="Enable LDAP authentication")
  205. ldap_server_url: str = Field(default="", description="LDAP server URL (e.g., ldap://ldap.example.com:389)")
  206. ldap_bind_dn: str = Field(default="", description="Bind DN for LDAP searches (e.g., cn=admin,dc=example,dc=com)")
  207. ldap_bind_password: str = Field(default="", description="Bind password for LDAP searches")
  208. ldap_search_base: str = Field(default="", description="Search base DN (e.g., ou=users,dc=example,dc=com)")
  209. ldap_user_filter: str = Field(
  210. default="(sAMAccountName={username})",
  211. description="LDAP user search filter. {username} is replaced with the login username",
  212. )
  213. ldap_security: str = Field(default="starttls", description="LDAP security: 'starttls' or 'ldaps'")
  214. ldap_group_mapping: str = Field(
  215. default="",
  216. description="JSON: LDAP group to BamBuddy group mapping {ldap_group_dn: bambuddy_group_name}",
  217. )
  218. ldap_auto_provision: bool = Field(
  219. default=False,
  220. description="Auto-create BamBuddy user on first successful LDAP login",
  221. )
  222. ldap_default_group: str = Field(
  223. default="",
  224. description="Fallback BamBuddy group name assigned when an LDAP user authenticates but has no mapped groups. Empty = no fallback.",
  225. )
  226. # Obico AI failure detection (#172)
  227. obico_enabled: bool = Field(default=False, description="Enable Obico AI print failure detection")
  228. obico_ml_url: str = Field(
  229. default="",
  230. description="Self-hosted Obico ML API base URL (e.g., http://192.168.1.10:3333)",
  231. )
  232. obico_sensitivity: str = Field(
  233. default="medium",
  234. description="Detection sensitivity: 'low', 'medium', or 'high' (adjusts LOW/HIGH thresholds)",
  235. )
  236. obico_action: str = Field(
  237. default="notify",
  238. description="Action on detected failure: 'notify', 'pause', or 'pause_and_off'",
  239. )
  240. obico_poll_interval: int = Field(
  241. default=10,
  242. ge=5,
  243. le=120,
  244. description="Seconds between detection checks while a print is running",
  245. )
  246. obico_enabled_printers: str = Field(
  247. default="",
  248. description="JSON array of printer IDs to monitor (empty = all connected printers)",
  249. )
  250. # Default sidebar order (admin-set for all users)
  251. default_sidebar_order: str = Field(
  252. default="",
  253. description="JSON object with 'order' key containing array of sidebar item IDs (empty = no default)",
  254. )
  255. class AppSettingsUpdate(BaseModel):
  256. """Schema for updating settings (all fields optional)."""
  257. auto_archive: bool | None = None
  258. save_thumbnails: bool | None = None
  259. capture_finish_photo: bool | None = None
  260. default_filament_cost: float | None = None
  261. currency: str | None = None
  262. energy_cost_per_kwh: float | None = None
  263. energy_tracking_mode: str | None = None
  264. spoolman_enabled: bool | None = None
  265. spoolman_url: str | None = None
  266. spoolman_sync_mode: str | None = None
  267. spoolman_disable_weight_sync: bool | None = None
  268. spoolman_report_partial_usage: bool | None = None
  269. disable_filament_warnings: bool | None = None
  270. prefer_lowest_filament: bool | None = None
  271. check_updates: bool | None = None
  272. check_printer_firmware: bool | None = None
  273. include_beta_updates: bool | None = None
  274. language: str | None = None
  275. notification_language: str | None = None
  276. bed_cooled_threshold: float | None = None
  277. ams_humidity_good: int | None = None
  278. ams_humidity_fair: int | None = None
  279. ams_temp_good: float | None = None
  280. ams_temp_fair: float | None = None
  281. ams_history_retention_days: int | None = None
  282. queue_drying_enabled: bool | None = None
  283. queue_drying_block: bool | None = None
  284. ambient_drying_enabled: bool | None = None
  285. drying_presets: str | None = None
  286. per_printer_mapping_expanded: bool | None = None
  287. date_format: str | None = None
  288. time_format: str | None = None
  289. default_printer_id: int | None = None
  290. virtual_printer_enabled: bool | None = None
  291. virtual_printer_access_code: str | None = None
  292. virtual_printer_mode: str | None = None
  293. dark_style: str | None = None
  294. dark_background: str | None = None
  295. dark_accent: str | None = None
  296. light_style: str | None = None
  297. light_background: str | None = None
  298. light_accent: str | None = None
  299. ftp_retry_enabled: bool | None = None
  300. ftp_retry_count: int | None = None
  301. ftp_retry_delay: int | None = None
  302. ftp_timeout: int | None = None
  303. mqtt_enabled: bool | None = None
  304. mqtt_broker: str | None = None
  305. mqtt_port: int | None = None
  306. mqtt_username: str | None = None
  307. mqtt_password: str | None = None
  308. mqtt_topic_prefix: str | None = None
  309. mqtt_use_tls: bool | None = None
  310. external_url: str | None = None
  311. ha_enabled: bool | None = None
  312. ha_url: str | None = None
  313. ha_token: str | None = None
  314. library_archive_mode: str | None = None
  315. library_disk_warning_gb: float | None = None
  316. camera_view_mode: str | None = None
  317. preferred_slicer: str | None = None
  318. prometheus_enabled: bool | None = None
  319. prometheus_token: str | None = None
  320. low_stock_threshold: float | None = Field(default=None, ge=0.1, le=99.9)
  321. user_notifications_enabled: bool | None = None
  322. default_bed_levelling: bool | None = None
  323. default_flow_cali: bool | None = None
  324. default_vibration_cali: bool | None = None
  325. default_layer_inspect: bool | None = None
  326. default_timelapse: bool | None = None
  327. stagger_group_size: int | None = Field(default=None, ge=1, le=50)
  328. stagger_interval_minutes: int | None = Field(default=None, ge=1, le=60)
  329. require_plate_clear: bool | None = None
  330. queue_shortest_first: bool | None = None
  331. gcode_snippets: str | None = None
  332. local_backup_enabled: bool | None = None
  333. local_backup_schedule: str | None = None
  334. local_backup_time: str | None = None
  335. local_backup_retention: int | None = None
  336. local_backup_path: str | None = None
  337. ldap_enabled: bool | None = None
  338. ldap_server_url: str | None = None
  339. ldap_bind_dn: str | None = None
  340. ldap_bind_password: str | None = None
  341. ldap_search_base: str | None = None
  342. ldap_user_filter: str | None = None
  343. ldap_security: str | None = None
  344. ldap_group_mapping: str | None = None
  345. ldap_auto_provision: bool | None = None
  346. ldap_default_group: str | None = None
  347. obico_enabled: bool | None = None
  348. obico_ml_url: str | None = None
  349. obico_sensitivity: str | None = None
  350. obico_action: str | None = None
  351. obico_poll_interval: int | None = Field(default=None, ge=5, le=120)
  352. obico_enabled_printers: str | None = None
  353. default_sidebar_order: str | None = None
  354. @field_validator("gcode_snippets")
  355. @classmethod
  356. def validate_gcode_snippets(cls, v: str | None) -> str | None:
  357. if v is None or v == "":
  358. return v
  359. try:
  360. parsed = json.loads(v)
  361. except json.JSONDecodeError:
  362. raise ValueError("gcode_snippets must be valid JSON or empty")
  363. if not isinstance(parsed, dict):
  364. raise ValueError("gcode_snippets must be a JSON object keyed by printer model")
  365. return v
  366. @field_validator("ldap_group_mapping")
  367. @classmethod
  368. def validate_ldap_group_mapping(cls, v: str | None) -> str | None:
  369. if v is None or v == "":
  370. return v
  371. try:
  372. parsed = json.loads(v)
  373. except json.JSONDecodeError:
  374. raise ValueError("ldap_group_mapping must be valid JSON or empty")
  375. if not isinstance(parsed, dict):
  376. raise ValueError("ldap_group_mapping must be a JSON object mapping LDAP group DNs to BamBuddy group names")
  377. return v
  378. @field_validator("obico_enabled_printers")
  379. @classmethod
  380. def validate_obico_enabled_printers(cls, v: str | None) -> str | None:
  381. if v is None or v == "":
  382. return v
  383. try:
  384. parsed = json.loads(v)
  385. except json.JSONDecodeError:
  386. raise ValueError("obico_enabled_printers must be valid JSON or empty")
  387. if not isinstance(parsed, list) or not all(isinstance(item, int) for item in parsed):
  388. raise ValueError("obico_enabled_printers must be a JSON array of printer IDs (integers)")
  389. return v
  390. @field_validator("obico_sensitivity")
  391. @classmethod
  392. def validate_obico_sensitivity(cls, v: str | None) -> str | None:
  393. if v is None:
  394. return v
  395. if v not in ("low", "medium", "high"):
  396. raise ValueError("obico_sensitivity must be 'low', 'medium', or 'high'")
  397. return v
  398. @field_validator("obico_action")
  399. @classmethod
  400. def validate_obico_action(cls, v: str | None) -> str | None:
  401. if v is None:
  402. return v
  403. if v not in ("notify", "pause", "pause_and_off"):
  404. raise ValueError("obico_action must be 'notify', 'pause', or 'pause_and_off'")
  405. return v
  406. @field_validator("default_sidebar_order")
  407. @classmethod
  408. def validate_default_sidebar_order(cls, v: str | None) -> str | None:
  409. if v is None or v == "":
  410. return v
  411. try:
  412. parsed = json.loads(v)
  413. except json.JSONDecodeError:
  414. raise ValueError("default_sidebar_order must be valid JSON or empty")
  415. if isinstance(parsed, dict):
  416. order = parsed.get("order")
  417. elif isinstance(parsed, list):
  418. order = parsed
  419. else:
  420. raise ValueError("default_sidebar_order must be a JSON object with 'order' key or a JSON array")
  421. if not isinstance(order, list) or not all(isinstance(item, str) for item in order):
  422. raise ValueError("sidebar order must be an array of strings")
  423. return v