Skip to content

Commit a3df08c

Browse files
committed
integrate smfix, and improve discover
1 parent 7ee6638 commit a3df08c

File tree

11 files changed

+266
-259
lines changed

11 files changed

+266
-259
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
11
*.py
22
dist/
33
.vscode/
4+
go.work*

connector.go

Lines changed: 57 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,53 @@ package main
22

33
import (
44
"errors"
5+
"io"
56
"net"
67
"time"
78
)
89

10+
const (
11+
FILE_SIZE_MIN = 1
12+
FILE_SIZE_MAX = 2 << 30 // 2GB
13+
)
14+
15+
var (
16+
errFileEmpty = errors.New("File is empty.")
17+
errFileTooLarge = errors.New("File is too large.")
18+
)
19+
20+
type Payload struct {
21+
File io.Reader
22+
Name string
23+
Size int64
24+
}
25+
26+
func (p *Payload) SetName(name string) {
27+
p.Name = normalizedFilename(name)
28+
}
29+
30+
func (p *Payload) ReadableSize() string {
31+
return humanReadableSize(p.Size)
32+
}
33+
34+
func (p *Payload) GetContent(fix bool) (cont []byte, err error) {
35+
if fix {
36+
cont, err = postProcess(p.File)
37+
p.Size = int64(len(cont))
38+
} else {
39+
cont, err = io.ReadAll(p.File)
40+
}
41+
return cont, err
42+
}
43+
44+
func NewPayload(file io.Reader, name string, size int64) *Payload {
45+
return &Payload{
46+
File: file,
47+
Name: normalizedFilename(name),
48+
Size: size,
49+
}
50+
}
51+
952
type connector struct {
1053
handlers []Handler
1154
}
@@ -14,38 +57,42 @@ type Handler interface {
1457
Ping(*Printer) bool
1558
Connect() error
1659
Disconnect() error
17-
Upload(fname string, content []byte) error
60+
Upload(*Payload) error
1861
}
1962

2063
func (c *connector) RegisterHandler(h Handler) {
2164
c.handlers = append(c.handlers, h)
2265
}
2366

2467
// Upload to upload a file to a printer
25-
func (c *connector) Upload(p *Printer, fname string, content []byte) error {
68+
func (c *connector) Upload(printer *Printer, payload *Payload) error {
2669
// Iterate through all handlers
2770
for _, h := range c.handlers {
2871
// Check if handler can ping the printer
29-
if h.Ping(p) {
72+
if h.Ping(printer) {
3073
// Connect to the printer
3174
if err := h.Connect(); err != nil {
3275
return err
3376
}
34-
// Upload the file to the printer
35-
if err := h.Upload(fname, content); err != nil {
36-
h.Disconnect()
37-
return err
77+
defer h.Disconnect()
78+
79+
if payload.Size > FILE_SIZE_MAX {
80+
return errFileTooLarge
81+
}
82+
if payload.Size < FILE_SIZE_MIN {
83+
return errFileEmpty
3884
}
39-
// Disconnect from the printer
40-
if err := h.Disconnect(); err != nil {
85+
// Upload the file to the printer
86+
if err := h.Upload(payload); err != nil {
4187
return err
4288
}
89+
4390
// Return nil if successful
4491
return nil
4592
}
4693
}
4794
// Return error if printer is not available
48-
return errors.New("Printer " + p.IP + " is not available.")
95+
return errors.New("Printer " + printer.IP + " is not available.")
4996
}
5097

5198
var Connector = &connector{}

connector_http.go

Lines changed: 45 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
package main
22

33
import (
4-
"bytes"
54
"fmt"
65
"io"
76
"log"
@@ -40,16 +39,12 @@ func (hc *HTTPConnector) Ping(p *Printer) bool {
4039
}
4140

4241
func (hc *HTTPConnector) Connect() error {
43-
hc.client = req.C()
44-
hc.client.DisableAllowGetMethodPayload()
45-
// hc.client.EnableDumpAllWithoutRequestBody()
46-
4742
result := struct {
4843
Token string `json:"token"`
4944
}{}
5045

5146
req := hc.request().
52-
SetSuccessResult(&result).
47+
SetResult(&result).
5348
SetRetryCount(3).
5449
SetRetryFixedInterval(1 * time.Second).
5550
SetRetryCondition(func(r *req.Response, err error) bool {
@@ -103,19 +98,19 @@ func (hc *HTTPConnector) Connect() error {
10398
}
10499

105100
func (hc *HTTPConnector) Disconnect() (err error) {
106-
if hc.printer.Token != "" {
101+
if hc.client != nil && hc.printer.Token != "" {
107102
_, err = hc.request().Post(hc.URL("/disconnect"))
108103
}
109104
return
110105
}
111106

112-
func (hc *HTTPConnector) Upload(fname string, content []byte) (err error) {
107+
func (hc *HTTPConnector) Upload(payload *Payload) (err error) {
113108
finished := make(chan empty, 1)
114109
defer func() {
115110
finished <- empty{}
116111
}()
117112
go func() {
118-
ticker := time.NewTicker(1 * time.Second)
113+
ticker := time.NewTicker(2 * time.Second)
119114
for {
120115
select {
121116
case <-ticker.C:
@@ -140,19 +135,40 @@ func (hc *HTTPConnector) Upload(fname string, content []byte) (err error) {
140135

141136
file := req.FileUpload{
142137
ParamName: "file",
143-
FileName: fname,
138+
FileName: payload.Name,
144139
GetFileContent: func() (io.ReadCloser, error) {
145-
return io.NopCloser(bytes.NewBuffer(content)), nil
140+
pr, pw := io.Pipe()
141+
go func() {
142+
defer pw.Close()
143+
content, err := payload.GetContent(SmFix)
144+
if SmFix {
145+
log.SetOutput(os.Stderr)
146+
if err != nil {
147+
log.Printf("G-Code fix error(ignored): %s", err)
148+
} else {
149+
log.Printf("G-Code fixed")
150+
}
151+
log.SetOutput(w)
152+
}
153+
pw.Write(content)
154+
}()
155+
return pr, nil
146156
},
147-
FileSize: int64(len(content)),
148-
ContentType: "application/octet-stream",
157+
FileSize: payload.Size,
158+
// ContentType: "application/octet-stream",
149159
}
150-
req := hc.request(0).SetFileUpload(file).SetUploadCallbackWithInterval(func(info req.UploadInfo) {
151-
perc := float64(info.UploadedSize/info.FileSize) * 100.0
152-
log.Printf(" - HTTP sending %.1f%%", perc)
160+
r := hc.request(0)
161+
r.SetFileUpload(file)
162+
r.SetUploadCallbackWithInterval(func(info req.UploadInfo) {
163+
if info.FileSize > 0 {
164+
perc := float64(info.UploadedSize) / float64(info.FileSize) * 100.0
165+
log.Printf(" - HTTP sending %.1f%%", perc)
166+
} else {
167+
log.Printf(" - HTTP sending %s...", humanReadableSize(info.UploadedSize))
168+
}
153169
}, 35*time.Millisecond)
154170

155-
_, err = req.Post(hc.URL("/upload"))
171+
_, err = r.Post(hc.URL("/upload"))
156172
return
157173
}
158174

@@ -161,13 +177,21 @@ func (hc *HTTPConnector) request(timeout ...int) *req.Request {
161177
if len(timeout) > 0 {
162178
to = timeout[0]
163179
}
180+
181+
if hc.client == nil {
182+
hc.client = req.C()
183+
hc.client.DisableAllowGetMethodPayload()
184+
if Debug {
185+
hc.client.EnableDumpAllWithoutRequestBody()
186+
}
187+
}
188+
164189
req := hc.client.SetTimeout(time.Second * time.Duration(to)).R()
165-
// for POST
166-
req.SetFormData(map[string]string{"token": hc.printer.Token})
167190
// for GET
168191
req.SetQueryParam("token", hc.printer.Token)
169-
// no cache
170-
req.SetQueryParam("_", fmt.Sprintf("%d", time.Now().Unix()))
192+
// for POST
193+
req.SetFormData(map[string]string{"token": hc.printer.Token})
194+
171195
return req
172196
}
173197

connector_sacp.go

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -41,12 +41,22 @@ func (sc *SACPConnector) Connect() (err error) {
4141

4242
func (sc *SACPConnector) Disconnect() error {
4343
if sc.conn != nil {
44+
SACP_disconnect(sc.conn, SACPTimeout*time.Second)
4445
sc.conn.Close()
4546
}
4647
return nil
4748
}
4849

49-
func (sc *SACPConnector) Upload(fname string, content []byte) (err error) {
50+
func (sc *SACPConnector) Upload(payload *Payload) (err error) {
51+
content, err := payload.GetContent(SmFix)
52+
if SmFix {
53+
if err != nil {
54+
log.Printf("G-Code fix error(ignored): %s", err)
55+
} else {
56+
log.Printf("G-Code fixed")
57+
}
58+
}
59+
5060
w := uilive.New()
5161
w.Start()
5262
log.SetOutput(w)
@@ -55,7 +65,7 @@ func (sc *SACPConnector) Upload(fname string, content []byte) (err error) {
5565
log.SetOutput(os.Stderr)
5666
}()
5767

58-
err = SACP_start_upload(sc.conn, fname, content, SACPTimeout*time.Second)
68+
err = SACP_start_upload(sc.conn, payload.Name, content, SACPTimeout*time.Second)
5969
return
6070
}
6171

0 commit comments

Comments
 (0)