settings.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716
  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,
  9. description=(
  10. "Capture photo from printer camera when print completes. Bambuddy records a "
  11. "brief timelapse during the print so the photo can be sourced from the moment "
  12. "before the bed drops; the timelapse file is kept if you enabled timelapse for "
  13. "this print, otherwise it is deleted automatically after the photo is captured."
  14. ),
  15. )
  16. default_filament_cost: float = Field(default=25.0, description="Default filament cost per kg")
  17. currency: str = Field(default="USD", description="Currency for cost tracking")
  18. energy_cost_per_kwh: float = Field(default=0.15, description="Electricity cost per kWh for energy tracking")
  19. energy_tracking_mode: str = Field(
  20. default="total",
  21. description="Energy display mode on stats: 'print' shows sum of per-print energy, 'total' shows lifetime plug consumption",
  22. )
  23. # Spoolman integration
  24. spoolman_enabled: bool = Field(default=False, description="Enable Spoolman integration for filament tracking")
  25. spoolman_url: str = Field(default="", description="Spoolman server URL (e.g., http://localhost:7912)")
  26. spoolman_sync_mode: str = Field(
  27. default="auto", description="Sync mode: 'auto' syncs immediately, 'manual' requires button press"
  28. )
  29. spoolman_disable_weight_sync: bool = Field(
  30. default=False,
  31. description="Disable remaining_weight sync. When enabled, only location is updated for existing spools.",
  32. )
  33. spoolman_report_partial_usage: bool = Field(
  34. default=True,
  35. 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.",
  36. )
  37. auto_add_unknown_rfid: bool = Field(
  38. default=True,
  39. description="Automatically add spools with unknown RFID tags to inventory. Disable if you pre-create inventory entries manually to avoid duplicates.",
  40. )
  41. disable_filament_warnings: bool = Field(
  42. default=False,
  43. description="Disable insufficient filament warnings when printing or queueing prints",
  44. )
  45. prefer_lowest_filament: bool = Field(
  46. default=False,
  47. description="When multiple AMS spools match, prefer the one with lowest remaining filament",
  48. )
  49. # Updates
  50. check_updates: bool = Field(default=True, description="Automatically check for updates on startup")
  51. check_printer_firmware: bool = Field(default=True, description="Check for printer firmware updates from Bambu Lab")
  52. include_beta_updates: bool = Field(default=False, description="Include beta/prerelease versions in update checks")
  53. # Language
  54. language: str = Field(default="en", description="UI language (en, de, fr, ja, it, pt-BR)")
  55. notification_language: str = Field(default="en", description="Language for push notifications (en, de)")
  56. # Bed cooled notification threshold
  57. bed_cooled_threshold: float = Field(
  58. default=35.0, description="Bed temperature threshold for cooled notification (°C)"
  59. )
  60. # AMS threshold settings for humidity and temperature coloring
  61. ams_humidity_good: int = Field(default=40, description="Humidity threshold for good (green): <= this value")
  62. ams_humidity_fair: int = Field(
  63. default=60, description="Humidity threshold for fair (orange): <= this value, > is red"
  64. )
  65. ams_temp_good: float = Field(default=28.0, description="Temperature threshold for good (blue): <= this value")
  66. ams_temp_fair: float = Field(
  67. default=35.0, description="Temperature threshold for fair (orange): <= this value, > is red"
  68. )
  69. ams_history_retention_days: int = Field(default=30, description="Number of days to keep AMS sensor history data")
  70. printer_sensor_history_retention_days: int = Field(
  71. default=30, description="Number of days to keep printer heater history data (nozzle / bed / chamber)"
  72. )
  73. # Queue auto-drying settings
  74. queue_drying_enabled: bool = Field(
  75. default=False, description="Automatically dry AMS filament between queued prints"
  76. )
  77. queue_drying_block: bool = Field(
  78. default=False,
  79. description="Block queue until drying completes (when disabled, prints take priority over drying)",
  80. )
  81. ambient_drying_enabled: bool = Field(
  82. default=False,
  83. description="Automatically dry AMS filament on idle printers when humidity exceeds threshold, regardless of queue",
  84. )
  85. print_drying_enabled: bool = Field(
  86. default=False,
  87. description=(
  88. "Allow auto-drying to also fire on a printer that is currently printing, "
  89. "when its model+firmware supports concurrent drying (H2D 01.03.00.00+, "
  90. "H2C/H2S/P2S/H2D Pro 01.02.00.00+, X2D/A2L 01.01.00.00+, X1C 01.11.02.00+). "
  91. "Drying temperature is automatically capped 5 degC below the idle preset "
  92. "(floor 40 degC) to protect spools during print."
  93. ),
  94. )
  95. drying_presets: str = Field(
  96. default="",
  97. description="JSON blob of drying presets per filament type (empty = use built-in defaults)",
  98. )
  99. ams_humidity_thresholds: str = Field(
  100. default="",
  101. description=(
  102. "JSON blob of per-filament-type humidity trigger thresholds for auto-drying and alarms. "
  103. 'Shape: {"default": int, "PLA": int, "ASA": int, ...}. '
  104. "Empty = fall back to ams_humidity_fair for all types."
  105. ),
  106. )
  107. # Auto-print G-code injection (#422)
  108. gcode_snippets: str = Field(
  109. default="",
  110. description="JSON: per-model G-code injection snippets {model: {start_gcode, end_gcode}}",
  111. )
  112. # Scheduled local backup (#884)
  113. local_backup_enabled: bool = Field(default=False, description="Enable scheduled local backups")
  114. local_backup_schedule: str = Field(default="daily", description="Backup frequency: hourly, daily, weekly")
  115. local_backup_time: str = Field(default="03:00", description="Time of day for daily/weekly backups (HH:MM, 24h)")
  116. local_backup_retention: int = Field(default=5, description="Number of backup files to keep (1-100)")
  117. local_backup_path: str = Field(default="", description="Backup output directory (empty = DATA_DIR/backups)")
  118. # Print modal settings
  119. per_printer_mapping_expanded: bool = Field(
  120. default=False, description="Expand custom filament mapping by default in print modal"
  121. )
  122. # Date/time display format
  123. date_format: str = Field(default="system", description="Date format: system, us, eu, iso")
  124. time_format: str = Field(default="system", description="Time format: system, 12h, 24h")
  125. # Default printer for operations
  126. default_printer_id: int | None = Field(default=None, description="Default printer ID for uploads, reprints, etc.")
  127. # Slicer Pipelines (#1425 PR C). Cap on the ``copies`` field in the
  128. # Run-with-pipeline modal — keeps a misclick from queueing 5000 prints.
  129. pipeline_max_copies: int = Field(
  130. default=50,
  131. ge=1,
  132. le=1000,
  133. description="Upper bound on the copies an operator can request when running a Slicer Pipeline. Larger fleets / production rigs can raise this; the hard ceiling at 1000 is a sanity guard against fat-fingered input.",
  134. )
  135. # Virtual Printer
  136. virtual_printer_enabled: bool = Field(default=False, description="Enable virtual printer for slicer uploads")
  137. virtual_printer_access_code: str = Field(default="", description="Access code for virtual printer authentication")
  138. virtual_printer_mode: str = Field(
  139. default="archive",
  140. description="Mode: 'archive' (archive now), 'review' (pending review), 'queue' (add to print queue), or 'proxy' (relay to real printer)",
  141. )
  142. virtual_printer_archive_name_source: str = Field(
  143. default="metadata",
  144. description="Source for the archive's display name on virtual-printer uploads: 'metadata' uses the 3MF's embedded print_name (default, matches Bambu's behavior), 'filename' uses the filename Bambu Studio sent over FTP (lets users rename via the slicer's 'send to printer' dialog).",
  145. )
  146. # Dark mode theme settings
  147. dark_style: str = Field(default="vibrant", description="Dark mode style: classic, glow, vibrant")
  148. dark_background: str = Field(
  149. default="cool", description="Dark mode background: neutral, warm, cool, oled, slate, forest"
  150. )
  151. dark_accent: str = Field(default="green", description="Dark mode accent: green, teal, blue, orange, purple, red")
  152. # Light mode theme settings
  153. light_style: str = Field(default="classic", description="Light mode style: classic, glow, vibrant")
  154. light_background: str = Field(default="neutral", description="Light mode background: neutral, warm, cool")
  155. light_accent: str = Field(default="green", description="Light mode accent: green, teal, blue, orange, purple, red")
  156. # FTP retry settings for unreliable WiFi connections
  157. ftp_retry_enabled: bool = Field(default=True, description="Enable automatic retry for FTP operations")
  158. ftp_retry_count: int = Field(default=3, description="Number of retry attempts for FTP operations (1-10)")
  159. ftp_retry_delay: int = Field(default=2, description="Seconds to wait between FTP retry attempts (1-30)")
  160. ftp_timeout: int = Field(default=30, description="FTP connection timeout in seconds (10-300)")
  161. # MQTT Relay settings for publishing events to external broker
  162. mqtt_enabled: bool = Field(default=False, description="Enable MQTT event publishing to external broker")
  163. mqtt_broker: str = Field(default="", description="MQTT broker hostname or IP address")
  164. mqtt_port: int = Field(default=1883, description="MQTT broker port (default 1883, TLS typically 8883)")
  165. mqtt_username: str = Field(default="", description="MQTT username for authentication (optional)")
  166. mqtt_password: str = Field(default="", description="MQTT password for authentication (optional)")
  167. mqtt_topic_prefix: str = Field(default="bambuddy", description="Topic prefix for all published messages")
  168. mqtt_use_tls: bool = Field(default=False, description="Use TLS/SSL encryption for MQTT connection")
  169. # External URL for notifications
  170. external_url: str = Field(
  171. default="", description="External URL where Bambuddy is accessible (for notification images)"
  172. )
  173. # Home Assistant integration for smart plug control
  174. ha_enabled: bool = Field(default=False, description="Enable Home Assistant integration for smart plug control")
  175. ha_url: str = Field(default="", description="Home Assistant URL (e.g., http://192.168.1.100:8123)")
  176. ha_token: str = Field(default="", description="Home Assistant Long-Lived Access Token")
  177. ha_url_from_env: bool = Field(default=False, description="Whether HA URL is set via HA_URL environment variable")
  178. ha_token_from_env: bool = Field(
  179. default=False, description="Whether HA token is set via HA_TOKEN environment variable"
  180. )
  181. ha_env_managed: bool = Field(
  182. default=False, description="Whether HA integration is fully managed by environment variables"
  183. )
  184. # File Manager / Library settings
  185. library_archive_mode: str = Field(
  186. default="ask",
  187. description="When printing from File Manager, create archive entry: 'always', 'never', or 'ask'",
  188. )
  189. library_disk_warning_gb: float = Field(
  190. default=5.0,
  191. description="Show warning when free disk space falls below this threshold (GB)",
  192. )
  193. # Camera view settings
  194. camera_view_mode: str = Field(
  195. default="window",
  196. description="Camera view mode: 'window' opens in new browser window, 'embedded' shows overlay on main screen",
  197. )
  198. # Preferred slicer application (server-side / API sidecar slicer)
  199. preferred_slicer: str = Field(
  200. default="bambu_studio",
  201. description="Slicer used for the server-side API / sidecar: 'bambu_studio' or 'orcaslicer'",
  202. )
  203. # "Open in Slicer" desktop URI handler — independent of the API slicer so
  204. # a user can slice via the Bambu Studio sidecar but open files locally in
  205. # OrcaSlicer, or vice versa (#1329). None falls back to ``preferred_slicer``
  206. # so existing installs behave identically until someone changes it.
  207. open_in_slicer: str | None = Field(
  208. default=None,
  209. description=(
  210. "Desktop slicer for the 'Open in Slicer' button: 'bambu_studio' or "
  211. "'orcaslicer'. None inherits from preferred_slicer."
  212. ),
  213. )
  214. # Slicer dispatch mode: when True, "Slice" actions open the in-app
  215. # SliceModal and call the slicer-API sidecar. When False (default), they
  216. # hand off to the user's local desktop slicer via URI scheme — preserving
  217. # the original Bambuddy behavior for users who don't run a sidecar.
  218. use_slicer_api: bool = Field(
  219. default=False,
  220. description="Use the slicer-API sidecar for slicing instead of the desktop slicer URI scheme",
  221. )
  222. # Slicer-API sidecar base URLs. Per-installation, configured via the
  223. # Settings UI (the "Slicer" card). Empty string means "fall back to the
  224. # SLICER_API_URL / BAMBU_STUDIO_API_URL env vars" — which themselves
  225. # default to the docker-compose ports in core/config.py.
  226. orcaslicer_api_url: str = Field(
  227. default="",
  228. description="OrcaSlicer sidecar URL (e.g. http://localhost:3003). Empty falls back to the SLICER_API_URL env var.",
  229. )
  230. bambu_studio_api_url: str = Field(
  231. default="",
  232. description="BambuStudio sidecar URL (e.g. http://localhost:3001). Empty falls back to the BAMBU_STUDIO_API_URL env var.",
  233. )
  234. # Prometheus metrics endpoint
  235. prometheus_enabled: bool = Field(default=False, description="Enable Prometheus metrics endpoint at /metrics")
  236. prometheus_token: str = Field(
  237. default="", description="Bearer token for Prometheus metrics authentication (optional)"
  238. )
  239. # Inventory low stock threshold
  240. low_stock_threshold: float = Field(
  241. default=20.0,
  242. ge=0.1,
  243. le=99.9,
  244. description="Low stock threshold percentage (%) for inventory filtering and display",
  245. )
  246. # Session policy (#1706) — admin-set ceiling for user session lifetime.
  247. # Default 24h preserves the M-2 audit reduction from 7 days. Max 720h
  248. # (30 days) bounds blast radius if an admin chooses a long session.
  249. session_max_hours: int = Field(
  250. default=24,
  251. ge=1,
  252. le=720,
  253. description=(
  254. "Maximum session lifetime in hours for user logins (default 24, max 720). "
  255. "Applies to new logins only; already-issued tokens keep their original expiry. "
  256. "Longer sessions reduce automatic logout protection."
  257. ),
  258. )
  259. # User email notifications (requires Advanced Authentication)
  260. user_notifications_enabled: bool = Field(
  261. default=True,
  262. description="Enable user email notifications for print job events (requires Advanced Authentication)",
  263. )
  264. # Default print options
  265. default_bed_levelling: bool = Field(default=True, description="Default bed levelling option for new prints")
  266. default_flow_cali: bool = Field(default=False, description="Default flow calibration option for new prints")
  267. default_vibration_cali: bool = Field(
  268. default=True, description="Default vibration calibration option for new prints"
  269. )
  270. default_layer_inspect: bool = Field(
  271. default=False, description="Default first layer inspection option for new prints"
  272. )
  273. default_timelapse: bool = Field(default=False, description="Default timelapse option for new prints")
  274. default_nozzle_offset_cali: bool = Field(
  275. default=True,
  276. description="Default nozzle offset calibration option for new prints (dual-nozzle printers only)",
  277. )
  278. # Staggered batch start for multi-printer jobs
  279. stagger_group_size: int = Field(
  280. default=2, ge=1, le=50, description="Number of printers to start simultaneously in staggered mode"
  281. )
  282. stagger_interval_minutes: int = Field(
  283. default=5, ge=1, le=60, description="Minutes between staggered printer groups"
  284. )
  285. # Plate-clear confirmation for queue scheduling
  286. require_plate_clear: bool = Field(
  287. default=False,
  288. description="Require per-printer plate-clear confirmation before starting queued prints on finished printers",
  289. )
  290. queue_shortest_first: bool = Field(
  291. default=False,
  292. description="Shortest Job First — scheduler prioritizes shorter print jobs over longer ones",
  293. )
  294. queue_max_concurrent_uploads: int = Field(
  295. default=4,
  296. ge=1,
  297. le=16,
  298. description=(
  299. "How many printers the queue may upload to at the same time. Printers are independent "
  300. "machines, so raising this starts a multi-printer batch proportionally sooner; each "
  301. "concurrent upload costs one connection and one thread on the Bambuddy host."
  302. ),
  303. )
  304. # Preheat / heat-soak before queued prints (#1468). The scheduler stage runs
  305. # BEFORE FTP upload. Three hardware tiers behave differently:
  306. # - Chamber heater (H2C/H2D/H2DPro/H2S/X2D/X1E): M141 → wait for chamber
  307. # sensor to reach target → soak
  308. # - Chamber sensor only (X1C/P2S): M140 only → wait for radiant chamber
  309. # warm-up to reach target OR max-wait timeout → soak
  310. # - No chamber sensor (P1S/P1P/A1/A1 Mini): M140 only → fixed soak timer
  311. # (no way to verify chamber temp; relies entirely on max_wait + soak)
  312. # Chamber target derives per-print from the loaded AMS filament types via
  313. # preheat_filament_targets (max across loaded slots). A target of 0 skips
  314. # the chamber phase but keeps the bed phase + soak. Per-queue-item
  315. # `preheat_chamber_target_override` (nullable) bypasses the derivation.
  316. preheat_enabled: bool = Field(
  317. default=False,
  318. description="Master toggle / default for new queue items. Per-item preheat_override can flip the decision per print.",
  319. )
  320. preheat_filament_targets: str = Field(
  321. default="",
  322. description=(
  323. "JSON map of normalized filament type → chamber target °C. Empty = bundled defaults "
  324. "(PLA/PETG/TPU/PVA: 0, PETG-CF: 40, ABS/ASA: 45, PA/PC/PC-FR: 50, PA-CF: 55, default: 0). "
  325. "Scheduler picks max across loaded AMS slots; 0 disables chamber phase for that print."
  326. ),
  327. )
  328. preheat_max_wait_seconds: int = Field(
  329. default=900,
  330. ge=60,
  331. le=3600,
  332. description="Maximum time to wait for the chamber to reach the target before falling through to the soak phase (radiant heating on X1C/P2S can take 15-30 min).",
  333. )
  334. preheat_soak_seconds: int = Field(
  335. default=300,
  336. ge=0,
  337. le=1800,
  338. description="Additional hold time at temperature after the chamber reaches the target (or after max_wait_seconds elapses). 0 = no soak.",
  339. )
  340. # User-configurable presets for the printer-card temperature / fan-speed
  341. # popovers. Each is a JSON array of exactly 3 ints (the "Off" button is
  342. # rendered separately and is not configurable). Empty string = use built-in
  343. # defaults. Validators on AppSettingsUpdate enforce the shape on writes.
  344. nozzle_temp_presets: str = Field(
  345. default="",
  346. description="JSON array of 3 nozzle-temperature preset values in C (0-320). Empty = use defaults [120, 220, 260]",
  347. )
  348. bed_temp_presets: str = Field(
  349. default="",
  350. description="JSON array of 3 bed-temperature preset values in C (0-140). Empty = use defaults [55, 75, 90]",
  351. )
  352. chamber_temp_presets: str = Field(
  353. default="",
  354. description="JSON array of 3 chamber-temperature preset values in C (0-60). Empty = use defaults [35, 45, 60]",
  355. )
  356. fan_speed_presets: str = Field(
  357. default="",
  358. description="JSON array of 3 fan-speed preset values in % (0-100). Empty = use defaults [50, 75, 100]",
  359. )
  360. # Local login (#1589) — when False, /auth/login rejects username+password
  361. # credentials with HTTP 403 and the login page hides the credentials form,
  362. # leaving only the OIDC SSO provider buttons. LDAP is governed by its own
  363. # `ldap_enabled` toggle and is not affected. The env-var
  364. # ``BAMBUDDY_LOCAL_LOGIN=true`` bypasses this gate at the route level so a
  365. # server admin can recover an install whose SSO provider is unreachable
  366. # without editing the DB.
  367. local_login_enabled: bool = Field(
  368. default=True,
  369. description=(
  370. "Allow username + password login on /auth/login. Disable when only SSO should be usable. "
  371. "BAMBUDDY_LOCAL_LOGIN=true on the server overrides this to keep a recovery path open."
  372. ),
  373. )
  374. # LDAP authentication (#794)
  375. ldap_enabled: bool = Field(default=False, description="Enable LDAP authentication")
  376. ldap_server_url: str = Field(default="", description="LDAP server URL (e.g., ldap://ldap.example.com:389)")
  377. ldap_bind_dn: str = Field(default="", description="Bind DN for LDAP searches (e.g., cn=admin,dc=example,dc=com)")
  378. ldap_bind_password: str = Field(default="", description="Bind password for LDAP searches")
  379. ldap_search_base: str = Field(default="", description="Search base DN (e.g., ou=users,dc=example,dc=com)")
  380. ldap_user_filter: str = Field(
  381. default="(sAMAccountName={username})",
  382. description="LDAP user search filter. {username} is replaced with the login username",
  383. )
  384. ldap_security: str = Field(default="starttls", description="LDAP security: 'starttls' or 'ldaps'")
  385. ldap_group_mapping: str = Field(
  386. default="",
  387. description="JSON: LDAP group to BamBuddy group mapping {ldap_group_dn: bambuddy_group_name}",
  388. )
  389. ldap_auto_provision: bool = Field(
  390. default=False,
  391. description="Auto-create BamBuddy user on first successful LDAP login",
  392. )
  393. ldap_default_group: str = Field(
  394. default="",
  395. description="Fallback BamBuddy group name assigned when an LDAP user authenticates but has no mapped groups. Empty = no fallback.",
  396. )
  397. # Obico AI failure detection (#172)
  398. obico_enabled: bool = Field(default=False, description="Enable Obico AI print failure detection")
  399. obico_ml_url: str = Field(
  400. default="",
  401. description="Self-hosted Obico ML API base URL (e.g., http://192.168.1.10:3333)",
  402. )
  403. obico_sensitivity: str = Field(
  404. default="medium",
  405. description="Detection sensitivity: 'low', 'medium', or 'high' (adjusts LOW/HIGH thresholds)",
  406. )
  407. obico_action: str = Field(
  408. default="notify",
  409. description="Action on detected failure: 'notify', 'pause', or 'pause_and_off'",
  410. )
  411. obico_poll_interval: int = Field(
  412. default=10,
  413. ge=5,
  414. le=120,
  415. description="Seconds between detection checks while a print is running",
  416. )
  417. obico_enabled_printers: str = Field(
  418. default="",
  419. description="JSON array of printer IDs to monitor (empty = all connected printers)",
  420. )
  421. # Inventory forecasting
  422. forecast_global_lead_time_days: int = Field(
  423. default=0,
  424. ge=0,
  425. description="Global lead time floor (days) used in reorder point calculation for all SKUs",
  426. )
  427. # Default sidebar order (admin-set for all users)
  428. default_sidebar_order: str = Field(
  429. default="",
  430. description="JSON object with 'order' key containing array of sidebar item IDs (empty = no default)",
  431. )
  432. class AppSettingsUpdate(BaseModel):
  433. """Schema for updating settings (all fields optional)."""
  434. auto_archive: bool | None = None
  435. save_thumbnails: bool | None = None
  436. capture_finish_photo: bool | None = None
  437. default_filament_cost: float | None = None
  438. currency: str | None = None
  439. energy_cost_per_kwh: float | None = None
  440. energy_tracking_mode: str | None = None
  441. spoolman_enabled: bool | None = None
  442. spoolman_url: str | None = None
  443. spoolman_sync_mode: str | None = None
  444. spoolman_disable_weight_sync: bool | None = None
  445. spoolman_report_partial_usage: bool | None = None
  446. auto_add_unknown_rfid: bool | None = None
  447. disable_filament_warnings: bool | None = None
  448. prefer_lowest_filament: bool | None = None
  449. check_updates: bool | None = None
  450. check_printer_firmware: bool | None = None
  451. include_beta_updates: bool | None = None
  452. local_login_enabled: bool | None = None
  453. language: str | None = None
  454. notification_language: str | None = None
  455. bed_cooled_threshold: float | None = None
  456. ams_humidity_good: int | None = None
  457. ams_humidity_fair: int | None = None
  458. ams_temp_good: float | None = None
  459. ams_temp_fair: float | None = None
  460. ams_history_retention_days: int | None = None
  461. printer_sensor_history_retention_days: int | None = None
  462. queue_drying_enabled: bool | None = None
  463. queue_drying_block: bool | None = None
  464. ambient_drying_enabled: bool | None = None
  465. print_drying_enabled: bool | None = None
  466. drying_presets: str | None = None
  467. ams_humidity_thresholds: str | None = None
  468. per_printer_mapping_expanded: bool | None = None
  469. date_format: str | None = None
  470. time_format: str | None = None
  471. default_printer_id: int | None = None
  472. pipeline_max_copies: int | None = None
  473. virtual_printer_enabled: bool | None = None
  474. virtual_printer_access_code: str | None = None
  475. virtual_printer_mode: str | None = None
  476. virtual_printer_archive_name_source: str | None = None
  477. dark_style: str | None = None
  478. dark_background: str | None = None
  479. dark_accent: str | None = None
  480. light_style: str | None = None
  481. light_background: str | None = None
  482. light_accent: str | None = None
  483. ftp_retry_enabled: bool | None = None
  484. ftp_retry_count: int | None = None
  485. ftp_retry_delay: int | None = None
  486. ftp_timeout: int | None = None
  487. mqtt_enabled: bool | None = None
  488. mqtt_broker: str | None = None
  489. mqtt_port: int | None = None
  490. mqtt_username: str | None = None
  491. mqtt_password: str | None = None
  492. mqtt_topic_prefix: str | None = None
  493. mqtt_use_tls: bool | None = None
  494. external_url: str | None = None
  495. ha_enabled: bool | None = None
  496. ha_url: str | None = None
  497. ha_token: str | None = None
  498. library_archive_mode: str | None = None
  499. library_disk_warning_gb: float | None = None
  500. camera_view_mode: str | None = None
  501. preferred_slicer: str | None = None
  502. open_in_slicer: str | None = None
  503. use_slicer_api: bool | None = None
  504. orcaslicer_api_url: str | None = None
  505. bambu_studio_api_url: str | None = None
  506. prometheus_enabled: bool | None = None
  507. prometheus_token: str | None = None
  508. low_stock_threshold: float | None = Field(default=None, ge=0.1, le=99.9)
  509. session_max_hours: int | None = Field(default=None, ge=1, le=720)
  510. user_notifications_enabled: bool | None = None
  511. default_bed_levelling: bool | None = None
  512. default_flow_cali: bool | None = None
  513. default_vibration_cali: bool | None = None
  514. default_layer_inspect: bool | None = None
  515. default_timelapse: bool | None = None
  516. default_nozzle_offset_cali: bool | None = None
  517. stagger_group_size: int | None = Field(default=None, ge=1, le=50)
  518. stagger_interval_minutes: int | None = Field(default=None, ge=1, le=60)
  519. require_plate_clear: bool | None = None
  520. queue_shortest_first: bool | None = None
  521. queue_max_concurrent_uploads: int | None = Field(default=None, ge=1, le=16)
  522. preheat_enabled: bool | None = None
  523. preheat_filament_targets: str | None = None
  524. preheat_max_wait_seconds: int | None = Field(default=None, ge=60, le=3600)
  525. preheat_soak_seconds: int | None = Field(default=None, ge=0, le=1800)
  526. nozzle_temp_presets: str | None = None
  527. bed_temp_presets: str | None = None
  528. chamber_temp_presets: str | None = None
  529. fan_speed_presets: str | None = None
  530. gcode_snippets: str | None = None
  531. local_backup_enabled: bool | None = None
  532. local_backup_schedule: str | None = None
  533. local_backup_time: str | None = None
  534. local_backup_retention: int | None = None
  535. local_backup_path: str | None = None
  536. ldap_enabled: bool | None = None
  537. ldap_server_url: str | None = None
  538. ldap_bind_dn: str | None = None
  539. ldap_bind_password: str | None = None
  540. ldap_search_base: str | None = None
  541. ldap_user_filter: str | None = None
  542. ldap_security: str | None = None
  543. ldap_group_mapping: str | None = None
  544. ldap_auto_provision: bool | None = None
  545. ldap_default_group: str | None = None
  546. obico_enabled: bool | None = None
  547. obico_ml_url: str | None = None
  548. obico_sensitivity: str | None = None
  549. obico_action: str | None = None
  550. obico_poll_interval: int | None = Field(default=None, ge=5, le=120)
  551. obico_enabled_printers: str | None = None
  552. default_sidebar_order: str | None = None
  553. forecast_global_lead_time_days: int | None = Field(default=None, ge=0)
  554. @field_validator("gcode_snippets")
  555. @classmethod
  556. def validate_gcode_snippets(cls, v: str | None) -> str | None:
  557. if v is None or v == "":
  558. return v
  559. try:
  560. parsed = json.loads(v)
  561. except json.JSONDecodeError:
  562. raise ValueError("gcode_snippets must be valid JSON or empty")
  563. if not isinstance(parsed, dict):
  564. raise ValueError("gcode_snippets must be a JSON object keyed by printer model")
  565. return v
  566. @field_validator("ldap_group_mapping")
  567. @classmethod
  568. def validate_ldap_group_mapping(cls, v: str | None) -> str | None:
  569. if v is None or v == "":
  570. return v
  571. try:
  572. parsed = json.loads(v)
  573. except json.JSONDecodeError:
  574. raise ValueError("ldap_group_mapping must be valid JSON or empty")
  575. if not isinstance(parsed, dict):
  576. raise ValueError("ldap_group_mapping must be a JSON object mapping LDAP group DNs to BamBuddy group names")
  577. return v
  578. @field_validator("obico_enabled_printers")
  579. @classmethod
  580. def validate_obico_enabled_printers(cls, v: str | None) -> str | None:
  581. if v is None or v == "":
  582. return v
  583. try:
  584. parsed = json.loads(v)
  585. except json.JSONDecodeError:
  586. raise ValueError("obico_enabled_printers must be valid JSON or empty")
  587. if not isinstance(parsed, list) or not all(isinstance(item, int) for item in parsed):
  588. raise ValueError("obico_enabled_printers must be a JSON array of printer IDs (integers)")
  589. return v
  590. @staticmethod
  591. def _validate_preset_triple(v: str | None, field_name: str, lo: int, hi: int) -> str | None:
  592. """Validate a JSON array of exactly 3 ints in [lo, hi]. Empty = defaults."""
  593. if v is None or v == "":
  594. return v
  595. try:
  596. parsed = json.loads(v)
  597. except json.JSONDecodeError:
  598. raise ValueError(f"{field_name} must be valid JSON or empty")
  599. if not isinstance(parsed, list) or len(parsed) != 3:
  600. raise ValueError(f"{field_name} must be a JSON array of exactly 3 integers")
  601. if not all(isinstance(item, int) and not isinstance(item, bool) for item in parsed):
  602. raise ValueError(f"{field_name} entries must all be integers")
  603. if not all(lo <= item <= hi for item in parsed):
  604. raise ValueError(f"{field_name} entries must each be in [{lo}, {hi}]")
  605. return v
  606. @field_validator("nozzle_temp_presets")
  607. @classmethod
  608. def validate_nozzle_temp_presets(cls, v: str | None) -> str | None:
  609. return cls._validate_preset_triple(v, "nozzle_temp_presets", 0, 320)
  610. @field_validator("bed_temp_presets")
  611. @classmethod
  612. def validate_bed_temp_presets(cls, v: str | None) -> str | None:
  613. return cls._validate_preset_triple(v, "bed_temp_presets", 0, 140)
  614. @field_validator("chamber_temp_presets")
  615. @classmethod
  616. def validate_chamber_temp_presets(cls, v: str | None) -> str | None:
  617. return cls._validate_preset_triple(v, "chamber_temp_presets", 0, 60)
  618. @field_validator("fan_speed_presets")
  619. @classmethod
  620. def validate_fan_speed_presets(cls, v: str | None) -> str | None:
  621. return cls._validate_preset_triple(v, "fan_speed_presets", 0, 100)
  622. @field_validator("obico_sensitivity")
  623. @classmethod
  624. def validate_obico_sensitivity(cls, v: str | None) -> str | None:
  625. if v is None:
  626. return v
  627. if v not in ("low", "medium", "high"):
  628. raise ValueError("obico_sensitivity must be 'low', 'medium', or 'high'")
  629. return v
  630. @field_validator("obico_action")
  631. @classmethod
  632. def validate_obico_action(cls, v: str | None) -> str | None:
  633. if v is None:
  634. return v
  635. if v not in ("notify", "pause", "pause_and_off"):
  636. raise ValueError("obico_action must be 'notify', 'pause', or 'pause_and_off'")
  637. return v
  638. @field_validator("default_sidebar_order")
  639. @classmethod
  640. def validate_default_sidebar_order(cls, v: str | None) -> str | None:
  641. if v is None or v == "":
  642. return v
  643. try:
  644. parsed = json.loads(v)
  645. except json.JSONDecodeError:
  646. raise ValueError("default_sidebar_order must be valid JSON or empty")
  647. if isinstance(parsed, dict):
  648. order = parsed.get("order")
  649. hidden_system_item_ids = parsed.get("hiddenSystemItemIds", [])
  650. if not isinstance(hidden_system_item_ids, list) or not all(
  651. isinstance(item, str) for item in hidden_system_item_ids
  652. ):
  653. raise ValueError("sidebar hidden system item IDs must be an array of strings")
  654. elif isinstance(parsed, list):
  655. order = parsed
  656. else:
  657. raise ValueError("default_sidebar_order must be a JSON object with 'order' key or a JSON array")
  658. if not isinstance(order, list) or not all(isinstance(item, str) for item in order):
  659. raise ValueError("sidebar order must be an array of strings")
  660. return v