/
client.go
419 lines (338 loc) Β· 10.5 KB
/
client.go
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
package makerbot
import (
"encoding/json"
"errors"
"fmt"
"hash/crc32"
"io/ioutil"
"path/filepath"
"strings"
"github.com/tjhorner/makerbot-rpc/printfile"
"github.com/tjhorner/makerbot-rpc/reflector"
"github.com/tjhorner/makerbot-rpc/jsonrpc"
)
const printFileBlockSize = 100000 // 100 KB
type rpcEmptyParams struct{}
type rpcSystemNotification struct {
Info *PrinterMetadata `json:"info"`
}
// Client represents an RPC client that can connect to
// MakerBot 3D printers via the network.
//
// Calls to the printer (e.g. LoadFilament, Cancel, etc.)
// will block, so you may want to take this into consideration.
type Client struct {
IP string
Port string
Printer *Printer
stateCbs []func(old, new *PrinterMetadata)
cameraCh *chan CameraFrame
cameraCbs []func(*CameraFrame)
rpc *jsonrpc.Client
}
// ConnectLocal connects to a local printer and performs the initial handshake.
// If it is successful, the Printer field will be populated with information
// about the machine this client is connected to.
//
// After using ConnectLocal, you must use one of the AuthenticateWith* methods
// to authenticate with the printer.
func (c *Client) ConnectLocal(ip, port string) error {
c.IP = ip
c.Port = port
err := c.connectRPC()
if err != nil {
return err
}
return c.handshake()
}
// ConnectRemote uses MakerBot Reflector to remotely connect to a printer
// and performs the initial handshake. It will connect to printer with ID
// `id` and will authenticate using the Thingiverse token `accessToken`.
//
// Since authentication is already performed by Thingiverse, you do not need
// to perform any additional authentication after it is connected.
func (c *Client) ConnectRemote(id, accessToken string) error {
refl := reflector.NewClient(accessToken)
call, err := refl.CallPrinter(id)
if err != nil {
return err
}
split := strings.Split(call.Call.Relay, ":")
c.IP = split[0]
c.Port = split[1]
err = c.connectRPC()
if err != nil {
return err
}
ok, err := c.sendAuthPacket(id, call)
if err != nil {
return err
}
if !*ok {
return errors.New("could not authenticate with printer via Reflector call")
}
return c.handshake()
}
func (c *Client) connectRPC() error {
c.rpc = jsonrpc.NewClient(c.IP, c.Port)
return c.rpc.Connect()
}
func (c *Client) handshake() error {
printer, err := c.sendHandshake()
if err != nil {
return err
}
c.Printer = printer
onStateChange := func(message json.RawMessage) {
var oldState *PrinterMetadata
if c.Printer != nil {
oldState = c.Printer.Metadata
}
var newState rpcSystemNotification
json.Unmarshal(message, &newState)
c.Printer.Metadata = newState.Info
for _, cb := range c.stateCbs {
go cb(oldState, newState.Info) // Async so we don't block other callbacks
}
}
c.rpc.Subscribe("system_notification", onStateChange)
c.rpc.Subscribe("state_notification", onStateChange)
c.rpc.Subscribe("camera_frame", func(m json.RawMessage) {
if len(c.cameraCbs) == 0 {
go c.endCameraStream()
}
metadata := unpackCameraFrameMetadata(c.rpc.GetRawData(16))
data := c.rpc.GetRawData(int(metadata.FileSize))
frame := CameraFrame{
Data: data,
Metadata: &metadata,
}
if c.cameraCh != nil {
*c.cameraCh <- frame
c.cameraCh = nil
}
for _, cb := range c.cameraCbs {
go cb(&frame) // Async so we don't block other callbacks
}
})
return nil
}
// Close closes the underlying TCP socket
// and should be called when the client is no
// longer needed
func (c *Client) Close() error {
if c.rpc == nil {
return nil // Nothing to do
}
return c.rpc.Close()
}
// HandleStateChange calls `cb` when the printer's state changes.
//
// The first parameter passed to `cb` is the previous state, and the
// second is the new state. You can use this to respond when e.g. a print
// fails for some reason, or when a print's progress changes.
func (c *Client) HandleStateChange(cb func(old, new *PrinterMetadata)) {
c.stateCbs = append(c.stateCbs, cb)
}
// HandleCameraFrame calls `cb` when the printer sends a camera frame.
func (c *Client) HandleCameraFrame(cb func(frame *CameraFrame)) {
c.cameraCbs = append(c.cameraCbs, cb)
go c.requestCameraStream()
}
func (c *Client) call(method string, args, result interface{}) error {
if c.rpc == nil {
return errors.New("client is not connected to printer")
}
return c.rpc.Call(method, args, &result)
}
func (c *Client) sendHandshake() (*Printer, error) {
var reply Printer
return &reply, c.call("handshake", rpcEmptyParams{}, &reply)
}
type rpcAuthenticateParams struct {
AccessToken string `json:"access_token"`
}
// authenticate performs authentication with the printer
// via an access token retrieved through the printer's
// HTTP server
func (c *Client) authenticate(accessToken string) (*json.RawMessage, error) {
var reply json.RawMessage
return &reply, c.call("authenticate", rpcAuthenticateParams{accessToken}, &reply)
}
type rpcAuthPacketParams struct {
CallID string `json:"call_id"`
ClientCode string `json:"client_code"`
PrinterID string `json:"printer_id"`
}
func (c *Client) sendAuthPacket(id string, pc *reflector.CallPrinterResponse) (*bool, error) {
params := rpcAuthPacketParams{
CallID: pc.Call.ID,
ClientCode: pc.Call.ClientCode,
PrinterID: id,
}
var reply bool
return &reply, c.call("auth_packet", params, &reply)
}
// AuthenticateWithThingiverse performs authentication with the printers
// by using a Thingiverse token:username pair.
//
// Ensure that you have authenticated your Thingiverse account with this printer
// at least once in the past. You can do this logging into the MakerBot Print
// application and connecting to the printer.
func (c *Client) AuthenticateWithThingiverse(token, username string) error {
accessToken, err := c.getThingiverseAccessToken(token, username)
if err != nil {
return err
}
_, err = c.authenticate(*accessToken)
return err
}
type rpcLoadUnloadFilamentParams struct {
ToolIndex int `json:"tool_index"`
}
// LoadFilament instructs the printer to begin loading filament into
// the extruder
func (c *Client) LoadFilament(toolIndex int) (*PrinterProcess, error) {
var reply PrinterProcess
return &reply, c.call("load_filament", rpcLoadUnloadFilamentParams{toolIndex}, &reply)
}
// UnloadFilament instructs the printer to begin unloading filament from
// the extruder
func (c *Client) UnloadFilament(toolIndex int) (*json.RawMessage, error) {
var reply json.RawMessage
return &reply, c.call("unload_filament", rpcLoadUnloadFilamentParams{toolIndex}, &reply)
}
// Cancel instructs the printer to cancel the current process, if any.
//
// It may result in a `ProcessNotCancellableException`, so you may want to
// check the `CurrentProcess` to ensure it is `Cancellable`. Or not, if you
// don't care if it fails.
func (c *Client) Cancel() (*json.RawMessage, error) {
var reply json.RawMessage
return &reply, c.call("cancel", rpcEmptyParams{}, &reply)
}
type rpcChangeMachineNameParams struct {
MachineName string `json:"machine_name"`
}
// ChangeMachineName instructs the printer to change its display name.
func (c *Client) ChangeMachineName(name string) (*json.RawMessage, error) {
var reply json.RawMessage
return &reply, c.call("cancel", rpcChangeMachineNameParams{name}, &reply)
}
func (c *Client) requestCameraStream() error {
return c.call("request_camera_stream", rpcEmptyParams{}, nil)
}
func (c *Client) endCameraStream() error {
return c.call("end_camera_stream", rpcEmptyParams{}, nil)
}
// GetCameraFrame requests a single frame from the printer's camera
func (c *Client) GetCameraFrame() (*CameraFrame, error) {
ch := make(chan CameraFrame)
c.cameraCh = &ch
err := c.requestCameraStream()
if err != nil {
return nil, err
}
data := <-ch
close(ch)
return &data, nil
}
type rpcPutRawParams struct {
FileID string `json:"file_id"`
Length int `json:"length"`
}
func (c *Client) sendPrintPart(part *[]byte) error {
err := c.call("put_raw", rpcPutRawParams{"1", len(*part)}, nil)
if err != nil {
return err
}
_, err = c.rpc.Write(*part)
if err != nil {
return err
}
return nil
}
type rpcPrintParams struct {
FilePath string `json:"filepath"`
TransferWait bool `json:"transfer_wait"`
}
type rpcProcessMethodParams struct {
Method string `json:"method"`
}
type rpcPutInitParams struct {
BlockSize int `json:"block_size"`
FileID string `json:"file_id"`
FilePath string `json:"file_path"`
Length int `json:"length"`
}
type rpcPutTermParams struct {
Checksum uint32 `json:"crc"`
FileID string `json:"file_id"`
Length int `json:"length"`
}
// Print will synchronously print a .makerbot file with the provided
// `filename` (can be anything). `data` should be the contents of the
// .makerbot file. The function returns when it is done sending the entire
// file. If you want to monitor progress of the upload, see HandleStateChange.
//
// For easier usage, see PrintFile.
func (c *Client) Print(filename string, data []byte) error {
err := c.call("print", rpcPrintParams{filename, true}, nil)
if err != nil {
return err
}
err = c.call("process_method", rpcProcessMethodParams{"build_plate_cleared"}, nil)
if err != nil {
return err
}
err = c.call("put_init", rpcPutInitParams{
BlockSize: printFileBlockSize,
FileID: "1",
FilePath: fmt.Sprintf("/current_thing/%s", filename),
Length: len(data),
}, nil)
if err != nil {
return err
}
checksum := crc32.ChecksumIEEE(data)
var parts [][]byte
for i := 0; i < len(data); i += printFileBlockSize {
end := i + printFileBlockSize
if end > len(data) {
end = len(data)
}
parts = append(parts, data[i:end])
}
for _, part := range parts {
err = c.sendPrintPart(&part)
if err != nil {
return err
}
}
return c.call("put_term", rpcPutTermParams{checksum, "1", len(data)}, nil)
}
// PrintFile is a convenience method for Print, taking in a
// `filename` and automatically reading from it then
// feeding it to Print.
func (c *Client) PrintFile(filename string) error {
// TODO support streaming files in so we don't need to
// load the entire thing into memory
data, err := ioutil.ReadFile(filename)
if err != nil {
return err
}
return c.Print(filepath.Base(filename), data)
}
// PrintFileVerify is exactly like PrintFile except it errors
// if the print file is not designed for the printer that this
// Client is connected to.
func (c *Client) PrintFileVerify(filename string) error {
metadata, err := printfile.GetFileMetadata(filename)
if err != nil {
return err
}
if metadata.BotType != c.Printer.BotType {
return errors.New("print file is not designed for this MakerBot printer")
}
return c.PrintFile(filename)
}