-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebsocket.go
More file actions
69 lines (56 loc) · 1.51 KB
/
websocket.go
File metadata and controls
69 lines (56 loc) · 1.51 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
package main
import (
"encoding/json"
"errors"
"strings"
"golang.org/x/net/websocket"
)
type printerSocketRequest struct {
Method string `json:"method"`
Params map[string]any `json:"params"`
}
type PrinterSocket struct {
ws *websocket.Conn
InitalFrame InitalWSResponse
}
// sends a raw query to the printer
func (ps PrinterSocket) SendRawQuery(method string, params map[string]any) error {
payload := printerSocketRequest{
Method: method,
Params: params,
}
ba, err := json.Marshal(payload)
if err != nil {
return err
}
_, werr := ps.ws.Write(ba)
if werr != nil {
return werr
}
return nil
}
// closes the socket
func (ps PrinterSocket) Close() error {
return ps.ws.Close()
}
// modifies a gcode file (delete, rename, print)
func (ps PrinterSocket) ModifyFile(file string, action string) error {
return ps.SendRawQuery("set", map[string]any{
"opGcodeFile": strings.ToLower(action) + "prt:/usr/data/printer_data/gcodes/" + file,
})
}
func NewPrinterWebsocket(url string) (PrinterSocket, error) {
ws, err := websocket.Dial("ws://"+url+":9999", "", "http://"+url)
if err != nil {
return PrinterSocket{}, errors.New("could not create printer websocket, is the printer online?\n" + err.Error())
}
var InitalData InitalWSResponse
err = websocket.JSON.Receive(ws, &InitalData)
if err != nil {
return PrinterSocket{}, errors.New("failed receiving initial frame from websocket, what?\n" + err.Error())
}
return PrinterSocket{
ws: ws,
InitalFrame: InitalData,
}, nil
}