client.ts 84 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660
  1. const API_BASE = '/api/v1';
  2. async function request<T>(
  3. endpoint: string,
  4. options: RequestInit = {}
  5. ): Promise<T> {
  6. const response = await fetch(`${API_BASE}${endpoint}`, {
  7. ...options,
  8. headers: {
  9. 'Content-Type': 'application/json',
  10. ...options.headers,
  11. },
  12. });
  13. if (!response.ok) {
  14. const error = await response.json().catch(() => ({}));
  15. const detail = error.detail;
  16. const message = typeof detail === 'string'
  17. ? detail
  18. : (detail ? JSON.stringify(detail) : `HTTP ${response.status}`);
  19. throw new Error(message);
  20. }
  21. return await response.json();
  22. }
  23. // Printer types
  24. export interface Printer {
  25. id: number;
  26. name: string;
  27. serial_number: string;
  28. ip_address: string;
  29. access_code: string;
  30. model: string | null;
  31. location: string | null; // Group/location name
  32. nozzle_count: number; // 1 or 2, auto-detected from MQTT
  33. is_active: boolean;
  34. auto_archive: boolean;
  35. created_at: string;
  36. updated_at: string;
  37. }
  38. export interface HMSError {
  39. code: string;
  40. attr: number; // Attribute value for constructing wiki URL
  41. module: number;
  42. severity: number; // 1=fatal, 2=serious, 3=common, 4=info
  43. }
  44. export interface AMSTray {
  45. id: number;
  46. tray_color: string | null;
  47. tray_type: string | null;
  48. tray_sub_brands: string | null; // Full name like "PLA Basic", "PETG HF"
  49. tray_id_name: string | null; // Bambu filament ID like "A00-Y2" (can decode to color)
  50. tray_info_idx: string | null; // Filament preset ID like "GFA00" - maps to cloud setting_id
  51. remain: number;
  52. k: number | null; // Pressure advance value (from tray or K-profile lookup)
  53. cali_idx: number | null; // Calibration index for K-profile lookup
  54. tag_uid: string | null; // RFID tag UID (any tag)
  55. tray_uuid: string | null; // Bambu Lab spool UUID (32-char hex, only valid for Bambu Lab spools)
  56. nozzle_temp_min: number | null; // Min nozzle temperature
  57. nozzle_temp_max: number | null; // Max nozzle temperature
  58. }
  59. export interface AMSUnit {
  60. id: number;
  61. humidity: number | null;
  62. temp: number | null;
  63. is_ams_ht: boolean; // True for AMS-HT (single spool), False for regular AMS (4 spools)
  64. tray: AMSTray[];
  65. }
  66. export interface NozzleInfo {
  67. nozzle_type: string; // "stainless_steel" or "hardened_steel"
  68. nozzle_diameter: string; // e.g., "0.4"
  69. }
  70. export interface PrintOptions {
  71. // Core AI detectors
  72. spaghetti_detector: boolean;
  73. print_halt: boolean;
  74. halt_print_sensitivity: string; // "low", "medium", "high" - spaghetti sensitivity
  75. first_layer_inspector: boolean;
  76. printing_monitor: boolean;
  77. buildplate_marker_detector: boolean;
  78. allow_skip_parts: boolean;
  79. // Additional AI detectors (decoded from cfg bitmask)
  80. nozzle_clumping_detector: boolean;
  81. nozzle_clumping_sensitivity: string; // "low", "medium", "high"
  82. pileup_detector: boolean;
  83. pileup_sensitivity: string; // "low", "medium", "high"
  84. airprint_detector: boolean;
  85. airprint_sensitivity: string; // "low", "medium", "high"
  86. auto_recovery_step_loss: boolean;
  87. filament_tangle_detect: boolean;
  88. }
  89. export interface PrinterStatus {
  90. id: number;
  91. name: string;
  92. connected: boolean;
  93. state: string | null;
  94. current_print: string | null;
  95. subtask_name: string | null;
  96. gcode_file: string | null;
  97. progress: number | null;
  98. remaining_time: number | null;
  99. layer_num: number | null;
  100. total_layers: number | null;
  101. temperatures: {
  102. bed?: number;
  103. bed_target?: number;
  104. bed_heating?: boolean; // Actual heater state from MQTT
  105. nozzle?: number;
  106. nozzle_target?: number;
  107. nozzle_heating?: boolean; // Actual heater state from MQTT
  108. nozzle_2?: number; // Second nozzle for H2 series (dual nozzle)
  109. nozzle_2_target?: number;
  110. nozzle_2_heating?: boolean; // Actual heater state from MQTT
  111. chamber?: number;
  112. chamber_target?: number;
  113. chamber_heating?: boolean; // Actual heater state from MQTT
  114. } | null;
  115. cover_url: string | null;
  116. hms_errors: HMSError[];
  117. ams: AMSUnit[];
  118. ams_exists: boolean;
  119. vt_tray: AMSTray | null; // Virtual tray / external spool
  120. sdcard: boolean; // SD card inserted
  121. store_to_sdcard: boolean; // Store sent files on SD card
  122. timelapse: boolean; // Timelapse recording active
  123. ipcam: boolean; // Live view enabled
  124. wifi_signal: number | null; // WiFi signal strength in dBm
  125. nozzles: NozzleInfo[]; // Nozzle hardware info (index 0=left/primary, 1=right)
  126. print_options: PrintOptions | null; // AI detection and print options
  127. // Calibration stage tracking
  128. stg_cur: number; // Current stage number (-1 = not calibrating)
  129. stg_cur_name: string | null; // Human-readable current stage name
  130. stg: number[]; // List of stage numbers in calibration sequence
  131. // Air conditioning mode (0=cooling, 1=heating)
  132. airduct_mode: number;
  133. // Print speed level (1=silent, 2=standard, 3=sport, 4=ludicrous)
  134. speed_level: number;
  135. // Chamber light on/off
  136. chamber_light: boolean;
  137. // Active extruder for dual nozzle (0=right, 1=left)
  138. active_extruder: number;
  139. // AMS mapping - which AMS is connected to which nozzle
  140. // Format: [ams_id_for_nozzle0, ams_id_for_nozzle1, ...] where -1 means no AMS
  141. ams_mapping: number[];
  142. // Per-AMS extruder mapping - extracted from each AMS unit's info field
  143. // Format: {ams_id: extruder_id} where extruder 0=right, 1=left
  144. // Note: JSON keys are always strings
  145. ams_extruder_map: Record<string, number>;
  146. // Currently loaded tray (global tray ID, 255 = no filament loaded, 254 = external spool)
  147. tray_now: number;
  148. // AMS status for filament change tracking (0=idle, 1=filament_change, 2=rfid_identifying, 3=assist, 4=calibration)
  149. ams_status_main: number;
  150. // AMS sub-status for filament change step (when main=1): 4=retraction, 6=load verification, 7=purge
  151. ams_status_sub: number;
  152. // mc_print_sub_stage - filament change step indicator used by OrcaSlicer/BambuStudio
  153. mc_print_sub_stage: number;
  154. // Timestamp of last AMS data update (for RFID refresh detection)
  155. last_ams_update: number;
  156. // Number of printable objects in current print (for skip objects feature)
  157. printable_objects_count: number;
  158. // Fan speeds (0-100 percentage, null if not available for this model)
  159. cooling_fan_speed: number | null; // Part cooling fan
  160. big_fan1_speed: number | null; // Auxiliary fan
  161. big_fan2_speed: number | null; // Chamber/exhaust fan
  162. heatbreak_fan_speed: number | null; // Hotend heatbreak fan
  163. }
  164. export interface PrinterCreate {
  165. name: string;
  166. serial_number: string;
  167. ip_address: string;
  168. access_code: string;
  169. model?: string;
  170. location?: string;
  171. auto_archive?: boolean;
  172. }
  173. // Archive types
  174. export interface ArchiveDuplicate {
  175. id: number;
  176. print_name: string | null;
  177. created_at: string;
  178. match_type: 'exact' | 'similar'; // 'exact' = hash match, 'similar' = name match
  179. }
  180. export interface Archive {
  181. id: number;
  182. printer_id: number | null;
  183. project_id: number | null;
  184. project_name: string | null;
  185. filename: string;
  186. file_path: string;
  187. file_size: number;
  188. content_hash: string | null;
  189. thumbnail_path: string | null;
  190. timelapse_path: string | null;
  191. source_3mf_path: string | null;
  192. duplicates: ArchiveDuplicate[] | null;
  193. duplicate_count: number;
  194. object_count: number | null;
  195. print_name: string | null;
  196. print_time_seconds: number | null;
  197. actual_time_seconds: number | null; // Computed from started_at/completed_at
  198. time_accuracy: number | null; // Percentage: 100 = perfect, >100 = faster than estimated
  199. filament_used_grams: number | null;
  200. filament_type: string | null;
  201. filament_color: string | null;
  202. layer_height: number | null;
  203. total_layers: number | null;
  204. nozzle_diameter: number | null;
  205. bed_temperature: number | null;
  206. nozzle_temperature: number | null;
  207. status: string;
  208. started_at: string | null;
  209. completed_at: string | null;
  210. extra_data: Record<string, unknown> | null;
  211. makerworld_url: string | null;
  212. designer: string | null;
  213. is_favorite: boolean;
  214. tags: string | null;
  215. notes: string | null;
  216. cost: number | null;
  217. photos: string[] | null;
  218. failure_reason: string | null;
  219. quantity: number;
  220. energy_kwh: number | null;
  221. energy_cost: number | null;
  222. created_at: string;
  223. }
  224. export interface ArchiveStats {
  225. total_prints: number;
  226. successful_prints: number;
  227. failed_prints: number;
  228. total_print_time_hours: number;
  229. total_filament_grams: number;
  230. total_cost: number;
  231. prints_by_filament_type: Record<string, number>;
  232. prints_by_printer: Record<string, number>;
  233. average_time_accuracy: number | null;
  234. time_accuracy_by_printer: Record<string, number> | null;
  235. total_energy_kwh: number;
  236. total_energy_cost: number;
  237. }
  238. export interface FailureAnalysis {
  239. period_days: number;
  240. total_prints: number;
  241. failed_prints: number;
  242. failure_rate: number;
  243. failures_by_reason: Record<string, number>;
  244. failures_by_filament: Record<string, number>;
  245. failures_by_printer: Record<string, number>;
  246. failures_by_hour: Record<number, number>;
  247. recent_failures: Array<{
  248. id: number;
  249. print_name: string;
  250. failure_reason: string | null;
  251. filament_type: string | null;
  252. printer_id: number | null;
  253. created_at: string | null;
  254. }>;
  255. trend: Array<{
  256. week_start: string;
  257. total_prints: number;
  258. failed_prints: number;
  259. failure_rate: number;
  260. }>;
  261. }
  262. export interface BulkUploadResult {
  263. uploaded: number;
  264. failed: number;
  265. results: Array<{ filename: string; id: number; status: string }>;
  266. errors: Array<{ filename: string; error: string }>;
  267. }
  268. // Archive Comparison types
  269. export interface ComparisonArchiveInfo {
  270. id: number;
  271. print_name: string;
  272. status: string;
  273. created_at: string | null;
  274. printer_id: number | null;
  275. project_name: string | null;
  276. }
  277. export interface ComparisonField {
  278. field: string;
  279. label: string;
  280. unit: string | null;
  281. values: (string | number | null)[];
  282. raw_values: (string | number | null)[];
  283. has_difference: boolean;
  284. }
  285. export interface SuccessCorrelationInsight {
  286. field: string;
  287. label: string;
  288. insight: string;
  289. success_avg?: number;
  290. failed_avg?: number;
  291. success_values?: string[];
  292. failed_values?: string[];
  293. }
  294. export interface SuccessCorrelation {
  295. has_both_outcomes: boolean;
  296. message?: string;
  297. successful_count?: number;
  298. failed_count?: number;
  299. insights?: SuccessCorrelationInsight[];
  300. }
  301. export interface ArchiveComparison {
  302. archives: ComparisonArchiveInfo[];
  303. comparison: ComparisonField[];
  304. differences: ComparisonField[];
  305. success_correlation: SuccessCorrelation;
  306. }
  307. export interface SimilarArchive {
  308. archive: {
  309. id: number;
  310. print_name: string;
  311. status: string;
  312. created_at: string | null;
  313. };
  314. match_reason: string;
  315. match_score: number;
  316. }
  317. // Project types
  318. export interface ProjectStats {
  319. total_archives: number;
  320. total_items: number; // Sum of quantities (total items printed)
  321. completed_prints: number;
  322. failed_prints: number;
  323. queued_prints: number;
  324. in_progress_prints: number;
  325. total_print_time_hours: number;
  326. total_filament_grams: number;
  327. progress_percent: number | null;
  328. estimated_cost: number;
  329. total_energy_kwh: number;
  330. total_energy_cost: number;
  331. remaining_prints: number | null;
  332. bom_total_items: number;
  333. bom_completed_items: number;
  334. }
  335. export interface ProjectChildPreview {
  336. id: number;
  337. name: string;
  338. color: string | null;
  339. status: string;
  340. progress_percent: number | null;
  341. }
  342. export interface Project {
  343. id: number;
  344. name: string;
  345. description: string | null;
  346. color: string | null;
  347. status: string; // active, completed, archived
  348. target_count: number | null;
  349. notes: string | null;
  350. attachments: ProjectAttachment[] | null;
  351. tags: string | null;
  352. due_date: string | null;
  353. priority: string; // low, normal, high, urgent
  354. budget: number | null;
  355. is_template: boolean;
  356. template_source_id: number | null;
  357. parent_id: number | null;
  358. parent_name: string | null;
  359. children: ProjectChildPreview[];
  360. created_at: string;
  361. updated_at: string;
  362. stats?: ProjectStats;
  363. }
  364. export interface ProjectAttachment {
  365. filename: string;
  366. original_name: string;
  367. size: number;
  368. uploaded_at: string;
  369. }
  370. export interface ArchivePreview {
  371. id: number;
  372. print_name: string | null;
  373. thumbnail_path: string | null;
  374. status: string;
  375. filament_type: string | null;
  376. filament_color: string | null;
  377. }
  378. export interface ProjectListItem {
  379. id: number;
  380. name: string;
  381. description: string | null;
  382. color: string | null;
  383. status: string;
  384. target_count: number | null;
  385. created_at: string;
  386. archive_count: number; // Number of print jobs
  387. total_items: number; // Sum of quantities (total items printed)
  388. queue_count: number;
  389. progress_percent: number | null;
  390. archives: ArchivePreview[];
  391. }
  392. export interface ProjectCreate {
  393. name: string;
  394. description?: string;
  395. color?: string;
  396. target_count?: number;
  397. notes?: string;
  398. tags?: string;
  399. due_date?: string;
  400. priority?: string;
  401. budget?: number;
  402. parent_id?: number;
  403. }
  404. export interface ProjectUpdate {
  405. name?: string;
  406. description?: string;
  407. color?: string;
  408. status?: string;
  409. target_count?: number;
  410. notes?: string;
  411. tags?: string;
  412. due_date?: string;
  413. priority?: string;
  414. budget?: number;
  415. parent_id?: number;
  416. }
  417. // BOM Types - Tracks sourced/purchased parts (hardware, electronics, etc.)
  418. export interface BOMItem {
  419. id: number;
  420. project_id: number;
  421. name: string;
  422. quantity_needed: number;
  423. quantity_acquired: number;
  424. unit_price: number | null;
  425. sourcing_url: string | null;
  426. archive_id: number | null;
  427. archive_name: string | null;
  428. stl_filename: string | null;
  429. remarks: string | null;
  430. sort_order: number;
  431. is_complete: boolean;
  432. created_at: string;
  433. updated_at: string;
  434. }
  435. export interface BOMItemCreate {
  436. name: string;
  437. quantity_needed?: number;
  438. unit_price?: number;
  439. sourcing_url?: string;
  440. archive_id?: number;
  441. stl_filename?: string;
  442. remarks?: string;
  443. }
  444. export interface BOMItemUpdate {
  445. name?: string;
  446. quantity_needed?: number;
  447. quantity_acquired?: number;
  448. unit_price?: number;
  449. sourcing_url?: string;
  450. archive_id?: number;
  451. stl_filename?: string;
  452. remarks?: string;
  453. }
  454. // Timeline Types
  455. export interface TimelineEvent {
  456. event_type: string;
  457. timestamp: string;
  458. title: string;
  459. description: string | null;
  460. metadata: Record<string, unknown> | null;
  461. }
  462. // API Key types
  463. export interface APIKey {
  464. id: number;
  465. name: string;
  466. key_prefix: string;
  467. can_queue: boolean;
  468. can_control_printer: boolean;
  469. can_read_status: boolean;
  470. printer_ids: number[] | null;
  471. enabled: boolean;
  472. last_used: string | null;
  473. created_at: string;
  474. expires_at: string | null;
  475. }
  476. export interface APIKeyCreate {
  477. name: string;
  478. can_queue?: boolean;
  479. can_control_printer?: boolean;
  480. can_read_status?: boolean;
  481. printer_ids?: number[] | null;
  482. expires_at?: string | null;
  483. }
  484. export interface APIKeyCreateResponse extends APIKey {
  485. key: string; // Full key, only shown on creation
  486. }
  487. export interface APIKeyUpdate {
  488. name?: string;
  489. can_queue?: boolean;
  490. can_control_printer?: boolean;
  491. can_read_status?: boolean;
  492. printer_ids?: number[] | null;
  493. enabled?: boolean;
  494. expires_at?: string | null;
  495. }
  496. // Settings types
  497. export interface AppSettings {
  498. auto_archive: boolean;
  499. save_thumbnails: boolean;
  500. capture_finish_photo: boolean;
  501. default_filament_cost: number;
  502. currency: string;
  503. energy_cost_per_kwh: number;
  504. energy_tracking_mode: 'print' | 'total';
  505. check_updates: boolean;
  506. notification_language: string;
  507. // AMS threshold settings
  508. ams_humidity_good: number; // <= this is green
  509. ams_humidity_fair: number; // <= this is orange, > is red
  510. ams_temp_good: number; // <= this is green/blue
  511. ams_temp_fair: number; // <= this is orange, > is red
  512. ams_history_retention_days: number; // days to keep AMS sensor history
  513. // Date/time format settings
  514. date_format: 'system' | 'us' | 'eu' | 'iso';
  515. time_format: 'system' | '12h' | '24h';
  516. // Default printer
  517. default_printer_id: number | null;
  518. // Telemetry
  519. telemetry_enabled: boolean;
  520. // Dark mode theme settings
  521. dark_style: 'classic' | 'glow' | 'vibrant';
  522. dark_background: 'neutral' | 'warm' | 'cool' | 'oled' | 'slate' | 'forest';
  523. dark_accent: 'green' | 'teal' | 'blue' | 'orange' | 'purple' | 'red';
  524. // Light mode theme settings
  525. light_style: 'classic' | 'glow' | 'vibrant';
  526. light_background: 'neutral' | 'warm' | 'cool';
  527. light_accent: 'green' | 'teal' | 'blue' | 'orange' | 'purple' | 'red';
  528. // FTP retry settings
  529. ftp_retry_enabled: boolean;
  530. ftp_retry_count: number;
  531. ftp_retry_delay: number;
  532. ftp_timeout: number;
  533. }
  534. export type AppSettingsUpdate = Partial<AppSettings>;
  535. // Cloud types
  536. export interface CloudAuthStatus {
  537. is_authenticated: boolean;
  538. email: string | null;
  539. }
  540. export interface CloudLoginResponse {
  541. success: boolean;
  542. needs_verification: boolean;
  543. message: string;
  544. }
  545. export interface SlicerSetting {
  546. setting_id: string;
  547. name: string;
  548. type: string;
  549. version: string | null;
  550. user_id: string | null;
  551. updated_time: string | null;
  552. }
  553. export interface SlicerSettingsResponse {
  554. filament: SlicerSetting[];
  555. printer: SlicerSetting[];
  556. process: SlicerSetting[];
  557. }
  558. export interface SlicerSettingDetail {
  559. message?: string | null;
  560. code?: string | null;
  561. error?: string | null;
  562. public: boolean;
  563. version?: string | null;
  564. type: string;
  565. name: string;
  566. update_time?: string | null;
  567. nickname?: string | null;
  568. base_id?: string | null;
  569. setting: Record<string, unknown>;
  570. filament_id?: string | null;
  571. setting_id?: string | null;
  572. }
  573. export interface SlicerSettingCreate {
  574. type: string; // 'filament', 'print', or 'printer'
  575. name: string;
  576. base_id: string;
  577. setting: Record<string, unknown>;
  578. }
  579. export interface SlicerSettingUpdate {
  580. name?: string;
  581. setting?: Record<string, unknown>;
  582. }
  583. export interface SlicerSettingDeleteResponse {
  584. success: boolean;
  585. message: string;
  586. }
  587. export interface FieldOption {
  588. value: string;
  589. label: string;
  590. }
  591. export interface FieldDefinition {
  592. key: string;
  593. label: string;
  594. type: 'text' | 'number' | 'boolean' | 'select';
  595. category: string;
  596. description?: string;
  597. options?: FieldOption[];
  598. unit?: string;
  599. min?: number;
  600. max?: number;
  601. step?: number;
  602. }
  603. export interface FieldDefinitionsResponse {
  604. version: string;
  605. description: string;
  606. fields: FieldDefinition[];
  607. }
  608. export interface CloudDevice {
  609. dev_id: string;
  610. name: string;
  611. dev_model_name: string | null;
  612. dev_product_name: string | null;
  613. online: boolean;
  614. }
  615. // Smart Plug types
  616. export interface SmartPlug {
  617. id: number;
  618. name: string;
  619. ip_address: string;
  620. printer_id: number | null;
  621. enabled: boolean;
  622. auto_on: boolean;
  623. auto_off: boolean;
  624. off_delay_mode: 'time' | 'temperature';
  625. off_delay_minutes: number;
  626. off_temp_threshold: number;
  627. username: string | null;
  628. password: string | null;
  629. // Power alerts
  630. power_alert_enabled: boolean;
  631. power_alert_high: number | null;
  632. power_alert_low: number | null;
  633. power_alert_last_triggered: string | null;
  634. // Schedule
  635. schedule_enabled: boolean;
  636. schedule_on_time: string | null;
  637. schedule_off_time: string | null;
  638. // Switchbar visibility
  639. show_in_switchbar: boolean;
  640. // Status
  641. last_state: string | null;
  642. last_checked: string | null;
  643. auto_off_executed: boolean; // True when auto-off was triggered after print
  644. created_at: string;
  645. updated_at: string;
  646. }
  647. export interface SmartPlugCreate {
  648. name: string;
  649. ip_address: string;
  650. printer_id?: number | null;
  651. enabled?: boolean;
  652. auto_on?: boolean;
  653. auto_off?: boolean;
  654. off_delay_mode?: 'time' | 'temperature';
  655. off_delay_minutes?: number;
  656. off_temp_threshold?: number;
  657. username?: string | null;
  658. password?: string | null;
  659. // Power alerts
  660. power_alert_enabled?: boolean;
  661. power_alert_high?: number | null;
  662. power_alert_low?: number | null;
  663. // Schedule
  664. schedule_enabled?: boolean;
  665. schedule_on_time?: string | null;
  666. schedule_off_time?: string | null;
  667. // Switchbar visibility
  668. show_in_switchbar?: boolean;
  669. }
  670. export interface SmartPlugUpdate {
  671. name?: string;
  672. ip_address?: string;
  673. printer_id?: number | null;
  674. enabled?: boolean;
  675. auto_on?: boolean;
  676. auto_off?: boolean;
  677. off_delay_mode?: 'time' | 'temperature';
  678. off_delay_minutes?: number;
  679. off_temp_threshold?: number;
  680. username?: string | null;
  681. password?: string | null;
  682. // Power alerts
  683. power_alert_enabled?: boolean;
  684. power_alert_high?: number | null;
  685. power_alert_low?: number | null;
  686. // Schedule
  687. schedule_enabled?: boolean;
  688. schedule_on_time?: string | null;
  689. schedule_off_time?: string | null;
  690. // Switchbar visibility
  691. show_in_switchbar?: boolean;
  692. }
  693. export interface SmartPlugEnergy {
  694. power: number | null; // Current watts
  695. voltage: number | null; // Volts
  696. current: number | null; // Amps
  697. today: number | null; // kWh used today
  698. yesterday: number | null; // kWh used yesterday
  699. total: number | null; // Total kWh
  700. factor: number | null; // Power factor (0-1)
  701. apparent_power: number | null; // VA
  702. reactive_power: number | null; // VAr
  703. }
  704. export interface SmartPlugStatus {
  705. state: string | null;
  706. reachable: boolean;
  707. device_name: string | null;
  708. energy: SmartPlugEnergy | null;
  709. }
  710. export interface SmartPlugTestResult {
  711. success: boolean;
  712. state: string | null;
  713. device_name: string | null;
  714. }
  715. // Tasmota Discovery types
  716. export interface TasmotaScanStatus {
  717. running: boolean;
  718. scanned: number;
  719. total: number;
  720. }
  721. export interface DiscoveredTasmotaDevice {
  722. ip_address: string;
  723. name: string;
  724. module: number | null;
  725. state: string | null;
  726. discovered_at: string | null;
  727. }
  728. // Print Queue types
  729. export interface PrintQueueItem {
  730. id: number;
  731. printer_id: number;
  732. archive_id: number;
  733. position: number;
  734. scheduled_time: string | null;
  735. require_previous_success: boolean;
  736. auto_off_after: boolean;
  737. manual_start: boolean; // Requires manual trigger to start (staged)
  738. ams_mapping: number[] | null; // AMS slot mapping for multi-color prints
  739. status: 'pending' | 'printing' | 'completed' | 'failed' | 'skipped' | 'cancelled';
  740. started_at: string | null;
  741. completed_at: string | null;
  742. error_message: string | null;
  743. created_at: string;
  744. archive_name?: string | null;
  745. archive_thumbnail?: string | null;
  746. printer_name?: string | null;
  747. print_time_seconds?: number | null; // Estimated print time from archive
  748. }
  749. export interface PrintQueueItemCreate {
  750. printer_id: number;
  751. archive_id: number;
  752. scheduled_time?: string | null;
  753. require_previous_success?: boolean;
  754. auto_off_after?: boolean;
  755. manual_start?: boolean; // Requires manual trigger to start (staged)
  756. ams_mapping?: number[] | null; // AMS slot mapping for multi-color prints
  757. }
  758. export interface PrintQueueItemUpdate {
  759. printer_id?: number;
  760. position?: number;
  761. scheduled_time?: string | null;
  762. require_previous_success?: boolean;
  763. auto_off_after?: boolean;
  764. manual_start?: boolean;
  765. ams_mapping?: number[];
  766. }
  767. // MQTT Logging types
  768. export interface MQTTLogEntry {
  769. timestamp: string;
  770. topic: string;
  771. direction: 'in' | 'out';
  772. payload: Record<string, unknown>;
  773. }
  774. export interface MQTTLogsResponse {
  775. logging_enabled: boolean;
  776. logs: MQTTLogEntry[];
  777. }
  778. // K-Profile types
  779. export interface KProfile {
  780. slot_id: number;
  781. extruder_id: number;
  782. nozzle_id: string;
  783. nozzle_diameter: string;
  784. filament_id: string;
  785. name: string;
  786. k_value: string;
  787. n_coef: string;
  788. ams_id: number;
  789. tray_id: number;
  790. setting_id: string | null;
  791. }
  792. export interface KProfileCreate {
  793. slot_id?: number; // Storage slot, 0 for new profiles
  794. extruder_id?: number;
  795. nozzle_id: string;
  796. nozzle_diameter: string;
  797. filament_id: string;
  798. name: string;
  799. k_value: string;
  800. n_coef?: string;
  801. ams_id?: number;
  802. tray_id?: number;
  803. setting_id?: string | null;
  804. }
  805. export interface KProfileDelete {
  806. slot_id: number; // cali_idx - calibration index to delete
  807. extruder_id: number;
  808. nozzle_id: string; // e.g., "HH00-0.4"
  809. nozzle_diameter: string; // e.g., "0.4"
  810. filament_id: string; // Bambu filament identifier
  811. setting_id?: string | null; // Setting ID (for X1C series)
  812. }
  813. export interface KProfilesResponse {
  814. profiles: KProfile[];
  815. nozzle_diameter: string;
  816. }
  817. export interface KProfileNote {
  818. setting_id: string;
  819. note: string;
  820. }
  821. export interface KProfileNotesResponse {
  822. notes: Record<string, string>; // setting_id -> note
  823. }
  824. // Slot Preset Mapping
  825. export interface SlotPresetMapping {
  826. ams_id: number;
  827. tray_id: number;
  828. preset_id: string;
  829. preset_name: string;
  830. }
  831. // Filament types
  832. export interface Filament {
  833. id: number;
  834. name: string;
  835. type: string; // PLA, PETG, ABS, etc.
  836. brand: string | null;
  837. color: string | null;
  838. color_hex: string | null;
  839. cost_per_kg: number;
  840. spool_weight_g: number;
  841. currency: string;
  842. density: number | null;
  843. print_temp_min: number | null;
  844. print_temp_max: number | null;
  845. bed_temp_min: number | null;
  846. bed_temp_max: number | null;
  847. created_at: string;
  848. updated_at: string;
  849. }
  850. // Notification Provider types
  851. export type ProviderType = 'callmebot' | 'ntfy' | 'pushover' | 'telegram' | 'email' | 'discord' | 'webhook';
  852. export interface NotificationProvider {
  853. id: number;
  854. name: string;
  855. provider_type: ProviderType;
  856. enabled: boolean;
  857. config: Record<string, unknown>;
  858. // Print lifecycle events
  859. on_print_start: boolean;
  860. on_print_complete: boolean;
  861. on_print_failed: boolean;
  862. on_print_stopped: boolean;
  863. on_print_progress: boolean;
  864. // Printer status events
  865. on_printer_offline: boolean;
  866. on_printer_error: boolean;
  867. on_filament_low: boolean;
  868. on_maintenance_due: boolean;
  869. // AMS environmental alarms (regular AMS)
  870. on_ams_humidity_high: boolean;
  871. on_ams_temperature_high: boolean;
  872. // AMS-HT environmental alarms
  873. on_ams_ht_humidity_high: boolean;
  874. on_ams_ht_temperature_high: boolean;
  875. // Quiet hours
  876. quiet_hours_enabled: boolean;
  877. quiet_hours_start: string | null;
  878. quiet_hours_end: string | null;
  879. // Daily digest
  880. daily_digest_enabled: boolean;
  881. daily_digest_time: string | null;
  882. // Printer filter
  883. printer_id: number | null;
  884. // Status tracking
  885. last_success: string | null;
  886. last_error: string | null;
  887. last_error_at: string | null;
  888. // Timestamps
  889. created_at: string;
  890. updated_at: string;
  891. }
  892. export interface NotificationProviderCreate {
  893. name: string;
  894. provider_type: ProviderType;
  895. enabled?: boolean;
  896. config: Record<string, unknown>;
  897. // Print lifecycle events
  898. on_print_start?: boolean;
  899. on_print_complete?: boolean;
  900. on_print_failed?: boolean;
  901. on_print_stopped?: boolean;
  902. on_print_progress?: boolean;
  903. // Printer status events
  904. on_printer_offline?: boolean;
  905. on_printer_error?: boolean;
  906. on_filament_low?: boolean;
  907. on_maintenance_due?: boolean;
  908. // AMS environmental alarms (regular AMS)
  909. on_ams_humidity_high?: boolean;
  910. on_ams_temperature_high?: boolean;
  911. // AMS-HT environmental alarms
  912. on_ams_ht_humidity_high?: boolean;
  913. on_ams_ht_temperature_high?: boolean;
  914. // Quiet hours
  915. quiet_hours_enabled?: boolean;
  916. quiet_hours_start?: string | null;
  917. quiet_hours_end?: string | null;
  918. // Daily digest
  919. daily_digest_enabled?: boolean;
  920. daily_digest_time?: string | null;
  921. // Printer filter
  922. printer_id?: number | null;
  923. }
  924. export interface NotificationProviderUpdate {
  925. name?: string;
  926. provider_type?: ProviderType;
  927. enabled?: boolean;
  928. config?: Record<string, unknown>;
  929. // Print lifecycle events
  930. on_print_start?: boolean;
  931. on_print_complete?: boolean;
  932. on_print_failed?: boolean;
  933. on_print_stopped?: boolean;
  934. on_print_progress?: boolean;
  935. // Printer status events
  936. on_printer_offline?: boolean;
  937. on_printer_error?: boolean;
  938. on_filament_low?: boolean;
  939. on_maintenance_due?: boolean;
  940. // AMS environmental alarms (regular AMS)
  941. on_ams_humidity_high?: boolean;
  942. on_ams_temperature_high?: boolean;
  943. // AMS-HT environmental alarms
  944. on_ams_ht_humidity_high?: boolean;
  945. on_ams_ht_temperature_high?: boolean;
  946. // Quiet hours
  947. quiet_hours_enabled?: boolean;
  948. quiet_hours_start?: string | null;
  949. quiet_hours_end?: string | null;
  950. // Daily digest
  951. daily_digest_enabled?: boolean;
  952. daily_digest_time?: string | null;
  953. // Printer filter
  954. printer_id?: number | null;
  955. }
  956. export interface NotificationTestRequest {
  957. provider_type: ProviderType;
  958. config: Record<string, unknown>;
  959. }
  960. export interface NotificationTestResponse {
  961. success: boolean;
  962. message: string;
  963. }
  964. // Provider-specific config types for reference
  965. export interface CallMeBotConfig {
  966. phone: string;
  967. apikey: string;
  968. }
  969. export interface NtfyConfig {
  970. server?: string;
  971. topic: string;
  972. auth_token?: string | null;
  973. }
  974. export interface PushoverConfig {
  975. user_key: string;
  976. app_token: string;
  977. priority?: number;
  978. }
  979. export interface TelegramConfig {
  980. bot_token: string;
  981. chat_id: string;
  982. }
  983. export interface EmailConfig {
  984. smtp_server: string;
  985. smtp_port?: number;
  986. username: string;
  987. password: string;
  988. from_email: string;
  989. to_email: string;
  990. use_tls?: boolean;
  991. }
  992. // Notification Template types
  993. export interface NotificationTemplate {
  994. id: number;
  995. event_type: string;
  996. name: string;
  997. title_template: string;
  998. body_template: string;
  999. is_default: boolean;
  1000. created_at: string;
  1001. updated_at: string;
  1002. }
  1003. export interface NotificationTemplateUpdate {
  1004. title_template?: string;
  1005. body_template?: string;
  1006. }
  1007. export interface EventVariablesResponse {
  1008. event_type: string;
  1009. event_name: string;
  1010. variables: string[];
  1011. }
  1012. export interface TemplatePreviewRequest {
  1013. event_type: string;
  1014. title_template: string;
  1015. body_template: string;
  1016. }
  1017. export interface TemplatePreviewResponse {
  1018. title: string;
  1019. body: string;
  1020. }
  1021. // Notification Log types
  1022. export interface NotificationLogEntry {
  1023. id: number;
  1024. provider_id: number;
  1025. provider_name: string | null;
  1026. provider_type: string | null;
  1027. event_type: string;
  1028. title: string;
  1029. message: string;
  1030. success: boolean;
  1031. error_message: string | null;
  1032. printer_id: number | null;
  1033. printer_name: string | null;
  1034. created_at: string;
  1035. }
  1036. export interface NotificationLogStats {
  1037. total: number;
  1038. success_count: number;
  1039. failure_count: number;
  1040. by_event_type: Record<string, number>;
  1041. by_provider: Record<string, number>;
  1042. }
  1043. // Spoolman types
  1044. export interface SpoolmanStatus {
  1045. enabled: boolean;
  1046. connected: boolean;
  1047. url: string | null;
  1048. }
  1049. export interface SkippedSpool {
  1050. location: string;
  1051. reason: string;
  1052. filament_type: string | null;
  1053. color: string | null;
  1054. }
  1055. export interface SpoolmanSyncResult {
  1056. success: boolean;
  1057. synced_count: number;
  1058. skipped_count: number;
  1059. skipped: SkippedSpool[];
  1060. errors: string[];
  1061. }
  1062. export interface UnlinkedSpool {
  1063. id: number;
  1064. filament_name: string | null;
  1065. filament_material: string | null;
  1066. filament_color_hex: string | null;
  1067. remaining_weight: number | null;
  1068. location: string | null;
  1069. }
  1070. // Update types
  1071. export interface VersionInfo {
  1072. version: string;
  1073. repo: string;
  1074. }
  1075. export interface UpdateCheckResult {
  1076. update_available: boolean;
  1077. current_version: string;
  1078. latest_version: string | null;
  1079. release_name?: string;
  1080. release_notes?: string;
  1081. release_url?: string;
  1082. published_at?: string;
  1083. error?: string;
  1084. message?: string;
  1085. is_docker?: boolean;
  1086. update_method?: 'docker' | 'git';
  1087. }
  1088. export interface UpdateStatus {
  1089. status: 'idle' | 'checking' | 'downloading' | 'installing' | 'complete' | 'error';
  1090. progress: number;
  1091. message: string;
  1092. error: string | null;
  1093. }
  1094. // Maintenance types
  1095. export interface MaintenanceType {
  1096. id: number;
  1097. name: string;
  1098. description: string | null;
  1099. default_interval_hours: number;
  1100. interval_type: 'hours' | 'days'; // "hours" = print hours, "days" = calendar days
  1101. icon: string | null;
  1102. wiki_url: string | null; // Documentation link
  1103. is_system: boolean;
  1104. created_at: string;
  1105. }
  1106. export interface MaintenanceTypeCreate {
  1107. name: string;
  1108. description?: string | null;
  1109. default_interval_hours?: number;
  1110. interval_type?: 'hours' | 'days';
  1111. icon?: string | null;
  1112. wiki_url?: string | null;
  1113. }
  1114. export interface MaintenanceStatus {
  1115. id: number;
  1116. printer_id: number;
  1117. printer_name: string;
  1118. printer_model: string | null;
  1119. maintenance_type_id: number;
  1120. maintenance_type_name: string;
  1121. maintenance_type_icon: string | null;
  1122. maintenance_type_wiki_url: string | null; // Custom wiki URL from type
  1123. enabled: boolean;
  1124. interval_hours: number; // For hours type: print hours; for days type: number of days
  1125. interval_type: 'hours' | 'days';
  1126. current_hours: number;
  1127. hours_since_maintenance: number;
  1128. hours_until_due: number;
  1129. days_since_maintenance: number | null; // For days type
  1130. days_until_due: number | null; // For days type
  1131. is_due: boolean;
  1132. is_warning: boolean;
  1133. last_performed_at: string | null;
  1134. }
  1135. export interface PrinterMaintenanceOverview {
  1136. printer_id: number;
  1137. printer_name: string;
  1138. printer_model: string | null;
  1139. total_print_hours: number;
  1140. maintenance_items: MaintenanceStatus[];
  1141. due_count: number;
  1142. warning_count: number;
  1143. }
  1144. export interface MaintenanceHistory {
  1145. id: number;
  1146. printer_maintenance_id: number;
  1147. performed_at: string;
  1148. hours_at_maintenance: number;
  1149. notes: string | null;
  1150. }
  1151. export interface MaintenanceSummary {
  1152. total_due: number;
  1153. total_warning: number;
  1154. printers_with_issues: Array<{
  1155. printer_id: number;
  1156. printer_name: string;
  1157. due_count: number;
  1158. warning_count: number;
  1159. }>;
  1160. }
  1161. // External Links (sidebar)
  1162. export interface ExternalLink {
  1163. id: number;
  1164. name: string;
  1165. url: string;
  1166. icon: string;
  1167. custom_icon: string | null;
  1168. sort_order: number;
  1169. created_at: string;
  1170. updated_at: string;
  1171. }
  1172. export interface ExternalLinkCreate {
  1173. name: string;
  1174. url: string;
  1175. icon: string;
  1176. }
  1177. export interface ExternalLinkUpdate {
  1178. name?: string;
  1179. url?: string;
  1180. icon?: string;
  1181. }
  1182. // API functions
  1183. export const api = {
  1184. // Printers
  1185. getPrinters: () => request<Printer[]>('/printers/'),
  1186. getPrinter: (id: number) => request<Printer>(`/printers/${id}`),
  1187. createPrinter: (data: PrinterCreate) =>
  1188. request<Printer>('/printers/', {
  1189. method: 'POST',
  1190. body: JSON.stringify(data),
  1191. }),
  1192. updatePrinter: (id: number, data: Partial<PrinterCreate>) =>
  1193. request<Printer>(`/printers/${id}`, {
  1194. method: 'PATCH',
  1195. body: JSON.stringify(data),
  1196. }),
  1197. deletePrinter: (id: number, deleteArchives: boolean = true) =>
  1198. request<{ status: string; archives_deleted: boolean }>(
  1199. `/printers/${id}?delete_archives=${deleteArchives}`,
  1200. { method: 'DELETE' }
  1201. ),
  1202. getPrinterStatus: (id: number) =>
  1203. request<PrinterStatus>(`/printers/${id}/status`),
  1204. refreshPrinterStatus: (id: number) =>
  1205. request<{ status: string }>(`/printers/${id}/refresh-status`, {
  1206. method: 'POST',
  1207. }),
  1208. connectPrinter: (id: number) =>
  1209. request<{ connected: boolean }>(`/printers/${id}/connect`, {
  1210. method: 'POST',
  1211. }),
  1212. disconnectPrinter: (id: number) =>
  1213. request<{ connected: boolean }>(`/printers/${id}/disconnect`, {
  1214. method: 'POST',
  1215. }),
  1216. // Print Control
  1217. stopPrint: (printerId: number) =>
  1218. request<{ success: boolean; message: string }>(`/printers/${printerId}/print/stop`, {
  1219. method: 'POST',
  1220. }),
  1221. pausePrint: (printerId: number) =>
  1222. request<{ success: boolean; message: string }>(`/printers/${printerId}/print/pause`, {
  1223. method: 'POST',
  1224. }),
  1225. resumePrint: (printerId: number) =>
  1226. request<{ success: boolean; message: string }>(`/printers/${printerId}/print/resume`, {
  1227. method: 'POST',
  1228. }),
  1229. // Chamber Light Control
  1230. setChamberLight: (printerId: number, on: boolean) =>
  1231. request<{ success: boolean; message: string }>(`/printers/${printerId}/chamber-light?on=${on}`, {
  1232. method: 'POST',
  1233. }),
  1234. // Skip Objects
  1235. getPrintableObjects: (printerId: number) =>
  1236. request<{
  1237. objects: Array<{ id: number; name: string; x: number | null; y: number | null; skipped: boolean }>;
  1238. total: number;
  1239. skipped_count: number;
  1240. is_printing: boolean;
  1241. bbox_all: [number, number, number, number] | null;
  1242. }>(`/printers/${printerId}/print/objects`),
  1243. skipObjects: (printerId: number, objectIds: number[]) =>
  1244. request<{ success: boolean; message: string; skipped_objects: number[] }>(
  1245. `/printers/${printerId}/print/skip-objects`,
  1246. {
  1247. method: 'POST',
  1248. body: JSON.stringify(objectIds),
  1249. }
  1250. ),
  1251. // AMS Control
  1252. refreshAmsSlot: (printerId: number, amsId: number, slotId: number) =>
  1253. request<{ success: boolean; message: string }>(
  1254. `/printers/${printerId}/ams/${amsId}/slot/${slotId}/refresh`,
  1255. { method: 'POST' }
  1256. ),
  1257. // MQTT Debug Logging
  1258. enableMQTTLogging: (printerId: number) =>
  1259. request<{ logging_enabled: boolean }>(`/printers/${printerId}/logging/enable`, {
  1260. method: 'POST',
  1261. }),
  1262. disableMQTTLogging: (printerId: number) =>
  1263. request<{ logging_enabled: boolean }>(`/printers/${printerId}/logging/disable`, {
  1264. method: 'POST',
  1265. }),
  1266. getMQTTLogs: (printerId: number) =>
  1267. request<MQTTLogsResponse>(`/printers/${printerId}/logging`),
  1268. clearMQTTLogs: (printerId: number) =>
  1269. request<{ status: string }>(`/printers/${printerId}/logging`, {
  1270. method: 'DELETE',
  1271. }),
  1272. // Printer File Manager
  1273. getPrinterFiles: (printerId: number, path = '/') =>
  1274. request<{
  1275. path: string;
  1276. files: Array<{
  1277. name: string;
  1278. is_directory: boolean;
  1279. size: number;
  1280. path: string;
  1281. }>;
  1282. }>(`/printers/${printerId}/files?path=${encodeURIComponent(path)}`),
  1283. getPrinterFileDownloadUrl: (printerId: number, path: string) =>
  1284. `${API_BASE}/printers/${printerId}/files/download?path=${encodeURIComponent(path)}`,
  1285. deletePrinterFile: (printerId: number, path: string) =>
  1286. request<{ status: string; path: string }>(`/printers/${printerId}/files?path=${encodeURIComponent(path)}`, {
  1287. method: 'DELETE',
  1288. }),
  1289. getPrinterStorage: (printerId: number) =>
  1290. request<{ used_bytes: number | null; free_bytes: number | null }>(`/printers/${printerId}/storage`),
  1291. // Archives
  1292. getArchives: (printerId?: number, projectId?: number, limit = 50, offset = 0) => {
  1293. const params = new URLSearchParams();
  1294. if (printerId) params.set('printer_id', String(printerId));
  1295. if (projectId) params.set('project_id', String(projectId));
  1296. params.set('limit', String(limit));
  1297. params.set('offset', String(offset));
  1298. return request<Archive[]>(`/archives/?${params}`);
  1299. },
  1300. getArchive: (id: number) => request<Archive>(`/archives/${id}`),
  1301. searchArchives: (query: string, options?: {
  1302. printerId?: number;
  1303. projectId?: number;
  1304. status?: string;
  1305. limit?: number;
  1306. offset?: number;
  1307. }) => {
  1308. const params = new URLSearchParams();
  1309. params.set('q', query);
  1310. if (options?.printerId) params.set('printer_id', String(options.printerId));
  1311. if (options?.projectId) params.set('project_id', String(options.projectId));
  1312. if (options?.status) params.set('status', options.status);
  1313. if (options?.limit) params.set('limit', String(options.limit));
  1314. if (options?.offset) params.set('offset', String(options.offset));
  1315. return request<Archive[]>(`/archives/search?${params}`);
  1316. },
  1317. rebuildSearchIndex: () => request<{ message: string }>('/archives/search/rebuild-index', { method: 'POST' }),
  1318. updateArchive: (id: number, data: {
  1319. printer_id?: number | null;
  1320. project_id?: number | null;
  1321. print_name?: string;
  1322. is_favorite?: boolean;
  1323. tags?: string;
  1324. notes?: string;
  1325. cost?: number;
  1326. failure_reason?: string | null;
  1327. status?: string;
  1328. quantity?: number;
  1329. }) =>
  1330. request<Archive>(`/archives/${id}`, {
  1331. method: 'PATCH',
  1332. body: JSON.stringify(data),
  1333. }),
  1334. toggleFavorite: (id: number) =>
  1335. request<Archive>(`/archives/${id}/favorite`, { method: 'POST' }),
  1336. deleteArchive: (id: number) =>
  1337. request<void>(`/archives/${id}`, { method: 'DELETE' }),
  1338. getArchiveStats: () => request<ArchiveStats>('/archives/stats'),
  1339. getFailureAnalysis: (options?: { days?: number; printerId?: number; projectId?: number }) => {
  1340. const params = new URLSearchParams();
  1341. if (options?.days) params.set('days', String(options.days));
  1342. if (options?.printerId) params.set('printer_id', String(options.printerId));
  1343. if (options?.projectId) params.set('project_id', String(options.projectId));
  1344. return request<FailureAnalysis>(`/archives/analysis/failures?${params}`);
  1345. },
  1346. compareArchives: (archiveIds: number[]) =>
  1347. request<ArchiveComparison>(`/archives/compare?archive_ids=${archiveIds.join(',')}`),
  1348. findSimilarArchives: (archiveId: number, limit = 10) =>
  1349. request<SimilarArchive[]>(`/archives/${archiveId}/similar?limit=${limit}`),
  1350. exportArchives: async (options?: {
  1351. format?: 'csv' | 'xlsx';
  1352. fields?: string[];
  1353. printerId?: number;
  1354. projectId?: number;
  1355. status?: string;
  1356. dateFrom?: string;
  1357. dateTo?: string;
  1358. search?: string;
  1359. }): Promise<{ blob: Blob; filename: string }> => {
  1360. const params = new URLSearchParams();
  1361. if (options?.format) params.set('format', options.format);
  1362. if (options?.fields) params.set('fields', options.fields.join(','));
  1363. if (options?.printerId) params.set('printer_id', String(options.printerId));
  1364. if (options?.projectId) params.set('project_id', String(options.projectId));
  1365. if (options?.status) params.set('status', options.status);
  1366. if (options?.dateFrom) params.set('date_from', options.dateFrom);
  1367. if (options?.dateTo) params.set('date_to', options.dateTo);
  1368. if (options?.search) params.set('search', options.search);
  1369. const response = await fetch(`${API_BASE}/archives/export?${params}`);
  1370. if (!response.ok) {
  1371. const error = await response.json().catch(() => ({}));
  1372. throw new Error(error.detail || `HTTP ${response.status}`);
  1373. }
  1374. const contentDisposition = response.headers.get('Content-Disposition');
  1375. let filename = options?.format === 'xlsx' ? 'archives_export.xlsx' : 'archives_export.csv';
  1376. if (contentDisposition) {
  1377. const match = contentDisposition.match(/filename="?([^"]+)"?/);
  1378. if (match) filename = match[1];
  1379. }
  1380. const blob = await response.blob();
  1381. return { blob, filename };
  1382. },
  1383. exportStats: async (options?: {
  1384. format?: 'csv' | 'xlsx';
  1385. days?: number;
  1386. printerId?: number;
  1387. projectId?: number;
  1388. }): Promise<{ blob: Blob; filename: string }> => {
  1389. const params = new URLSearchParams();
  1390. if (options?.format) params.set('format', options.format);
  1391. if (options?.days) params.set('days', String(options.days));
  1392. if (options?.printerId) params.set('printer_id', String(options.printerId));
  1393. if (options?.projectId) params.set('project_id', String(options.projectId));
  1394. const response = await fetch(`${API_BASE}/archives/stats/export?${params}`);
  1395. if (!response.ok) {
  1396. const error = await response.json().catch(() => ({}));
  1397. throw new Error(error.detail || `HTTP ${response.status}`);
  1398. }
  1399. const contentDisposition = response.headers.get('Content-Disposition');
  1400. let filename = options?.format === 'xlsx' ? 'stats_export.xlsx' : 'stats_export.csv';
  1401. if (contentDisposition) {
  1402. const match = contentDisposition.match(/filename="?([^"]+)"?/);
  1403. if (match) filename = match[1];
  1404. }
  1405. const blob = await response.blob();
  1406. return { blob, filename };
  1407. },
  1408. getArchiveDuplicates: (id: number) =>
  1409. request<{ duplicates: ArchiveDuplicate[]; count: number }>(`/archives/${id}/duplicates`),
  1410. backfillContentHashes: () =>
  1411. request<{ updated: number; errors: Array<{ id: number; error: string }> }>('/archives/backfill-hashes', {
  1412. method: 'POST',
  1413. }),
  1414. getArchiveThumbnail: (id: number) => `${API_BASE}/archives/${id}/thumbnail?v=${Date.now()}`,
  1415. getArchiveDownload: (id: number) => `${API_BASE}/archives/${id}/download`,
  1416. getArchiveGcode: (id: number) => `${API_BASE}/archives/${id}/gcode`,
  1417. getArchivePlatePreview: (id: number) => `${API_BASE}/archives/${id}/plate-preview`,
  1418. getArchiveTimelapse: (id: number) => `${API_BASE}/archives/${id}/timelapse?v=${Date.now()}`,
  1419. scanArchiveTimelapse: (id: number) =>
  1420. request<{
  1421. status: string;
  1422. message: string;
  1423. filename?: string;
  1424. available_files?: Array<{ name: string; path: string; size: number; mtime: string | null }>;
  1425. }>(`/archives/${id}/timelapse/scan`, {
  1426. method: 'POST',
  1427. }),
  1428. selectArchiveTimelapse: (id: number, filename: string) =>
  1429. request<{ status: string; message: string; filename: string }>(
  1430. `/archives/${id}/timelapse/select?filename=${encodeURIComponent(filename)}`,
  1431. { method: 'POST' }
  1432. ),
  1433. uploadArchiveTimelapse: async (archiveId: number, file: File): Promise<{ status: string; filename: string }> => {
  1434. const formData = new FormData();
  1435. formData.append('file', file);
  1436. const response = await fetch(`${API_BASE}/archives/${archiveId}/timelapse/upload`, {
  1437. method: 'POST',
  1438. body: formData,
  1439. });
  1440. if (!response.ok) {
  1441. const error = await response.json().catch(() => ({}));
  1442. throw new Error(error.detail || `HTTP ${response.status}`);
  1443. }
  1444. return response.json();
  1445. },
  1446. // Timelapse Editor
  1447. getTimelapseInfo: (archiveId: number) =>
  1448. request<{
  1449. duration: number;
  1450. width: number;
  1451. height: number;
  1452. fps: number;
  1453. codec: string;
  1454. file_size: number;
  1455. has_audio: boolean;
  1456. }>(`/archives/${archiveId}/timelapse/info`),
  1457. getTimelapseThumbnails: (archiveId: number, count: number = 10) =>
  1458. request<{
  1459. thumbnails: string[];
  1460. timestamps: number[];
  1461. }>(`/archives/${archiveId}/timelapse/thumbnails?count=${count}`),
  1462. processTimelapse: async (
  1463. archiveId: number,
  1464. params: {
  1465. trimStart?: number;
  1466. trimEnd?: number;
  1467. speed?: number;
  1468. saveMode: 'replace' | 'new';
  1469. outputFilename?: string;
  1470. },
  1471. audioFile?: File
  1472. ): Promise<{ status: string; output_path: string | null; message: string }> => {
  1473. const formData = new FormData();
  1474. formData.append('trim_start', String(params.trimStart ?? 0));
  1475. if (params.trimEnd !== undefined) {
  1476. formData.append('trim_end', String(params.trimEnd));
  1477. }
  1478. formData.append('speed', String(params.speed ?? 1));
  1479. formData.append('save_mode', params.saveMode);
  1480. if (params.outputFilename) {
  1481. formData.append('output_filename', params.outputFilename);
  1482. }
  1483. if (audioFile) {
  1484. formData.append('audio', audioFile);
  1485. }
  1486. const response = await fetch(`${API_BASE}/archives/${archiveId}/timelapse/process`, {
  1487. method: 'POST',
  1488. body: formData,
  1489. });
  1490. if (!response.ok) {
  1491. const error = await response.json().catch(() => ({}));
  1492. throw new Error(error.detail || `HTTP ${response.status}`);
  1493. }
  1494. return response.json();
  1495. },
  1496. // Photos
  1497. getArchivePhotoUrl: (archiveId: number, filename: string) =>
  1498. `${API_BASE}/archives/${archiveId}/photos/${encodeURIComponent(filename)}`,
  1499. uploadArchivePhoto: async (archiveId: number, file: File): Promise<{ status: string; filename: string; photos: string[] }> => {
  1500. const formData = new FormData();
  1501. formData.append('file', file);
  1502. const response = await fetch(`${API_BASE}/archives/${archiveId}/photos`, {
  1503. method: 'POST',
  1504. body: formData,
  1505. });
  1506. if (!response.ok) {
  1507. const error = await response.json().catch(() => ({}));
  1508. throw new Error(error.detail || `HTTP ${response.status}`);
  1509. }
  1510. return response.json();
  1511. },
  1512. deleteArchivePhoto: (archiveId: number, filename: string) =>
  1513. request<{ status: string; photos: string[] | null }>(`/archives/${archiveId}/photos/${encodeURIComponent(filename)}`, {
  1514. method: 'DELETE',
  1515. }),
  1516. // Source 3MF (original slicer project file)
  1517. getSource3mfDownloadUrl: (archiveId: number) =>
  1518. `${API_BASE}/archives/${archiveId}/source`,
  1519. getSource3mfForSlicer: (archiveId: number, filename: string) =>
  1520. `${API_BASE}/archives/${archiveId}/source/${encodeURIComponent(filename.endsWith('.3mf') ? filename : filename + '.3mf')}`,
  1521. uploadSource3mf: async (archiveId: number, file: File): Promise<{ status: string; filename: string }> => {
  1522. const formData = new FormData();
  1523. formData.append('file', file);
  1524. const response = await fetch(`${API_BASE}/archives/${archiveId}/source`, {
  1525. method: 'POST',
  1526. body: formData,
  1527. });
  1528. if (!response.ok) {
  1529. const error = await response.json().catch(() => ({}));
  1530. throw new Error(error.detail || `HTTP ${response.status}`);
  1531. }
  1532. return response.json();
  1533. },
  1534. deleteSource3mf: (archiveId: number) =>
  1535. request<{ status: string }>(`/archives/${archiveId}/source`, {
  1536. method: 'DELETE',
  1537. }),
  1538. // QR Code
  1539. getArchiveQRCodeUrl: (archiveId: number, size = 200) =>
  1540. `${API_BASE}/archives/${archiveId}/qrcode?size=${size}`,
  1541. getArchiveCapabilities: (id: number) =>
  1542. request<{
  1543. has_model: boolean;
  1544. has_gcode: boolean;
  1545. has_source: boolean;
  1546. build_volume: { x: number; y: number; z: number };
  1547. filament_colors: string[];
  1548. }>(`/archives/${id}/capabilities`),
  1549. // Project Page
  1550. getArchiveProjectPage: (id: number) =>
  1551. request<{
  1552. title: string | null;
  1553. description: string | null;
  1554. designer: string | null;
  1555. designer_user_id: string | null;
  1556. license: string | null;
  1557. copyright: string | null;
  1558. creation_date: string | null;
  1559. modification_date: string | null;
  1560. origin: string | null;
  1561. profile_title: string | null;
  1562. profile_description: string | null;
  1563. profile_cover: string | null;
  1564. profile_user_id: string | null;
  1565. profile_user_name: string | null;
  1566. design_model_id: string | null;
  1567. design_profile_id: string | null;
  1568. design_region: string | null;
  1569. model_pictures: Array<{ name: string; path: string; url: string }>;
  1570. profile_pictures: Array<{ name: string; path: string; url: string }>;
  1571. thumbnails: Array<{ name: string; path: string; url: string }>;
  1572. }>(`/archives/${id}/project-page`),
  1573. updateArchiveProjectPage: (id: number, data: {
  1574. title?: string;
  1575. description?: string;
  1576. designer?: string;
  1577. license?: string;
  1578. copyright?: string;
  1579. profile_title?: string;
  1580. profile_description?: string;
  1581. }) =>
  1582. request(`/archives/${id}/project-page`, {
  1583. method: 'PATCH',
  1584. body: JSON.stringify(data),
  1585. }),
  1586. getArchiveProjectImageUrl: (archiveId: number, imagePath: string) =>
  1587. `${API_BASE}/archives/${archiveId}/project-image/${encodeURIComponent(imagePath)}`,
  1588. getArchiveForSlicer: (id: number, filename: string) =>
  1589. `${API_BASE}/archives/${id}/file/${encodeURIComponent(filename.endsWith('.3mf') ? filename : filename + '.3mf')}`,
  1590. getArchiveFilamentRequirements: (archiveId: number) =>
  1591. request<{
  1592. archive_id: number;
  1593. filename: string;
  1594. filaments: Array<{
  1595. slot_id: number;
  1596. type: string;
  1597. color: string;
  1598. used_grams: number;
  1599. used_meters: number;
  1600. }>;
  1601. }>(`/archives/${archiveId}/filament-requirements`),
  1602. reprintArchive: (
  1603. archiveId: number,
  1604. printerId: number,
  1605. options?: {
  1606. ams_mapping?: number[];
  1607. timelapse?: boolean;
  1608. bed_levelling?: boolean;
  1609. flow_cali?: boolean;
  1610. vibration_cali?: boolean;
  1611. layer_inspect?: boolean;
  1612. use_ams?: boolean;
  1613. }
  1614. ) =>
  1615. request<{ status: string; printer_id: number; archive_id: number; filename: string }>(
  1616. `/archives/${archiveId}/reprint?printer_id=${printerId}`,
  1617. {
  1618. method: 'POST',
  1619. headers: options ? { 'Content-Type': 'application/json' } : undefined,
  1620. body: options ? JSON.stringify(options) : undefined,
  1621. }
  1622. ),
  1623. uploadArchive: async (file: File, printerId?: number): Promise<Archive> => {
  1624. const formData = new FormData();
  1625. formData.append('file', file);
  1626. const url = printerId
  1627. ? `${API_BASE}/archives/upload?printer_id=${printerId}`
  1628. : `${API_BASE}/archives/upload`;
  1629. const response = await fetch(url, {
  1630. method: 'POST',
  1631. body: formData,
  1632. });
  1633. if (!response.ok) {
  1634. const error = await response.json().catch(() => ({}));
  1635. throw new Error(error.detail || `HTTP ${response.status}`);
  1636. }
  1637. return response.json();
  1638. },
  1639. uploadArchivesBulk: async (files: File[], printerId?: number): Promise<BulkUploadResult> => {
  1640. const formData = new FormData();
  1641. files.forEach((file) => formData.append('files', file));
  1642. const url = printerId
  1643. ? `${API_BASE}/archives/upload-bulk?printer_id=${printerId}`
  1644. : `${API_BASE}/archives/upload-bulk`;
  1645. const response = await fetch(url, {
  1646. method: 'POST',
  1647. body: formData,
  1648. });
  1649. if (!response.ok) {
  1650. const error = await response.json().catch(() => ({}));
  1651. throw new Error(error.detail || `HTTP ${response.status}`);
  1652. }
  1653. return response.json();
  1654. },
  1655. // Settings
  1656. getSettings: () => request<AppSettings>('/settings/'),
  1657. updateSettings: (data: AppSettingsUpdate) =>
  1658. request<AppSettings>('/settings/', {
  1659. method: 'PUT',
  1660. body: JSON.stringify(data),
  1661. }),
  1662. resetSettings: () =>
  1663. request<AppSettings>('/settings/reset', { method: 'POST' }),
  1664. exportBackup: async (categories?: Record<string, boolean>): Promise<{ blob: Blob; filename: string }> => {
  1665. const params = new URLSearchParams();
  1666. if (categories) {
  1667. if (categories.settings !== undefined) params.set('include_settings', String(categories.settings));
  1668. if (categories.notifications !== undefined) params.set('include_notifications', String(categories.notifications));
  1669. if (categories.templates !== undefined) params.set('include_templates', String(categories.templates));
  1670. if (categories.smart_plugs !== undefined) params.set('include_smart_plugs', String(categories.smart_plugs));
  1671. if (categories.external_links !== undefined) params.set('include_external_links', String(categories.external_links));
  1672. if (categories.printers !== undefined) params.set('include_printers', String(categories.printers));
  1673. if (categories.filaments !== undefined) params.set('include_filaments', String(categories.filaments));
  1674. if (categories.maintenance !== undefined) params.set('include_maintenance', String(categories.maintenance));
  1675. if (categories.archives !== undefined) params.set('include_archives', String(categories.archives));
  1676. if (categories.projects !== undefined) params.set('include_projects', String(categories.projects));
  1677. if (categories.access_codes !== undefined) params.set('include_access_codes', String(categories.access_codes));
  1678. }
  1679. const url = `${API_BASE}/settings/backup${params.toString() ? '?' + params.toString() : ''}`;
  1680. const response = await fetch(url);
  1681. // Get filename from Content-Disposition header
  1682. const contentDisposition = response.headers.get('Content-Disposition');
  1683. let filename = 'bambuddy-backup.json';
  1684. if (contentDisposition) {
  1685. const match = contentDisposition.match(/filename=([^;]+)/);
  1686. if (match) filename = match[1].trim();
  1687. }
  1688. const blob = await response.blob();
  1689. return { blob, filename };
  1690. },
  1691. importBackup: async (file: File, overwrite = false) => {
  1692. const formData = new FormData();
  1693. formData.append('file', file);
  1694. const url = `${API_BASE}/settings/restore${overwrite ? '?overwrite=true' : ''}`;
  1695. const response = await fetch(url, {
  1696. method: 'POST',
  1697. body: formData,
  1698. });
  1699. return response.json() as Promise<{
  1700. success: boolean;
  1701. message: string;
  1702. restored?: Record<string, number>;
  1703. skipped?: Record<string, number>;
  1704. skipped_details?: Record<string, string[]>;
  1705. files_restored?: number;
  1706. total_skipped?: number;
  1707. }>;
  1708. },
  1709. checkFfmpeg: () =>
  1710. request<{ installed: boolean; path: string | null }>('/settings/check-ffmpeg'),
  1711. // Cloud
  1712. getCloudStatus: () => request<CloudAuthStatus>('/cloud/status'),
  1713. cloudLogin: (email: string, password: string, region = 'global') =>
  1714. request<CloudLoginResponse>('/cloud/login', {
  1715. method: 'POST',
  1716. body: JSON.stringify({ email, password, region }),
  1717. }),
  1718. cloudVerify: (email: string, code: string) =>
  1719. request<CloudLoginResponse>('/cloud/verify', {
  1720. method: 'POST',
  1721. body: JSON.stringify({ email, code }),
  1722. }),
  1723. cloudSetToken: (access_token: string) =>
  1724. request<CloudAuthStatus>('/cloud/token', {
  1725. method: 'POST',
  1726. body: JSON.stringify({ access_token }),
  1727. }),
  1728. cloudLogout: () =>
  1729. request<{ success: boolean }>('/cloud/logout', { method: 'POST' }),
  1730. getCloudSettings: (version = '02.04.00.70') =>
  1731. request<SlicerSettingsResponse>(`/cloud/settings?version=${version}`),
  1732. getCloudSettingDetail: (settingId: string) =>
  1733. request<SlicerSettingDetail>(`/cloud/settings/${settingId}`),
  1734. createCloudSetting: (data: SlicerSettingCreate) =>
  1735. request<SlicerSettingDetail>('/cloud/settings', {
  1736. method: 'POST',
  1737. body: JSON.stringify(data),
  1738. }),
  1739. updateCloudSetting: (settingId: string, data: SlicerSettingUpdate) =>
  1740. request<SlicerSettingDetail>(`/cloud/settings/${settingId}`, {
  1741. method: 'PUT',
  1742. body: JSON.stringify(data),
  1743. }),
  1744. deleteCloudSetting: (settingId: string) =>
  1745. request<SlicerSettingDeleteResponse>(`/cloud/settings/${settingId}`, {
  1746. method: 'DELETE',
  1747. }),
  1748. getCloudDevices: () => request<CloudDevice[]>('/cloud/devices'),
  1749. getCloudFields: (presetType: 'filament' | 'print' | 'process' | 'printer') =>
  1750. request<FieldDefinitionsResponse>(`/cloud/fields/${presetType}`),
  1751. getAllCloudFields: () =>
  1752. request<Record<string, FieldDefinitionsResponse>>('/cloud/fields'),
  1753. getFilamentInfo: (settingIds: string[]) =>
  1754. request<Record<string, { name: string; k: number | null }>>('/cloud/filament-info', {
  1755. method: 'POST',
  1756. body: JSON.stringify(settingIds),
  1757. }),
  1758. // Smart Plugs
  1759. getSmartPlugs: () => request<SmartPlug[]>('/smart-plugs/'),
  1760. getSmartPlug: (id: number) => request<SmartPlug>(`/smart-plugs/${id}`),
  1761. getSmartPlugByPrinter: (printerId: number) => request<SmartPlug | null>(`/smart-plugs/by-printer/${printerId}`),
  1762. createSmartPlug: (data: SmartPlugCreate) =>
  1763. request<SmartPlug>('/smart-plugs/', {
  1764. method: 'POST',
  1765. body: JSON.stringify(data),
  1766. }),
  1767. updateSmartPlug: (id: number, data: SmartPlugUpdate) =>
  1768. request<SmartPlug>(`/smart-plugs/${id}`, {
  1769. method: 'PATCH',
  1770. body: JSON.stringify(data),
  1771. }),
  1772. deleteSmartPlug: (id: number) =>
  1773. request<void>(`/smart-plugs/${id}`, { method: 'DELETE' }),
  1774. controlSmartPlug: (id: number, action: 'on' | 'off' | 'toggle') =>
  1775. request<{ success: boolean; action: string }>(`/smart-plugs/${id}/control`, {
  1776. method: 'POST',
  1777. body: JSON.stringify({ action }),
  1778. }),
  1779. getSmartPlugStatus: (id: number) =>
  1780. request<SmartPlugStatus>(`/smart-plugs/${id}/status`),
  1781. testSmartPlugConnection: (ip_address: string, username?: string | null, password?: string | null) =>
  1782. request<SmartPlugTestResult>('/smart-plugs/test-connection', {
  1783. method: 'POST',
  1784. body: JSON.stringify({ ip_address, username, password }),
  1785. }),
  1786. // Tasmota Discovery (auto-detects network)
  1787. startTasmotaScan: () =>
  1788. fetch(`${API_BASE}/smart-plugs/discover/scan`, { method: 'POST' })
  1789. .then(res => res.ok ? res.json() : res.json().then(e => { throw new Error(e.detail || `HTTP ${res.status}`); })),
  1790. getTasmotaScanStatus: () =>
  1791. request<TasmotaScanStatus>('/smart-plugs/discover/status'),
  1792. stopTasmotaScan: () =>
  1793. fetch(`${API_BASE}/smart-plugs/discover/stop`, { method: 'POST' })
  1794. .then(res => res.ok ? res.json() : res.json().then(e => { throw new Error(e.detail || `HTTP ${res.status}`); })),
  1795. getDiscoveredTasmotaDevices: () =>
  1796. request<DiscoveredTasmotaDevice[]>('/smart-plugs/discover/devices'),
  1797. // Print Queue
  1798. getQueue: (printerId?: number, status?: string) => {
  1799. const params = new URLSearchParams();
  1800. if (printerId) params.set('printer_id', String(printerId));
  1801. if (status) params.set('status', status);
  1802. return request<PrintQueueItem[]>(`/queue/?${params}`);
  1803. },
  1804. getQueueItem: (id: number) => request<PrintQueueItem>(`/queue/${id}`),
  1805. addToQueue: (data: PrintQueueItemCreate) =>
  1806. request<PrintQueueItem>('/queue/', {
  1807. method: 'POST',
  1808. body: JSON.stringify(data),
  1809. }),
  1810. updateQueueItem: (id: number, data: PrintQueueItemUpdate) =>
  1811. request<PrintQueueItem>(`/queue/${id}`, {
  1812. method: 'PATCH',
  1813. body: JSON.stringify(data),
  1814. }),
  1815. removeFromQueue: (id: number) =>
  1816. request<{ message: string }>(`/queue/${id}`, { method: 'DELETE' }),
  1817. reorderQueue: (items: { id: number; position: number }[]) =>
  1818. request<{ message: string }>('/queue/reorder', {
  1819. method: 'POST',
  1820. body: JSON.stringify({ items }),
  1821. }),
  1822. cancelQueueItem: (id: number) =>
  1823. request<{ message: string }>(`/queue/${id}/cancel`, { method: 'POST' }),
  1824. stopQueueItem: (id: number) =>
  1825. request<{ message: string }>(`/queue/${id}/stop`, { method: 'POST' }),
  1826. startQueueItem: (id: number) =>
  1827. request<PrintQueueItem>(`/queue/${id}/start`, { method: 'POST' }),
  1828. // K-Profiles
  1829. getKProfiles: (printerId: number, nozzleDiameter = '0.4') =>
  1830. request<KProfilesResponse>(`/printers/${printerId}/kprofiles/?nozzle_diameter=${nozzleDiameter}`),
  1831. setKProfile: (printerId: number, profile: KProfileCreate) =>
  1832. request<{ success: boolean; message: string }>(`/printers/${printerId}/kprofiles/`, {
  1833. method: 'POST',
  1834. body: JSON.stringify(profile),
  1835. }),
  1836. deleteKProfile: (printerId: number, profile: KProfileDelete) =>
  1837. request<{ success: boolean; message: string }>(`/printers/${printerId}/kprofiles/`, {
  1838. method: 'DELETE',
  1839. body: JSON.stringify(profile),
  1840. }),
  1841. setKProfilesBatch: (printerId: number, profiles: KProfileCreate[]) =>
  1842. request<{ success: boolean; message: string }>(`/printers/${printerId}/kprofiles/batch`, {
  1843. method: 'POST',
  1844. body: JSON.stringify(profiles),
  1845. }),
  1846. // K-Profile Notes (stored locally, not on printer)
  1847. getKProfileNotes: (printerId: number) =>
  1848. request<KProfileNotesResponse>(`/printers/${printerId}/kprofiles/notes`),
  1849. setKProfileNote: (printerId: number, settingId: string, note: string) =>
  1850. request<{ success: boolean; message: string }>(`/printers/${printerId}/kprofiles/notes`, {
  1851. method: 'PUT',
  1852. body: JSON.stringify({ setting_id: settingId, note }),
  1853. }),
  1854. deleteKProfileNote: (printerId: number, settingId: string) =>
  1855. request<{ success: boolean; message: string }>(`/printers/${printerId}/kprofiles/notes/${encodeURIComponent(settingId)}`, {
  1856. method: 'DELETE',
  1857. }),
  1858. // Slot Preset Mappings
  1859. getSlotPresets: (printerId: number) =>
  1860. request<Record<number, SlotPresetMapping>>(`/printers/${printerId}/slot-presets`),
  1861. getSlotPreset: (printerId: number, amsId: number, trayId: number) =>
  1862. request<SlotPresetMapping | null>(`/printers/${printerId}/slot-presets/${amsId}/${trayId}`),
  1863. saveSlotPreset: (printerId: number, amsId: number, trayId: number, presetId: string, presetName: string) =>
  1864. request<SlotPresetMapping>(`/printers/${printerId}/slot-presets/${amsId}/${trayId}?preset_id=${encodeURIComponent(presetId)}&preset_name=${encodeURIComponent(presetName)}`, {
  1865. method: 'PUT',
  1866. }),
  1867. deleteSlotPreset: (printerId: number, amsId: number, trayId: number) =>
  1868. request<{ success: boolean }>(`/printers/${printerId}/slot-presets/${amsId}/${trayId}`, {
  1869. method: 'DELETE',
  1870. }),
  1871. // Filaments
  1872. listFilaments: () => request<Filament[]>('/filaments/'),
  1873. getFilament: (id: number) => request<Filament>(`/filaments/${id}`),
  1874. getFilamentsByType: (type: string) => request<Filament[]>(`/filaments/by-type/${type}`),
  1875. // Notification Providers
  1876. getNotificationProviders: () => request<NotificationProvider[]>('/notifications/'),
  1877. getNotificationProvider: (id: number) => request<NotificationProvider>(`/notifications/${id}`),
  1878. createNotificationProvider: (data: NotificationProviderCreate) =>
  1879. request<NotificationProvider>('/notifications/', {
  1880. method: 'POST',
  1881. body: JSON.stringify(data),
  1882. }),
  1883. updateNotificationProvider: (id: number, data: NotificationProviderUpdate) =>
  1884. request<NotificationProvider>(`/notifications/${id}`, {
  1885. method: 'PATCH',
  1886. body: JSON.stringify(data),
  1887. }),
  1888. deleteNotificationProvider: (id: number) =>
  1889. request<{ message: string }>(`/notifications/${id}`, { method: 'DELETE' }),
  1890. testNotificationProvider: (id: number) =>
  1891. request<NotificationTestResponse>(`/notifications/${id}/test`, { method: 'POST' }),
  1892. testNotificationConfig: (data: NotificationTestRequest) =>
  1893. request<NotificationTestResponse>('/notifications/test-config', {
  1894. method: 'POST',
  1895. body: JSON.stringify(data),
  1896. }),
  1897. testAllNotificationProviders: () =>
  1898. request<{
  1899. tested: number;
  1900. success: number;
  1901. failed: number;
  1902. results: Array<{
  1903. provider_id: number;
  1904. provider_name: string;
  1905. provider_type: string;
  1906. success: boolean;
  1907. message: string;
  1908. }>;
  1909. }>('/notifications/test-all', { method: 'POST' }),
  1910. // Notification Templates
  1911. getNotificationTemplates: () => request<NotificationTemplate[]>('/notification-templates'),
  1912. getNotificationTemplate: (id: number) => request<NotificationTemplate>(`/notification-templates/${id}`),
  1913. updateNotificationTemplate: (id: number, data: NotificationTemplateUpdate) =>
  1914. request<NotificationTemplate>(`/notification-templates/${id}`, {
  1915. method: 'PUT',
  1916. body: JSON.stringify(data),
  1917. }),
  1918. resetNotificationTemplate: (id: number) =>
  1919. request<NotificationTemplate>(`/notification-templates/${id}/reset`, {
  1920. method: 'POST',
  1921. }),
  1922. getTemplateVariables: () => request<EventVariablesResponse[]>('/notification-templates/variables'),
  1923. previewTemplate: (data: TemplatePreviewRequest) =>
  1924. request<TemplatePreviewResponse>('/notification-templates/preview', {
  1925. method: 'POST',
  1926. body: JSON.stringify(data),
  1927. }),
  1928. // Notification Logs
  1929. getNotificationLogs: (params?: {
  1930. limit?: number;
  1931. offset?: number;
  1932. provider_id?: number;
  1933. event_type?: string;
  1934. success?: boolean;
  1935. days?: number;
  1936. }) => {
  1937. const searchParams = new URLSearchParams();
  1938. if (params?.limit) searchParams.set('limit', String(params.limit));
  1939. if (params?.offset) searchParams.set('offset', String(params.offset));
  1940. if (params?.provider_id) searchParams.set('provider_id', String(params.provider_id));
  1941. if (params?.event_type) searchParams.set('event_type', params.event_type);
  1942. if (params?.success !== undefined) searchParams.set('success', String(params.success));
  1943. if (params?.days) searchParams.set('days', String(params.days));
  1944. return request<NotificationLogEntry[]>(`/notifications/logs?${searchParams}`);
  1945. },
  1946. getNotificationLogStats: (days = 7) =>
  1947. request<NotificationLogStats>(`/notifications/logs/stats?days=${days}`),
  1948. clearNotificationLogs: (olderThanDays = 30) =>
  1949. request<{ deleted: number; message: string }>(
  1950. `/notifications/logs?older_than_days=${olderThanDays}`,
  1951. { method: 'DELETE' }
  1952. ),
  1953. // Spoolman Integration
  1954. getSpoolmanStatus: () => request<SpoolmanStatus>('/spoolman/status'),
  1955. connectSpoolman: () =>
  1956. request<{ success: boolean; message: string }>('/spoolman/connect', {
  1957. method: 'POST',
  1958. }),
  1959. disconnectSpoolman: () =>
  1960. request<{ success: boolean; message: string }>('/spoolman/disconnect', {
  1961. method: 'POST',
  1962. }),
  1963. syncPrinterAms: (printerId: number) =>
  1964. request<SpoolmanSyncResult>(`/spoolman/sync/${printerId}`, {
  1965. method: 'POST',
  1966. }),
  1967. syncAllPrintersAms: () =>
  1968. request<SpoolmanSyncResult>('/spoolman/sync-all', {
  1969. method: 'POST',
  1970. }),
  1971. getSpoolmanSpools: () =>
  1972. request<{ spools: unknown[] }>('/spoolman/spools'),
  1973. getSpoolmanFilaments: () =>
  1974. request<{ filaments: unknown[] }>('/spoolman/filaments'),
  1975. getUnlinkedSpools: () =>
  1976. request<UnlinkedSpool[]>('/spoolman/spools/unlinked'),
  1977. linkSpool: (spoolId: number, trayUuid: string) =>
  1978. request<{ success: boolean; message: string }>(`/spoolman/spools/${spoolId}/link`, {
  1979. method: 'POST',
  1980. body: JSON.stringify({ tray_uuid: trayUuid }),
  1981. }),
  1982. // Updates
  1983. getVersion: () => request<VersionInfo>('/updates/version'),
  1984. checkForUpdates: () => request<UpdateCheckResult>('/updates/check'),
  1985. applyUpdate: () =>
  1986. request<{ success: boolean; message: string; status?: UpdateStatus; is_docker?: boolean }>('/updates/apply', {
  1987. method: 'POST',
  1988. }),
  1989. getUpdateStatus: () => request<UpdateStatus>('/updates/status'),
  1990. // Maintenance
  1991. getMaintenanceTypes: () => request<MaintenanceType[]>('/maintenance/types'),
  1992. createMaintenanceType: (data: MaintenanceTypeCreate) =>
  1993. request<MaintenanceType>('/maintenance/types', {
  1994. method: 'POST',
  1995. body: JSON.stringify(data),
  1996. }),
  1997. updateMaintenanceType: (id: number, data: Partial<MaintenanceTypeCreate>) =>
  1998. request<MaintenanceType>(`/maintenance/types/${id}`, {
  1999. method: 'PATCH',
  2000. body: JSON.stringify(data),
  2001. }),
  2002. deleteMaintenanceType: (id: number) =>
  2003. request<{ status: string }>(`/maintenance/types/${id}`, { method: 'DELETE' }),
  2004. getMaintenanceOverview: () => request<PrinterMaintenanceOverview[]>('/maintenance/overview'),
  2005. getPrinterMaintenance: (printerId: number) =>
  2006. request<PrinterMaintenanceOverview>(`/maintenance/printers/${printerId}`),
  2007. updateMaintenanceItem: (itemId: number, data: { custom_interval_hours?: number | null; custom_interval_type?: 'hours' | 'days' | null; enabled?: boolean }) =>
  2008. request<MaintenanceStatus>(`/maintenance/items/${itemId}`, {
  2009. method: 'PATCH',
  2010. body: JSON.stringify(data),
  2011. }),
  2012. performMaintenance: (itemId: number, notes?: string) =>
  2013. request<MaintenanceStatus>(`/maintenance/items/${itemId}/perform`, {
  2014. method: 'POST',
  2015. body: JSON.stringify({ notes }),
  2016. }),
  2017. getMaintenanceHistory: (itemId: number) =>
  2018. request<MaintenanceHistory[]>(`/maintenance/items/${itemId}/history`),
  2019. getMaintenanceSummary: () => request<MaintenanceSummary>('/maintenance/summary'),
  2020. setPrinterHours: (printerId: number, totalHours: number) =>
  2021. request<{ printer_id: number; total_hours: number; archive_hours: number; offset_hours: number }>(
  2022. `/maintenance/printers/${printerId}/hours?total_hours=${totalHours}`,
  2023. { method: 'PATCH' }
  2024. ),
  2025. assignMaintenanceType: (printerId: number, typeId: number) =>
  2026. request<MaintenanceStatus>(`/maintenance/printers/${printerId}/assign/${typeId}`, {
  2027. method: 'POST',
  2028. }),
  2029. removeMaintenanceItem: (itemId: number) =>
  2030. request<{ status: string }>(`/maintenance/items/${itemId}`, {
  2031. method: 'DELETE',
  2032. }),
  2033. // Camera
  2034. getCameraStreamUrl: (printerId: number, fps = 10) =>
  2035. `${API_BASE}/printers/${printerId}/camera/stream?fps=${fps}`,
  2036. getCameraSnapshotUrl: (printerId: number) =>
  2037. `${API_BASE}/printers/${printerId}/camera/snapshot`,
  2038. testCameraConnection: (printerId: number) =>
  2039. request<{ success: boolean; message?: string; error?: string }>(`/printers/${printerId}/camera/test`),
  2040. // External Links
  2041. getExternalLinks: () => request<ExternalLink[]>('/external-links/'),
  2042. getExternalLink: (id: number) => request<ExternalLink>(`/external-links/${id}`),
  2043. createExternalLink: (data: ExternalLinkCreate) =>
  2044. request<ExternalLink>('/external-links/', {
  2045. method: 'POST',
  2046. body: JSON.stringify(data),
  2047. }),
  2048. updateExternalLink: (id: number, data: ExternalLinkUpdate) =>
  2049. request<ExternalLink>(`/external-links/${id}`, {
  2050. method: 'PATCH',
  2051. body: JSON.stringify(data),
  2052. }),
  2053. deleteExternalLink: (id: number) =>
  2054. request<{ message: string }>(`/external-links/${id}`, { method: 'DELETE' }),
  2055. reorderExternalLinks: (ids: number[]) =>
  2056. request<ExternalLink[]>('/external-links/reorder', {
  2057. method: 'PUT',
  2058. body: JSON.stringify({ ids }),
  2059. }),
  2060. uploadExternalLinkIcon: async (id: number, file: File): Promise<ExternalLink> => {
  2061. const formData = new FormData();
  2062. formData.append('file', file);
  2063. const response = await fetch(`${API_BASE}/external-links/${id}/icon`, {
  2064. method: 'POST',
  2065. body: formData,
  2066. });
  2067. if (!response.ok) {
  2068. const error = await response.json().catch(() => ({}));
  2069. throw new Error(error.detail || `HTTP ${response.status}`);
  2070. }
  2071. return response.json();
  2072. },
  2073. deleteExternalLinkIcon: (id: number) =>
  2074. request<ExternalLink>(`/external-links/${id}/icon`, { method: 'DELETE' }),
  2075. getExternalLinkIconUrl: (id: number) => `${API_BASE}/external-links/${id}/icon`,
  2076. // Projects
  2077. getProjects: (status?: string) => {
  2078. const params = new URLSearchParams();
  2079. if (status) params.set('status', status);
  2080. return request<ProjectListItem[]>(`/projects/?${params}`);
  2081. },
  2082. getProject: (id: number) => request<Project>(`/projects/${id}`),
  2083. createProject: (data: ProjectCreate) =>
  2084. request<Project>('/projects/', {
  2085. method: 'POST',
  2086. body: JSON.stringify(data),
  2087. }),
  2088. updateProject: (id: number, data: ProjectUpdate) =>
  2089. request<Project>(`/projects/${id}`, {
  2090. method: 'PATCH',
  2091. body: JSON.stringify(data),
  2092. }),
  2093. deleteProject: (id: number) =>
  2094. request<{ message: string }>(`/projects/${id}`, { method: 'DELETE' }),
  2095. getProjectArchives: (id: number, limit = 100, offset = 0) =>
  2096. request<Archive[]>(`/projects/${id}/archives?limit=${limit}&offset=${offset}`),
  2097. addArchivesToProject: (projectId: number, archiveIds: number[]) =>
  2098. request<{ message: string }>(`/projects/${projectId}/add-archives`, {
  2099. method: 'POST',
  2100. body: JSON.stringify({ archive_ids: archiveIds }),
  2101. }),
  2102. removeArchivesFromProject: (projectId: number, archiveIds: number[]) =>
  2103. request<{ message: string }>(`/projects/${projectId}/remove-archives`, {
  2104. method: 'POST',
  2105. body: JSON.stringify({ archive_ids: archiveIds }),
  2106. }),
  2107. addQueueItemsToProject: (projectId: number, queueItemIds: number[]) =>
  2108. request<{ message: string }>(`/projects/${projectId}/add-queue`, {
  2109. method: 'POST',
  2110. body: JSON.stringify({ queue_item_ids: queueItemIds }),
  2111. }),
  2112. // Project Attachments
  2113. uploadProjectAttachment: async (projectId: number, file: File): Promise<{
  2114. status: string;
  2115. filename: string;
  2116. original_name: string;
  2117. attachments: ProjectAttachment[];
  2118. }> => {
  2119. const formData = new FormData();
  2120. formData.append('file', file);
  2121. const response = await fetch(`${API_BASE}/projects/${projectId}/attachments`, {
  2122. method: 'POST',
  2123. body: formData,
  2124. });
  2125. if (!response.ok) {
  2126. const error = await response.json().catch(() => ({}));
  2127. throw new Error(error.detail || `HTTP ${response.status}`);
  2128. }
  2129. return response.json();
  2130. },
  2131. getProjectAttachmentUrl: (projectId: number, filename: string) =>
  2132. `${API_BASE}/projects/${projectId}/attachments/${encodeURIComponent(filename)}`,
  2133. deleteProjectAttachment: (projectId: number, filename: string) =>
  2134. request<{ status: string; message: string; attachments: ProjectAttachment[] | null }>(
  2135. `/projects/${projectId}/attachments/${encodeURIComponent(filename)}`,
  2136. { method: 'DELETE' }
  2137. ),
  2138. // BOM (Bill of Materials)
  2139. getProjectBOM: (projectId: number) =>
  2140. request<BOMItem[]>(`/projects/${projectId}/bom`),
  2141. createBOMItem: (projectId: number, data: BOMItemCreate) =>
  2142. request<BOMItem>(`/projects/${projectId}/bom`, {
  2143. method: 'POST',
  2144. body: JSON.stringify(data),
  2145. }),
  2146. updateBOMItem: (projectId: number, itemId: number, data: BOMItemUpdate) =>
  2147. request<BOMItem>(`/projects/${projectId}/bom/${itemId}`, {
  2148. method: 'PATCH',
  2149. body: JSON.stringify(data),
  2150. }),
  2151. deleteBOMItem: (projectId: number, itemId: number) =>
  2152. request<{ status: string; message: string }>(`/projects/${projectId}/bom/${itemId}`, {
  2153. method: 'DELETE',
  2154. }),
  2155. // Templates
  2156. getTemplates: () => request<ProjectListItem[]>('/projects/templates/'),
  2157. createTemplateFromProject: (projectId: number) =>
  2158. request<Project>(`/projects/${projectId}/create-template`, { method: 'POST' }),
  2159. createProjectFromTemplate: (templateId: number, name?: string) =>
  2160. request<Project>(`/projects/from-template/${templateId}${name ? `?name=${encodeURIComponent(name)}` : ''}`, {
  2161. method: 'POST',
  2162. }),
  2163. // Timeline
  2164. getProjectTimeline: (projectId: number, limit = 50) =>
  2165. request<TimelineEvent[]>(`/projects/${projectId}/timeline?limit=${limit}`),
  2166. // API Keys
  2167. getAPIKeys: () => request<APIKey[]>('/api-keys/'),
  2168. createAPIKey: (data: APIKeyCreate) =>
  2169. request<APIKeyCreateResponse>('/api-keys/', {
  2170. method: 'POST',
  2171. body: JSON.stringify(data),
  2172. }),
  2173. updateAPIKey: (id: number, data: APIKeyUpdate) =>
  2174. request<APIKey>(`/api-keys/${id}`, {
  2175. method: 'PATCH',
  2176. body: JSON.stringify(data),
  2177. }),
  2178. deleteAPIKey: (id: number) =>
  2179. request<{ message: string }>(`/api-keys/${id}`, { method: 'DELETE' }),
  2180. // AMS History
  2181. getAMSHistory: (printerId: number, amsId: number, hours = 24) =>
  2182. request<AMSHistoryResponse>(`/ams-history/${printerId}/${amsId}?hours=${hours}`),
  2183. // System Info
  2184. getSystemInfo: () => request<SystemInfo>('/system/info'),
  2185. };
  2186. // AMS History types
  2187. export interface AMSHistoryPoint {
  2188. recorded_at: string;
  2189. humidity: number | null;
  2190. humidity_raw: number | null;
  2191. temperature: number | null;
  2192. }
  2193. export interface AMSHistoryResponse {
  2194. printer_id: number;
  2195. ams_id: number;
  2196. data: AMSHistoryPoint[];
  2197. min_humidity: number | null;
  2198. max_humidity: number | null;
  2199. avg_humidity: number | null;
  2200. min_temperature: number | null;
  2201. max_temperature: number | null;
  2202. avg_temperature: number | null;
  2203. }
  2204. // System Info types
  2205. export interface SystemInfo {
  2206. app: {
  2207. version: string;
  2208. base_dir: string;
  2209. archive_dir: string;
  2210. };
  2211. database: {
  2212. archives: number;
  2213. archives_completed: number;
  2214. archives_failed: number;
  2215. archives_printing: number;
  2216. printers: number;
  2217. filaments: number;
  2218. projects: number;
  2219. smart_plugs: number;
  2220. total_print_time_seconds: number;
  2221. total_print_time_formatted: string;
  2222. total_filament_grams: number;
  2223. total_filament_kg: number;
  2224. };
  2225. printers: {
  2226. total: number;
  2227. connected: number;
  2228. connected_list: Array<{
  2229. id: number;
  2230. name: string;
  2231. state: string;
  2232. model: string;
  2233. }>;
  2234. };
  2235. storage: {
  2236. archive_size_bytes: number;
  2237. archive_size_formatted: string;
  2238. database_size_bytes: number;
  2239. database_size_formatted: string;
  2240. disk_total_bytes: number;
  2241. disk_total_formatted: string;
  2242. disk_used_bytes: number;
  2243. disk_used_formatted: string;
  2244. disk_free_bytes: number;
  2245. disk_free_formatted: string;
  2246. disk_percent_used: number;
  2247. };
  2248. system: {
  2249. platform: string;
  2250. platform_release: string;
  2251. platform_version: string;
  2252. architecture: string;
  2253. hostname: string;
  2254. python_version: string;
  2255. uptime_seconds: number;
  2256. uptime_formatted: string;
  2257. boot_time: string;
  2258. };
  2259. memory: {
  2260. total_bytes: number;
  2261. total_formatted: string;
  2262. available_bytes: number;
  2263. available_formatted: string;
  2264. used_bytes: number;
  2265. used_formatted: string;
  2266. percent_used: number;
  2267. };
  2268. cpu: {
  2269. count: number;
  2270. count_logical: number;
  2271. percent: number;
  2272. };
  2273. }
  2274. // Discovery types
  2275. export interface DiscoveredPrinter {
  2276. serial: string;
  2277. name: string;
  2278. ip_address: string;
  2279. model: string | null;
  2280. discovered_at: string | null;
  2281. }
  2282. export interface DiscoveryStatus {
  2283. running: boolean;
  2284. }
  2285. export interface DiscoveryInfo {
  2286. is_docker: boolean;
  2287. ssdp_running: boolean;
  2288. scan_running: boolean;
  2289. }
  2290. export interface SubnetScanStatus {
  2291. running: boolean;
  2292. scanned: number;
  2293. total: number;
  2294. }
  2295. // Discovery API
  2296. export const discoveryApi = {
  2297. getInfo: () => request<DiscoveryInfo>('/discovery/info'),
  2298. getStatus: () => request<DiscoveryStatus>('/discovery/status'),
  2299. startDiscovery: (duration: number = 10) =>
  2300. request<DiscoveryStatus>(`/discovery/start?duration=${duration}`, { method: 'POST' }),
  2301. stopDiscovery: () =>
  2302. request<DiscoveryStatus>('/discovery/stop', { method: 'POST' }),
  2303. getDiscoveredPrinters: () =>
  2304. request<DiscoveredPrinter[]>('/discovery/printers'),
  2305. // Subnet scanning (for Docker environments)
  2306. startSubnetScan: (subnet: string, timeout: number = 1.0) =>
  2307. request<SubnetScanStatus>('/discovery/scan', {
  2308. method: 'POST',
  2309. body: JSON.stringify({ subnet, timeout }),
  2310. }),
  2311. getScanStatus: () => request<SubnetScanStatus>('/discovery/scan/status'),
  2312. stopSubnetScan: () =>
  2313. request<SubnetScanStatus>('/discovery/scan/stop', { method: 'POST' }),
  2314. };
  2315. // Virtual Printer types
  2316. export interface VirtualPrinterStatus {
  2317. enabled: boolean;
  2318. running: boolean;
  2319. mode: 'immediate' | 'queue';
  2320. name: string;
  2321. serial: string;
  2322. model: string;
  2323. model_name: string;
  2324. pending_files: number;
  2325. }
  2326. export interface VirtualPrinterSettings {
  2327. enabled: boolean;
  2328. access_code_set: boolean;
  2329. mode: 'immediate' | 'queue';
  2330. model: string;
  2331. status: VirtualPrinterStatus;
  2332. }
  2333. export interface VirtualPrinterModels {
  2334. models: Record<string, string>; // SSDP code -> display name
  2335. default: string;
  2336. }
  2337. export interface PendingUpload {
  2338. id: number;
  2339. filename: string;
  2340. file_size: number;
  2341. source_ip: string | null;
  2342. status: string;
  2343. tags: string | null;
  2344. notes: string | null;
  2345. project_id: number | null;
  2346. uploaded_at: string;
  2347. }
  2348. // Virtual Printer API
  2349. export const virtualPrinterApi = {
  2350. getSettings: () => request<VirtualPrinterSettings>('/settings/virtual-printer'),
  2351. getModels: () => request<VirtualPrinterModels>('/settings/virtual-printer/models'),
  2352. updateSettings: (data: {
  2353. enabled?: boolean;
  2354. access_code?: string;
  2355. mode?: 'immediate' | 'queue';
  2356. model?: string;
  2357. }) => {
  2358. const params = new URLSearchParams();
  2359. if (data.enabled !== undefined) params.set('enabled', String(data.enabled));
  2360. if (data.access_code !== undefined) params.set('access_code', data.access_code);
  2361. if (data.mode !== undefined) params.set('mode', data.mode);
  2362. if (data.model !== undefined) params.set('model', data.model);
  2363. return request<VirtualPrinterSettings>(`/settings/virtual-printer?${params.toString()}`, {
  2364. method: 'PUT',
  2365. });
  2366. },
  2367. };
  2368. // Pending Uploads API
  2369. export const pendingUploadsApi = {
  2370. list: () => request<PendingUpload[]>('/pending-uploads/'),
  2371. getCount: () => request<{ count: number }>('/pending-uploads/count'),
  2372. get: (id: number) => request<PendingUpload>(`/pending-uploads/${id}`),
  2373. archive: (id: number, data?: { tags?: string; notes?: string; project_id?: number }) =>
  2374. request<{ id: number; print_name: string; filename: string }>(`/pending-uploads/${id}/archive`, {
  2375. method: 'POST',
  2376. body: JSON.stringify(data || {}),
  2377. }),
  2378. discard: (id: number) =>
  2379. request<{ success: boolean }>(`/pending-uploads/${id}`, { method: 'DELETE' }),
  2380. archiveAll: () =>
  2381. request<{ archived: number; failed: number }>('/pending-uploads/archive-all', { method: 'POST' }),
  2382. discardAll: () =>
  2383. request<{ discarded: number }>('/pending-uploads/discard-all', { method: 'DELETE' }),
  2384. };
  2385. // Firmware API Types
  2386. export interface FirmwareUpdateInfo {
  2387. printer_id: number;
  2388. printer_name: string;
  2389. model: string | null;
  2390. current_version: string | null;
  2391. latest_version: string | null;
  2392. update_available: boolean;
  2393. download_url: string | null;
  2394. release_notes: string | null;
  2395. }
  2396. export interface FirmwareUploadPrepare {
  2397. can_proceed: boolean;
  2398. sd_card_present: boolean;
  2399. sd_card_free_space: number;
  2400. firmware_size: number;
  2401. space_sufficient: boolean;
  2402. update_available: boolean;
  2403. current_version: string | null;
  2404. latest_version: string | null;
  2405. firmware_filename: string | null;
  2406. errors: string[];
  2407. }
  2408. export interface FirmwareUploadStatus {
  2409. status: 'idle' | 'preparing' | 'downloading' | 'uploading' | 'complete' | 'error';
  2410. progress: number;
  2411. message: string;
  2412. error: string | null;
  2413. firmware_filename: string | null;
  2414. firmware_version: string | null;
  2415. }
  2416. // Firmware API
  2417. export const firmwareApi = {
  2418. checkUpdates: () =>
  2419. request<{ updates: FirmwareUpdateInfo[]; updates_available: number }>('/firmware/updates'),
  2420. checkPrinterUpdate: (printerId: number) =>
  2421. request<FirmwareUpdateInfo>(`/firmware/updates/${printerId}`),
  2422. prepareUpload: (printerId: number) =>
  2423. request<FirmwareUploadPrepare>(`/firmware/updates/${printerId}/prepare`),
  2424. startUpload: (printerId: number) =>
  2425. request<{ started: boolean; message: string }>(`/firmware/updates/${printerId}/upload`, {
  2426. method: 'POST',
  2427. }),
  2428. getUploadStatus: (printerId: number) =>
  2429. request<FirmwareUploadStatus>(`/firmware/updates/${printerId}/upload/status`),
  2430. };
  2431. // Support types
  2432. export interface DebugLoggingState {
  2433. enabled: boolean;
  2434. enabled_at: string | null;
  2435. duration_seconds: number | null;
  2436. }
  2437. // Support API
  2438. export const supportApi = {
  2439. getDebugLoggingState: () =>
  2440. request<DebugLoggingState>('/support/debug-logging'),
  2441. setDebugLogging: (enabled: boolean) =>
  2442. request<DebugLoggingState>('/support/debug-logging', {
  2443. method: 'POST',
  2444. body: JSON.stringify({ enabled }),
  2445. }),
  2446. downloadSupportBundle: async () => {
  2447. const response = await fetch(`${API_BASE}/support/bundle`);
  2448. if (!response.ok) {
  2449. const error = await response.json().catch(() => ({}));
  2450. throw new Error(error.detail || `HTTP ${response.status}`);
  2451. }
  2452. // Get filename from Content-Disposition header or use default
  2453. const disposition = response.headers.get('Content-Disposition');
  2454. const filenameMatch = disposition?.match(/filename=(.+)/);
  2455. const filename = filenameMatch ? filenameMatch[1] : 'bambuddy-support.zip';
  2456. // Download the blob
  2457. const blob = await response.blob();
  2458. const url = window.URL.createObjectURL(blob);
  2459. const a = document.createElement('a');
  2460. a.href = url;
  2461. a.download = filename;
  2462. document.body.appendChild(a);
  2463. a.click();
  2464. document.body.removeChild(a);
  2465. window.URL.revokeObjectURL(url);
  2466. },
  2467. };