460 lines
14 KiB
Go
460 lines
14 KiB
Go
package main
|
|
|
|
import (
|
|
"encoding/json"
|
|
"flag"
|
|
"fmt"
|
|
"log"
|
|
"net/http"
|
|
"sync"
|
|
"time"
|
|
|
|
"github.com/gorilla/websocket"
|
|
)
|
|
|
|
func main() {
|
|
var listen string
|
|
flag.StringVar(&listen, "listen", ":7125", "address to listen on")
|
|
flag.Parse()
|
|
|
|
mux := http.NewServeMux()
|
|
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
|
|
if r.URL.Path != "/" {
|
|
http.NotFound(w, r)
|
|
return
|
|
}
|
|
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
|
_, _ = w.Write([]byte(`<!doctype html><html><head><title>Mock UI</title><link rel="stylesheet" href="/assets/app.css"></head><body><h1>Mock Printer UI</h1><script src="/assets/app.js"></script></body></html>`))
|
|
})
|
|
mux.HandleFunc("/assets/app.css", func(w http.ResponseWriter, r *http.Request) {
|
|
w.Header().Set("Content-Type", "text/css")
|
|
_, _ = w.Write([]byte(`body{font-family:sans-serif;background:#111619;color:#f7f3eb}`))
|
|
})
|
|
mux.HandleFunc("/assets/app.js", func(w http.ResponseWriter, r *http.Request) {
|
|
w.Header().Set("Content-Type", "application/javascript")
|
|
_, _ = w.Write([]byte(`fetch("/printer/info").then(r=>r.json()); const wsPath="/websocket"; console.log("mock ui", wsPath);`))
|
|
})
|
|
upgrader := websocket.Upgrader{CheckOrigin: func(r *http.Request) bool { return true }}
|
|
mux.HandleFunc("/websocket", func(w http.ResponseWriter, r *http.Request) {
|
|
conn, err := upgrader.Upgrade(w, r, nil)
|
|
if err != nil {
|
|
return
|
|
}
|
|
defer conn.Close()
|
|
var writeMu sync.Mutex
|
|
var updatesDone chan struct{}
|
|
defer func() {
|
|
if updatesDone != nil {
|
|
close(updatesDone)
|
|
}
|
|
}()
|
|
for {
|
|
messageType, payload, err := conn.ReadMessage()
|
|
if err != nil {
|
|
return
|
|
}
|
|
var request map[string]any
|
|
if err := json.Unmarshal(payload, &request); err != nil {
|
|
_ = conn.WriteMessage(messageType, payload)
|
|
continue
|
|
}
|
|
method, _ := request["method"].(string)
|
|
if method == "printer.objects.list" {
|
|
response := map[string]any{
|
|
"jsonrpc": "2.0",
|
|
"id": request["id"],
|
|
"result": map[string]any{
|
|
"objects": mockMoonrakerObjects(),
|
|
},
|
|
}
|
|
writeMu.Lock()
|
|
_ = conn.WriteJSON(response)
|
|
writeMu.Unlock()
|
|
continue
|
|
}
|
|
if method == "printer.objects.subscribe" {
|
|
requested := mockMoonrakerRequestedObjects(request)
|
|
response := map[string]any{
|
|
"jsonrpc": "2.0",
|
|
"id": request["id"],
|
|
"result": map[string]any{
|
|
"eventtime": time.Now().Unix(),
|
|
"status": mockMoonrakerStatus(requested, 0),
|
|
},
|
|
}
|
|
writeMu.Lock()
|
|
_ = conn.WriteJSON(response)
|
|
writeMu.Unlock()
|
|
if updatesDone == nil {
|
|
updatesDone = make(chan struct{})
|
|
go func() {
|
|
ticker := time.NewTicker(1 * time.Second)
|
|
defer ticker.Stop()
|
|
tick := 1
|
|
for {
|
|
select {
|
|
case <-ticker.C:
|
|
update := map[string]any{
|
|
"jsonrpc": "2.0",
|
|
"method": "notify_status_update",
|
|
"params": []any{
|
|
map[string]any{
|
|
"eventtime": time.Now().Unix(),
|
|
"status": mockMoonrakerStatus(requested, tick),
|
|
},
|
|
},
|
|
}
|
|
writeMu.Lock()
|
|
_ = conn.WriteJSON(update)
|
|
writeMu.Unlock()
|
|
tick++
|
|
case <-updatesDone:
|
|
return
|
|
}
|
|
}
|
|
}()
|
|
}
|
|
continue
|
|
}
|
|
response := map[string]any{
|
|
"jsonrpc": "2.0",
|
|
"result": map[string]any{"echo": method},
|
|
}
|
|
if id, ok := request["id"]; ok {
|
|
response["id"] = id
|
|
}
|
|
writeMu.Lock()
|
|
_ = conn.WriteJSON(response)
|
|
writeMu.Unlock()
|
|
}
|
|
})
|
|
mux.HandleFunc("/printer/info", func(w http.ResponseWriter, r *http.Request) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
_ = json.NewEncoder(w).Encode(map[string]any{
|
|
"result": map[string]any{
|
|
"hostname": "mock-printer",
|
|
"software_version": "mock",
|
|
"cpu_info": "local-development",
|
|
"klipper_path": "/home/pi/klipper",
|
|
"python_path": "/home/pi/klippy-env/bin/python",
|
|
"log_file": "/tmp/klippy.log",
|
|
"config_file": "/tmp/printer.cfg",
|
|
},
|
|
})
|
|
})
|
|
mux.HandleFunc("/server/info", func(w http.ResponseWriter, r *http.Request) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
_ = json.NewEncoder(w).Encode(map[string]any{
|
|
"result": map[string]any{
|
|
"klippy_connected": true,
|
|
"moonraker_version": "mock",
|
|
"time": time.Now().Unix(),
|
|
},
|
|
})
|
|
})
|
|
mux.HandleFunc("/server/webcams/list", func(w http.ResponseWriter, r *http.Request) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
_ = json.NewEncoder(w).Encode(map[string]any{
|
|
"result": map[string]any{
|
|
"webcams": []map[string]any{
|
|
{
|
|
"name": "moonraker-default",
|
|
"enabled": true,
|
|
"stream_url": "/webcam/?action=stream",
|
|
"snapshot_url": "/webcam/?action=snapshot",
|
|
"aspect_ratio": "16:9",
|
|
"rotation": 0,
|
|
"location": "printer",
|
|
"service": "mjpegstreamer",
|
|
"source": "database",
|
|
},
|
|
},
|
|
},
|
|
})
|
|
})
|
|
mux.HandleFunc("/server/history/list", func(w http.ResponseWriter, r *http.Request) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
_ = json.NewEncoder(w).Encode(map[string]any{
|
|
"result": map[string]any{
|
|
"jobs": []map[string]any{
|
|
{
|
|
"filename": "benchy.gcode",
|
|
"status": "completed",
|
|
"start_time": time.Now().Add(-2 * time.Hour).Unix(),
|
|
"end_time": time.Now().Add(-90 * time.Minute).Unix(),
|
|
"total_duration": 3600.0,
|
|
"print_duration": 3555.0,
|
|
"filament_used": 12345.6,
|
|
"total_weight": 34.5,
|
|
"message": "Completed successfully",
|
|
"metadata": map[string]any{"layer_height": 0.2},
|
|
},
|
|
{
|
|
"filename": "calibration_cube.gcode",
|
|
"status": "cancelled",
|
|
"start_time": time.Now().Add(-5 * time.Hour).Unix(),
|
|
"end_time": time.Now().Add(-4 * time.Hour).Unix(),
|
|
"total_duration": 1800.0,
|
|
"print_duration": 1240.0,
|
|
"filament_used": 2456.1,
|
|
"total_weight": 7.2,
|
|
"message": "User cancelled",
|
|
},
|
|
},
|
|
},
|
|
})
|
|
})
|
|
mux.HandleFunc("/server/files/metadata", func(w http.ResponseWriter, r *http.Request) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
_ = json.NewEncoder(w).Encode(map[string]any{
|
|
"result": map[string]any{
|
|
"filename": r.URL.Query().Get("filename"),
|
|
"modified": time.Now().Add(-30 * time.Minute).Unix(),
|
|
"size": 4926481,
|
|
"filament_name": []string{"Generic PLA Brown", "Generic PETG Blue"},
|
|
"filament_type": []string{"PLA", "PETG"},
|
|
"filament_weights": []float64{18.6, 7.4},
|
|
"referenced_tools": []int{0, 1},
|
|
"filament_weight_total": 26.0,
|
|
"mmu_print": 1,
|
|
},
|
|
})
|
|
})
|
|
mux.HandleFunc("/server/files/list", func(w http.ResponseWriter, r *http.Request) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
_ = json.NewEncoder(w).Encode([]map[string]any{
|
|
{
|
|
"path": "benchy.gcode",
|
|
"modified": time.Now().Add(-30 * time.Minute).Unix(),
|
|
"size": 4926481,
|
|
"permissions": "rw",
|
|
},
|
|
{
|
|
"path": "calibration_cube.gcode",
|
|
"modified": time.Now().Add(-2 * time.Hour).Unix(),
|
|
"size": 324236,
|
|
"permissions": "rw",
|
|
},
|
|
{
|
|
"path": "nested/test_piece.gcode",
|
|
"modified": time.Now().Add(-4 * time.Hour).Unix(),
|
|
"size": 1687387,
|
|
"permissions": "rw",
|
|
},
|
|
})
|
|
})
|
|
mux.HandleFunc("/printer/print/start", func(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method != http.MethodPost {
|
|
w.Header().Set("Allow", "POST")
|
|
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
|
return
|
|
}
|
|
w.Header().Set("Content-Type", "application/json")
|
|
_ = json.NewEncoder(w).Encode(map[string]any{
|
|
"result": "ok",
|
|
})
|
|
})
|
|
mux.HandleFunc("/printer/gcode/script", func(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method != http.MethodPost {
|
|
w.Header().Set("Allow", "POST")
|
|
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
|
return
|
|
}
|
|
w.Header().Set("Content-Type", "application/json")
|
|
_ = json.NewEncoder(w).Encode(map[string]any{
|
|
"result": "ok",
|
|
})
|
|
})
|
|
mux.HandleFunc("/printer/objects/query", func(w http.ResponseWriter, r *http.Request) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
_ = json.NewEncoder(w).Encode(map[string]any{
|
|
"result": map[string]any{
|
|
"status": map[string]any{
|
|
"print_stats": map[string]any{
|
|
"filename": "benchy.gcode",
|
|
"state": "printing",
|
|
"message": "Printing benchy",
|
|
"print_duration": 492.4,
|
|
"total_duration": 621.8,
|
|
"filament_used": 1234.5,
|
|
"estimated_time_remaining": 119.3,
|
|
"info": map[string]any{
|
|
"current_layer": 0,
|
|
"total_layer": 0,
|
|
},
|
|
},
|
|
"display_status": map[string]any{
|
|
"progress": 0.68,
|
|
},
|
|
"extruder": map[string]any{
|
|
"temperature": 215.4,
|
|
"target": 220.0,
|
|
},
|
|
"heater_bed": map[string]any{
|
|
"temperature": 61.2,
|
|
"target": 60.0,
|
|
},
|
|
"temperature_sensor chamber": map[string]any{
|
|
"temperature": 38.5,
|
|
},
|
|
"fan": map[string]any{
|
|
"speed": 0.74,
|
|
},
|
|
"fan_generic part_cooling": map[string]any{
|
|
"speed": 0.32,
|
|
},
|
|
"gcode_move": map[string]any{
|
|
"position": []float64{0, 0, 0.41, 0},
|
|
},
|
|
"toolhead": map[string]any{
|
|
"position": []float64{0, 0, 0.42},
|
|
},
|
|
},
|
|
},
|
|
})
|
|
})
|
|
mux.HandleFunc("/webcam/", func(w http.ResponseWriter, r *http.Request) {
|
|
switch r.URL.Query().Get("action") {
|
|
case "snapshot":
|
|
writeMockJPEG(w)
|
|
case "stream":
|
|
writeMockMJPEG(w)
|
|
default:
|
|
http.NotFound(w, r)
|
|
}
|
|
})
|
|
|
|
log.Printf("mock moonraker listening on %s", listen)
|
|
if err := http.ListenAndServe(listen, mux); err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
}
|
|
|
|
func writeMockJPEG(w http.ResponseWriter) {
|
|
w.Header().Set("Content-Type", "image/svg+xml")
|
|
_, _ = w.Write([]byte(`<svg xmlns="http://www.w3.org/2000/svg" width="640" height="360" viewBox="0 0 640 360"><rect width="640" height="360" fill="#111619"/><rect x="118" y="82" width="404" height="196" rx="10" fill="#1f2a2c" stroke="#48d4bf" stroke-width="4"/><circle cx="320" cy="180" r="58" fill="#48d4bf" opacity=".72"/><text x="320" y="306" fill="#f7f3eb" font-family="Arial" font-size="28" text-anchor="middle">Mock camera snapshot</text></svg>`))
|
|
}
|
|
|
|
func writeMockMJPEG(w http.ResponseWriter) {
|
|
w.Header().Set("Content-Type", "multipart/x-mixed-replace; boundary=frame")
|
|
flusher, _ := w.(http.Flusher)
|
|
for i := 0; i < 120; i++ {
|
|
frame := fmt.Sprintf(`<svg xmlns="http://www.w3.org/2000/svg" width="640" height="360" viewBox="0 0 640 360"><rect width="640" height="360" fill="#111619"/><rect x="%d" y="118" width="120" height="90" rx="8" fill="#48d4bf"/><text x="320" y="306" fill="#f7f3eb" font-family="Arial" font-size="28" text-anchor="middle">Mock camera stream %03d</text></svg>`, 80+(i%32)*12, i)
|
|
_, _ = fmt.Fprintf(w, "--frame\r\nContent-Type: image/svg+xml\r\nContent-Length: %d\r\n\r\n%s\r\n", len(frame), frame)
|
|
if flusher != nil {
|
|
flusher.Flush()
|
|
}
|
|
time.Sleep(250 * time.Millisecond)
|
|
}
|
|
_, _ = fmt.Fprint(w, "--frame--\r\n")
|
|
}
|
|
|
|
func mockMoonrakerObjects() []string {
|
|
return []string{
|
|
"webhooks",
|
|
"print_stats",
|
|
"display_status",
|
|
"gcode_move",
|
|
"toolhead",
|
|
"extruder",
|
|
"heater_bed",
|
|
"temperature_sensor chamber",
|
|
"temperature_fan chamber",
|
|
"fan",
|
|
"fan_generic part_cooling",
|
|
"controller_fan electronics",
|
|
}
|
|
}
|
|
|
|
func mockMoonrakerRequestedObjects(request map[string]any) []string {
|
|
params, _ := request["params"].(map[string]any)
|
|
requested, _ := params["objects"].(map[string]any)
|
|
names := make([]string, 0, len(requested))
|
|
for name := range requested {
|
|
names = append(names, name)
|
|
}
|
|
return names
|
|
}
|
|
|
|
func mockMoonrakerStatus(requested []string, tick int) map[string]any {
|
|
wanted := map[string]struct{}{}
|
|
for _, name := range requested {
|
|
wanted[name] = struct{}{}
|
|
}
|
|
status := map[string]any{}
|
|
if len(wanted) == 0 || containsMockMoonrakerObject(wanted, "print_stats") {
|
|
status["print_stats"] = map[string]any{
|
|
"filename": "benchy.gcode",
|
|
"state": "printing",
|
|
"message": "Printing benchy",
|
|
"print_duration": 492.4 + float64(tick),
|
|
"total_duration": 621.8 + float64(tick),
|
|
"filament_used": 1234.5 + float64(tick)*2,
|
|
"estimated_time_remaining": 119.3 - float64(tick),
|
|
"info": map[string]any{
|
|
"current_layer": tick + 1,
|
|
"total_layer": 12,
|
|
},
|
|
}
|
|
}
|
|
if len(wanted) == 0 || containsMockMoonrakerObject(wanted, "display_status") {
|
|
status["display_status"] = map[string]any{
|
|
"progress": 0.68 + float64(tick)*0.02,
|
|
}
|
|
}
|
|
if len(wanted) == 0 || containsMockMoonrakerObject(wanted, "extruder") {
|
|
status["extruder"] = map[string]any{
|
|
"temperature": 215.4 + float64(tick)*1.5,
|
|
"target": 220.0,
|
|
}
|
|
}
|
|
if len(wanted) == 0 || containsMockMoonrakerObject(wanted, "heater_bed") {
|
|
status["heater_bed"] = map[string]any{
|
|
"temperature": 61.2 + float64(tick)*0.8,
|
|
"target": 60.0,
|
|
}
|
|
}
|
|
if len(wanted) == 0 || containsMockMoonrakerObject(wanted, "temperature_sensor chamber") {
|
|
status["temperature_sensor chamber"] = map[string]any{
|
|
"temperature": 38.5 + float64(tick)*0.2,
|
|
}
|
|
}
|
|
if len(wanted) == 0 || containsMockMoonrakerObject(wanted, "temperature_fan chamber") {
|
|
status["temperature_fan chamber"] = map[string]any{
|
|
"temperature": 42.1 + float64(tick)*0.1,
|
|
"speed": 0.55,
|
|
}
|
|
}
|
|
if len(wanted) == 0 || containsMockMoonrakerObject(wanted, "fan") {
|
|
status["fan"] = map[string]any{
|
|
"speed": 0.74 - float64(tick)*0.01,
|
|
}
|
|
}
|
|
if len(wanted) == 0 || containsMockMoonrakerObject(wanted, "fan_generic part_cooling") {
|
|
status["fan_generic part_cooling"] = map[string]any{
|
|
"speed": 0.32 + float64(tick)*0.01,
|
|
}
|
|
}
|
|
if len(wanted) == 0 || containsMockMoonrakerObject(wanted, "controller_fan electronics") {
|
|
status["controller_fan electronics"] = map[string]any{
|
|
"speed": 0.22,
|
|
}
|
|
}
|
|
if len(wanted) == 0 || containsMockMoonrakerObject(wanted, "gcode_move") {
|
|
status["gcode_move"] = map[string]any{
|
|
"position": []float64{0, 0, 0.41 + float64(tick)*0.01, 0},
|
|
}
|
|
}
|
|
if len(wanted) == 0 || containsMockMoonrakerObject(wanted, "toolhead") {
|
|
status["toolhead"] = map[string]any{
|
|
"position": []float64{0, 0, 0.42 + float64(tick)*0.01},
|
|
}
|
|
}
|
|
return status
|
|
}
|
|
|
|
func containsMockMoonrakerObject(set map[string]struct{}, name string) bool {
|
|
_, ok := set[name]
|
|
return ok
|
|
}
|