This repository was archived by the owner on Apr 16, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathweb.go
More file actions
1736 lines (1497 loc) · 51.3 KB
/
Copy pathweb.go
File metadata and controls
1736 lines (1497 loc) · 51.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"embed"
"encoding/base64"
"encoding/json"
"fmt"
"html/template"
"io/fs"
"log"
"net/http"
neturl "net/url"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
"github.com/skip2/go-qrcode"
)
//go:embed templates/*
var templatesFS embed.FS
//go:embed static/**
var staticFS embed.FS
// WebServer handles HTTP requests using Gin
type WebServer struct {
bridge *FilamentBridge
router *gin.Engine
operationMutex sync.Mutex // Protects add/update/delete printer operations
wsHub *WebSocketHub
}
// WebSocketHub manages WebSocket connections and broadcasts
type WebSocketHub struct {
clients map[*WebSocketClient]bool
register chan *WebSocketClient
unregister chan *WebSocketClient
broadcast chan []byte
mutex sync.RWMutex
}
// WebSocketClient represents a WebSocket connection
type WebSocketClient struct {
hub *WebSocketHub
conn *websocket.Conn
send chan []byte
}
// WebSocketMessage represents the structure of messages sent to clients
type WebSocketMessage struct {
Type string `json:"type"`
Timestamp time.Time `json:"timestamp"`
Printers map[string]PrinterData `json:"printers"`
Spools []SpoolmanSpool `json:"spools"`
ToolheadMappings map[string]map[int]ToolheadMapping `json:"toolhead_mappings"`
PrintErrors []PrintError `json:"print_errors,omitempty"`
}
// NewWebServer creates a new web server with Gin
func NewWebServer(bridge *FilamentBridge) *WebServer {
gin.SetMode(gin.ReleaseMode)
router := gin.New()
// Add middleware
router.Use(gin.Logger())
router.Use(gin.Recovery())
// Add custom recovery middleware for API routes to ensure JSON responses
router.Use(func(c *gin.Context) {
defer func() {
if err := recover(); err != nil {
// Check if this is an API route
if strings.HasPrefix(c.Request.URL.Path, "/api/") {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Internal server error"})
c.Abort()
} else {
// For non-API routes, use default recovery behavior
c.AbortWithStatus(http.StatusInternalServerError)
}
}
}()
c.Next()
})
// Create WebSocket hub
wsHub := &WebSocketHub{
clients: make(map[*WebSocketClient]bool),
register: make(chan *WebSocketClient),
unregister: make(chan *WebSocketClient),
broadcast: make(chan []byte),
}
ws := &WebServer{
bridge: bridge,
router: router,
wsHub: wsHub,
}
// Start WebSocket hub
go wsHub.run()
ws.setupRoutes()
return ws
}
// generateToolheadIDs generates a slice of toolhead IDs from 0 to count-1
func generateToolheadIDs(count int) []int {
ids := make([]int, count)
for i := 0; i < count; i++ {
ids[i] = i
}
return ids
}
// setupRoutes configures all the routes
func (ws *WebServer) setupRoutes() {
// Load HTML templates with custom functions from embedded filesystem
tmpl := template.Must(template.New("").Funcs(template.FuncMap{
"generateToolheadIDs": generateToolheadIDs,
}).ParseFS(templatesFS, "templates/*"))
ws.router.SetHTMLTemplate(tmpl)
// Static files (embedded in binary)
// Use fs.Sub to strip the "static/" prefix from embedded paths
staticSubFS, err := fs.Sub(staticFS, "static")
if err != nil {
log.Fatalf("Failed to create static filesystem: %v", err)
}
ws.router.StaticFS("/static", http.FS(staticSubFS))
// Main dashboard
ws.router.GET("/", ws.dashboardHandler)
// API routes
api := ws.router.Group("/api")
{
api.GET("/status", ws.statusHandler)
api.GET("/spools", ws.spoolsHandler)
api.GET("/filaments", ws.filamentsHandler)
api.POST("/map_toolhead", ws.mapToolheadHandler)
api.GET("/available_spools", ws.availableSpoolsHandler)
api.GET("/spoolman/test", ws.testSpoolmanConnectionHandler)
api.GET("/spoolman/debug", ws.debugSpoolmanHandler)
api.POST("/test/print_complete", ws.testPrintCompleteHandler)
api.GET("/config", ws.getConfigHandler)
api.POST("/config", ws.updateConfigHandler)
api.GET("/config/auto-assign-previous-spool", ws.getAutoAssignPreviousSpoolHandler)
api.PUT("/config/auto-assign-previous-spool", ws.updateAutoAssignPreviousSpoolHandler)
api.GET("/printers", ws.getPrintersHandler)
api.POST("/printers", ws.addPrinterHandler)
api.PUT("/printers/:id", ws.updatePrinterHandler)
api.DELETE("/printers/:id", ws.deletePrinterHandler)
api.GET("/printers/:id/toolheads", ws.getToolheadNamesHandler)
api.PUT("/printers/:id/toolheads/:toolhead_id", ws.updateToolheadNameHandler)
api.POST("/detect_printer", ws.detectPrinterHandler)
api.GET("/print-errors", ws.getPrintErrorsHandler)
api.POST("/print-errors/:id/acknowledge", ws.acknowledgePrintErrorHandler)
api.GET("/nfc/assign", ws.nfcAssignHandler)
api.GET("/nfc/urls", ws.nfcUrlsHandler)
api.GET("/nfc/session/status", ws.nfcSessionStatusHandler)
api.GET("/locations", ws.getLocationsHandler)
api.GET("/locations/:name/status", ws.getLocationStatusHandler)
api.POST("/locations", ws.createLocationHandler)
api.PUT("/locations/:name", ws.updateLocationHandler)
api.DELETE("/locations/:name", ws.deleteLocationHandler)
}
// WebSocket endpoint
ws.router.GET("/ws/status", ws.websocketHandler)
}
// WebSocket hub methods
// run starts the WebSocket hub
func (h *WebSocketHub) run() {
for {
select {
case client := <-h.register:
h.mutex.Lock()
h.clients[client] = true
h.mutex.Unlock()
log.Printf("WebSocket client connected. Total clients: %d", len(h.clients))
case client := <-h.unregister:
h.mutex.Lock()
if _, ok := h.clients[client]; ok {
delete(h.clients, client)
close(client.send)
}
h.mutex.Unlock()
log.Printf("WebSocket client disconnected. Total clients: %d", len(h.clients))
case message := <-h.broadcast:
h.mutex.RLock()
for client := range h.clients {
select {
case client.send <- message:
default:
close(client.send)
delete(h.clients, client)
}
}
h.mutex.RUnlock()
}
}
}
// BroadcastStatus sends status updates to all connected clients
func (ws *WebServer) BroadcastStatus() {
// Get current status
status, err := ws.bridge.GetStatus()
if err != nil {
log.Printf("Error getting status for broadcast: %v", err)
return
}
// Get current spools
spools, err := ws.bridge.spoolman.GetAllSpools()
if err != nil {
log.Printf("Error getting spools for broadcast: %v", err)
spools = []SpoolmanSpool{}
}
// Get print errors
printErrors := ws.bridge.GetPrintErrors()
// Create message
message := WebSocketMessage{
Type: "status_update",
Timestamp: time.Now(),
Printers: status.Printers,
Spools: spools,
ToolheadMappings: status.ToolheadMappings,
PrintErrors: printErrors,
}
// Marshal to JSON
jsonData, err := json.Marshal(message)
if err != nil {
log.Printf("Error marshaling WebSocket message: %v", err)
return
}
// Broadcast to all clients
select {
case ws.wsHub.broadcast <- jsonData:
log.Printf("Broadcasted status update to %d clients", len(ws.wsHub.clients))
default:
log.Printf("No clients connected to receive broadcast")
}
}
// websocketHandler handles WebSocket connections
func (ws *WebServer) websocketHandler(c *gin.Context) {
upgrader := websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true // Allow connections from any origin
},
}
conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
if err != nil {
log.Printf("WebSocket upgrade error: %v", err)
return
}
client := &WebSocketClient{
hub: ws.wsHub,
conn: conn,
send: make(chan []byte, 256),
}
client.hub.register <- client
// Start goroutines for reading and writing
go client.writePump()
go client.readPump()
}
// WebSocket client methods
// readPump pumps messages from the WebSocket connection to the hub
func (c *WebSocketClient) readPump() {
defer func() {
c.hub.unregister <- c
c.conn.Close()
}()
c.conn.SetReadLimit(512)
c.conn.SetReadDeadline(time.Now().Add(60 * time.Second))
c.conn.SetPongHandler(func(string) error {
c.conn.SetReadDeadline(time.Now().Add(60 * time.Second))
return nil
})
for {
_, _, err := c.conn.ReadMessage()
if err != nil {
if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
log.Printf("WebSocket error: %v", err)
}
break
}
}
}
// writePump pumps messages from the hub to the WebSocket connection
func (c *WebSocketClient) writePump() {
ticker := time.NewTicker(54 * time.Second)
defer func() {
ticker.Stop()
c.conn.Close()
}()
for {
select {
case message, ok := <-c.send:
c.conn.SetWriteDeadline(time.Now().Add(10 * time.Second))
if !ok {
c.conn.WriteMessage(websocket.CloseMessage, []byte{})
return
}
w, err := c.conn.NextWriter(websocket.TextMessage)
if err != nil {
return
}
w.Write(message)
// Add queued chat messages to the current websocket message
n := len(c.send)
for i := 0; i < n; i++ {
w.Write([]byte{'\n'})
w.Write(<-c.send)
}
if err := w.Close(); err != nil {
return
}
case <-ticker.C:
c.conn.SetWriteDeadline(time.Now().Add(10 * time.Second))
if err := c.conn.WriteMessage(websocket.PingMessage, nil); err != nil {
return
}
}
}
}
// dashboardHandler serves the main dashboard
func (ws *WebServer) dashboardHandler(c *gin.Context) {
status, err := ws.bridge.GetStatus()
if err != nil {
c.HTML(http.StatusInternalServerError, "error.html", gin.H{
"Error": "Failed to get printer status",
})
return
}
// Test Spoolman connection
spoolmanConnected := true
spoolmanError := ""
spools, err := ws.bridge.spoolman.GetAllSpools()
if err != nil {
spoolmanConnected = false
spoolmanError = err.Error()
spools = []SpoolmanSpool{}
}
// Check if this is a first run
isFirstRun, err := ws.bridge.IsFirstRun()
if err != nil {
isFirstRun = false
}
hasErrors := !spoolmanConnected || hasConnectionErrors(status)
// Get print errors
printErrors := ws.bridge.GetPrintErrors()
hasPrintErrors := len(printErrors) > 0
c.HTML(http.StatusOK, "index.html", gin.H{
"Status": status,
"Spools": spools,
"HasErrors": hasErrors,
"HasPrintErrors": hasPrintErrors,
"PrintErrors": printErrors,
"IsFirstRun": isFirstRun,
"Printers": ws.bridge.config.Printers,
"SpoolmanConnected": spoolmanConnected,
"SpoolmanError": spoolmanError,
"SpoolmanBaseURL": ws.bridge.config.SpoolmanURL,
})
}
// hasConnectionErrors checks if there are connection errors
func hasConnectionErrors(status *PrinterStatus) bool {
for _, printer := range status.Printers {
if printer.State == StateOffline {
return true
}
}
return false
}
// statusHandler returns current status as JSON
func (ws *WebServer) statusHandler(c *gin.Context) {
status, err := ws.bridge.GetStatus()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, status)
}
// spoolsHandler returns all spools as JSON
func (ws *WebServer) spoolsHandler(c *gin.Context) {
spools, err := ws.bridge.spoolman.GetAllSpools()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, spools)
}
// filamentsHandler returns all filament types as JSON
func (ws *WebServer) filamentsHandler(c *gin.Context) {
filaments, err := ws.bridge.spoolman.GetAllFilaments()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, filaments)
}
// validatePrinterConfig validates printer configuration input
func validatePrinterConfig(config PrinterConfig) error {
if config.Name == "" {
return fmt.Errorf("printer name is required")
}
if config.IPAddress == "" {
return fmt.Errorf("address is required")
}
if config.Toolheads < 1 {
return fmt.Errorf("toolheads must be at least 1")
}
if config.Toolheads > 10 {
return fmt.Errorf("toolheads cannot exceed 10")
}
return nil
}
// validateAddress validates hostname or IP address format
func validateAddress(address string) error {
if address == "" {
return fmt.Errorf("address cannot be empty")
}
// Basic validation - check for reasonable length (hostnames can be longer than IPs)
// Minimum: 1 character (e.g., "a"), Maximum: 253 characters (RFC 1035)
if len(address) < 1 || len(address) > 253 {
return fmt.Errorf("invalid address format")
}
// Basic character validation - allow common characters used in hostnames and IP addresses
// This includes: letters, numbers, dots, hyphens, underscores, colons (for IPv6), and brackets (for IPv6)
// The HTTP client will perform more thorough validation when connecting
for _, char := range address {
if !((char >= 'a' && char <= 'z') || (char >= 'A' && char <= 'Z') ||
(char >= '0' && char <= '9') || char == '.' || char == '-' || char == '_' ||
char == ':' || char == '[' || char == ']') {
return fmt.Errorf("invalid address format: contains invalid characters")
}
}
return nil
}
// mapToolheadHandler maps a spool to a toolhead
func (ws *WebServer) mapToolheadHandler(c *gin.Context) {
var req struct {
PrinterName string `json:"printer_name" binding:"required"`
ToolheadID int `json:"toolhead_id"`
SpoolID int `json:"spool_id"`
}
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid JSON"})
return
}
if req.PrinterName == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "Missing required parameters"})
return
}
if req.ToolheadID < 0 {
c.JSON(http.StatusBadRequest, gin.H{"error": "Toolhead ID must be non-negative"})
return
}
// Handle unmapping (SpoolID = 0) or mapping (SpoolID > 0)
if req.SpoolID == 0 {
// Unmap the toolhead
if err := ws.bridge.UnmapToolhead(req.PrinterName, req.ToolheadID); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"message": "Toolhead unmapped successfully"})
} else {
// Map the spool to the toolhead
if err := ws.bridge.SetToolheadMapping(req.PrinterName, req.ToolheadID, req.SpoolID); err != nil {
// Check if this is a spool conflict error
if strings.Contains(err.Error(), "is already assigned to") {
c.JSON(http.StatusConflict, gin.H{"error": err.Error()})
} else {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
}
return
}
c.JSON(http.StatusOK, gin.H{"message": "Toolhead mapped successfully"})
}
}
// availableSpoolsHandler returns spools available for assignment to a specific toolhead
func (ws *WebServer) availableSpoolsHandler(c *gin.Context) {
printerName := c.Query("printer_name")
toolheadIDStr := c.Query("toolhead_id")
if printerName == "" || toolheadIDStr == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "printer_name and toolhead_id parameters are required"})
return
}
toolheadID, err := strconv.Atoi(toolheadIDStr)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid toolhead_id"})
return
}
// Get all spools from Spoolman
allSpools, err := ws.bridge.spoolman.GetAllSpools()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
// Get all current toolhead mappings
allMappings, err := ws.bridge.GetAllToolheadMappings()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
// Create a set of assigned spool IDs (excluding the current toolhead)
assignedSpoolIDs := make(map[int]bool)
for _, printerMappings := range allMappings {
for tid, mapping := range printerMappings {
// Skip the current toolhead (allow re-assignment to the same toolhead)
if mapping.PrinterName == printerName && tid == toolheadID {
continue
}
// Mark this spool as assigned (prevents same spool being used on multiple printers)
assignedSpoolIDs[mapping.SpoolID] = true
}
}
// Filter out assigned spools
var availableSpools []SpoolmanSpool
for _, spool := range allSpools {
if !assignedSpoolIDs[spool.ID] {
availableSpools = append(availableSpools, spool)
}
}
c.JSON(http.StatusOK, gin.H{"spools": availableSpools})
}
// getConfigHandler returns current configuration
func (ws *WebServer) getConfigHandler(c *gin.Context) {
config, err := ws.bridge.GetAllConfig()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, config)
}
// updateConfigHandler updates configuration
func (ws *WebServer) updateConfigHandler(c *gin.Context) {
var config map[string]string
if err := c.ShouldBindJSON(&config); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid JSON"})
return
}
// Update each config value
for key, value := range config {
if err := ws.bridge.SetConfigValue(key, value); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
}
// Reload configuration
newConfig, err := LoadConfig(ws.bridge)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
if err := ws.bridge.UpdateConfig(newConfig); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"message": "Configuration updated successfully"})
}
// getAutoAssignPreviousSpoolHandler returns current auto-assign previous spool settings
func (ws *WebServer) getAutoAssignPreviousSpoolHandler(c *gin.Context) {
enabled, err := ws.bridge.GetAutoAssignPreviousSpoolEnabled()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
location, err := ws.bridge.GetAutoAssignPreviousSpoolLocation()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{
"enabled": enabled,
"location": location,
})
}
// updateAutoAssignPreviousSpoolHandler updates auto-assign previous spool settings
func (ws *WebServer) updateAutoAssignPreviousSpoolHandler(c *gin.Context) {
var req struct {
Enabled bool `json:"enabled" binding:"required"`
Location string `json:"location"`
}
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid JSON or missing 'enabled' field"})
return
}
// Update enabled setting
if err := ws.bridge.SetAutoAssignPreviousSpoolEnabled(req.Enabled); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
// Update location setting
if err := ws.bridge.SetAutoAssignPreviousSpoolLocation(req.Location); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"message": "Auto-assign previous spool settings updated successfully"})
}
// getPrintersHandler returns all configured printers
func (ws *WebServer) getPrintersHandler(c *gin.Context) {
printerConfigs, err := ws.bridge.GetAllPrinterConfigs()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
// Enhance printer configs with toolhead names
result := make(map[string]interface{})
for printerID, printerConfig := range printerConfigs {
printerData := map[string]interface{}{
"name": printerConfig.Name,
"model": printerConfig.Model,
"ip_address": printerConfig.IPAddress,
"api_key": printerConfig.APIKey,
"toolheads": printerConfig.Toolheads,
}
// Get toolhead names for this printer
toolheadNames, err := ws.bridge.GetAllToolheadNames(printerID)
if err == nil {
// Build toolhead names map with defaults
toolheadNamesMap := make(map[int]string)
for toolheadID := 0; toolheadID < printerConfig.Toolheads; toolheadID++ {
if name, exists := toolheadNames[toolheadID]; exists {
toolheadNamesMap[toolheadID] = name
} else {
toolheadNamesMap[toolheadID] = fmt.Sprintf("Toolhead %d", toolheadID)
}
}
printerData["toolhead_names"] = toolheadNamesMap
}
result[printerID] = printerData
}
c.JSON(http.StatusOK, gin.H{"printers": result})
}
// addPrinterHandler adds a new printer configuration
func (ws *WebServer) addPrinterHandler(c *gin.Context) {
// Serialize printer operations to prevent race conditions
ws.operationMutex.Lock()
defer ws.operationMutex.Unlock()
var printerConfig PrinterConfig
if err := c.ShouldBindJSON(&printerConfig); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
// Validate printer configuration
if err := validatePrinterConfig(printerConfig); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
// Validate address
if err := validateAddress(printerConfig.IPAddress); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
// Generate a unique printer ID using nanosecond timestamp + random component
printerID := fmt.Sprintf("printer_%d_%d", time.Now().UnixNano(), time.Now().Nanosecond()%1000)
// Save the printer configuration
if err := ws.bridge.SavePrinterConfig(printerID, printerConfig); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
// Reload configuration to include the new printer
if err := ws.reloadBridgeConfig(); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to reload configuration"})
return
}
c.JSON(http.StatusOK, gin.H{"message": "Printer added successfully", "printer_id": printerID})
}
// updatePrinterHandler updates an existing printer configuration
func (ws *WebServer) updatePrinterHandler(c *gin.Context) {
// Serialize printer operations to prevent race conditions
ws.operationMutex.Lock()
defer ws.operationMutex.Unlock()
printerID := c.Param("id")
var printerConfig PrinterConfig
if err := c.ShouldBindJSON(&printerConfig); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
// Validate printer configuration
if err := validatePrinterConfig(printerConfig); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
// Validate address
if err := validateAddress(printerConfig.IPAddress); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
// Auto-detect model if address or API key changed, or if model is currently "Unknown"
if printerConfig.Model == "" || printerConfig.Model == ModelUnknown {
log.Printf("🔍 [Auto-Detection] Detecting model for printer %s (IP: %s)", printerID, printerConfig.IPAddress)
// Create PrusaLink client for detection
client := NewPrusaLinkClient(printerConfig.IPAddress, printerConfig.APIKey, 10, 60) // Use default timeouts for detection
// Try to get printer info
printerInfo, err := client.GetPrinterInfo()
if err != nil {
log.Printf("⚠️ [Auto-Detection] Failed to detect model for %s: %v (keeping current model: %s)",
printerConfig.IPAddress, err, printerConfig.Model)
} else {
// Use shared model detection function
detectedModel := detectPrinterModel(printerInfo.Hostname)
if detectedModel != ModelUnknown {
log.Printf("✅ [Auto-Detection] Detected model for %s: '%s' -> %s",
printerConfig.IPAddress, printerInfo.Hostname, detectedModel)
printerConfig.Model = detectedModel
} else {
log.Printf("❌ [Auto-Detection] No pattern matched for hostname '%s' from %s",
printerInfo.Hostname, printerConfig.IPAddress)
}
}
}
// Save the updated printer configuration
if err := ws.bridge.SavePrinterConfig(printerID, printerConfig); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
// Reload configuration to include the updated printer
if err := ws.reloadBridgeConfig(); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to reload configuration"})
return
}
c.JSON(http.StatusOK, gin.H{"message": "Printer updated successfully"})
}
// deletePrinterHandler deletes a printer configuration
func (ws *WebServer) deletePrinterHandler(c *gin.Context) {
// Serialize printer operations to prevent race conditions
ws.operationMutex.Lock()
defer ws.operationMutex.Unlock()
printerID := c.Param("id")
// Delete the printer configuration
if err := ws.bridge.DeletePrinterConfig(printerID); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
// Reload configuration to remove the deleted printer
if err := ws.reloadBridgeConfig(); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to reload configuration"})
return
}
c.JSON(http.StatusOK, gin.H{"message": "Printer deleted successfully"})
}
// getToolheadNamesHandler returns all toolhead names for a printer
func (ws *WebServer) getToolheadNamesHandler(c *gin.Context) {
printerID := c.Param("id")
// Verify printer exists
printerConfigs, err := ws.bridge.GetAllPrinterConfigs()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
printerConfig, exists := printerConfigs[printerID]
if !exists {
c.JSON(http.StatusNotFound, gin.H{"error": "Printer not found"})
return
}
// Get all toolhead names
toolheadNames, err := ws.bridge.GetAllToolheadNames(printerID)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
// Build response with all toolheads (including defaults for unnamed ones)
result := make(map[int]string)
for toolheadID := 0; toolheadID < printerConfig.Toolheads; toolheadID++ {
if name, exists := toolheadNames[toolheadID]; exists {
result[toolheadID] = name
} else {
result[toolheadID] = fmt.Sprintf("Toolhead %d", toolheadID)
}
}
c.JSON(http.StatusOK, gin.H{"toolhead_names": result})
}
// updateToolheadNameHandler updates a toolhead's display name
func (ws *WebServer) updateToolheadNameHandler(c *gin.Context) {
printerID := c.Param("id")
toolheadIDStr := c.Param("toolhead_id")
// Parse toolhead ID
toolheadID, err := strconv.Atoi(toolheadIDStr)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid toolhead ID"})
return
}
// Verify printer exists
printerConfigs, err := ws.bridge.GetAllPrinterConfigs()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
printerConfig, exists := printerConfigs[printerID]
if !exists {
c.JSON(http.StatusNotFound, gin.H{"error": "Printer not found"})
return
}
// Validate toolhead ID is within range
if toolheadID < 0 || toolheadID >= printerConfig.Toolheads {
c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("Toolhead ID must be between 0 and %d", printerConfig.Toolheads-1)})
return
}
// Parse request body
var req struct {
Name string `json:"name" binding:"required"`
}
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid JSON or missing 'name' field"})
return
}
// Update toolhead name
if err := ws.bridge.SetToolheadName(printerID, toolheadID, req.Name); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"message": "Toolhead name updated successfully"})
}
// detectPrinterModel detects printer model from hostname
func detectPrinterModel(hostname string) string {
model := ModelUnknown
hostnameLower := strings.ToLower(hostname)
hostnameLower = strings.TrimSpace(hostnameLower) // Clean up any whitespace
log.Printf("🔍 [Detection] Checking hostname '%s' against patterns:", hostnameLower)
if strings.Contains(hostnameLower, ModelCorePattern) {
model = ModelCoreOne
log.Printf("✅ [Detection] Matched pattern '%s' -> %s", ModelCorePattern, model)
} else if strings.Contains(hostnameLower, ModelXLPattern) {
model = ModelXL
log.Printf("✅ [Detection] Matched pattern '%s' -> %s", ModelXLPattern, model)
} else if strings.Contains(hostnameLower, ModelMK4Pattern) {
model = ModelMK4
log.Printf("✅ [Detection] Matched pattern '%s' -> %s", ModelMK4Pattern, model)
} else if strings.Contains(hostnameLower, ModelMK3Pattern) {
model = ModelMK35
log.Printf("✅ [Detection] Matched pattern '%s' -> %s", ModelMK3Pattern, model)
} else if strings.Contains(hostnameLower, ModelMiniPattern) {
model = ModelMiniPlus
log.Printf("✅ [Detection] Matched pattern '%s' -> %s", ModelMiniPattern, model)
} else {
log.Printf("❌ [Detection] No pattern matched for hostname '%s'. Available patterns: %s, %s, %s, %s, %s",
hostnameLower, ModelCorePattern, ModelXLPattern, ModelMK4Pattern, ModelMK3Pattern, ModelMiniPattern)
}
log.Printf("🎯 [Detection] Final result: hostname='%s' -> model='%s'", hostname, model)
return model
}
// detectPrinterHandler detects printer model from PrusaLink API
func (ws *WebServer) detectPrinterHandler(c *gin.Context) {
var req struct {
IPAddress string `json:"ip_address" binding:"required"`
APIKey string `json:"api_key" binding:"required"`
}
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid JSON"})
return
}
// Validate address
if err := validateAddress(req.IPAddress); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
log.Printf("🔍 [Detection] Starting printer model detection for IP: %s", req.IPAddress)
// Create PrusaLink client
client := NewPrusaLinkClient(req.IPAddress, req.APIKey, 10, 60) // Use default timeouts for detection
// Try to get printer info, but don't fail if it times out
printerInfo, err := client.GetPrinterInfo()
if err != nil {
log.Printf("❌ [Detection] Failed to get printer info from %s: %v", req.IPAddress, err)
// If API call fails, return default values instead of error
// This allows users to add printers even if they're offline
c.JSON(http.StatusOK, gin.H{
"model": ModelUnknown,
"hostname": "Unknown",
"detected": false,
"warning": "Could not connect to printer. You can still add it manually.",
})
return
}
log.Printf("📥 [Detection] Received printer info: hostname='%s'", printerInfo.Hostname)
// Use shared model detection function