-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
415 lines (372 loc) Β· 10.9 KB
/
index.js
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
const EventEmitter = require('events')
const request = require('request')
const JsonRpc = require('./lib/jsonrpc')
const fs = require('fs')
const crc = require('crc')
const Reflector = require('makerbot')
const path = require('path')
const bufferSplit = require('node-split').split
// Client ID/secret, for LAN access
const AUTH_CLIENT_ID = "MakerWare"
const AUTH_CLIENT_SECRET = "secret"
/**
* A client to interact with a MakerBot printer via JSON-RPC.
*
* @class MakerbotRpcClient
* @extends {EventEmitter}
*/
class MakerbotRpcClient extends EventEmitter {
constructor(options = { }) {
super()
this.connected = false
this.currentPrintBuffers = [ ]
this.currentPrintCrc32 = ""
this.currentPrintByteLength = 0
this._connect(options)
this.options = options
}
_connect(options) {
if(options.authMethod === "reflector")
this._initReflector(options)
else
this._initLocal(options)
}
reconnect() {
this.client.conn.end()
this.client.conn.destroy()
this.connected = false
this.emit("disconnected")
this._connect(this.options)
}
_setupConnection(options) {
// Set up autorescue
if(options.autoRescue) {
this.client.conn.on("timeout", () => {
this.emit("timeout")
this.client.conn.end()
this.client.conn.destroy()
this.connected = false
this.emit("disconnected")
this._connect(options)
})
this.client.conn.on("close", err => {
// only reconnect in case of connection error
if(err) {
this.connected = false
this.emit("disconnected")
this._connect(options)
}
})
}
this.client.on("response", res => {
// console.log("Sys notif", res)
if(res.method === "system_notification") {
this.state = res.params.info
this.emit("state", res)
}
})
this.client.on("binary-data", data => {
this.emit("camera-frame", data)
})
this.client.on("disconnected", () => {
this.connected = false
this.emit("disconnected")
})
}
/**
* Initialize a connection with the printer remotely via MakerBot Reflector.
*
* @param {any} options
*
* @memberOf MakerbotRpcClient
*/
_initReflector(options) {
this.reflector = new Reflector(options.accessToken)
this.reflector.callPrinter(options.printerId)
.catch(err => this.emit("connect-error", err))
.then(res => {
if(res.call) {
return res.call
} else {
this.emit("connect-error", res)
}
})
.then(res => {
var ip = res.relay.split(":")[0]
var port = parseInt(res.relay.split(":")[1])
this.client = new JsonRpc(ip, port)
this._setupConnection(options)
return this.client.request("auth_packet", {
call_id: res.id,
client_code: res.client_code,
printer_id: options.printerId
})
})
.then(res => {
if(res && res.result === true)
return true
else
this.emit("connect-error")
})
.catch(err => this.emit("connect-error", err))
.then(connResult => {
return this.client.request("handshake", { })
})
.then(handshakeRes => {
if(handshakeRes.result) {
this.emit("connected", handshakeRes.result)
this.emit("authenticated")
} else {
this.emit("connect-error", handshakeRes)
}
})
}
/**
* Initialize a connection with the printer via LAN.
*
* @param {any} options
*
* @memberOf MakerbotRpcClient
*/
_initLocal(options) {
this.client = new JsonRpc(options.ip, options.port || 9999)
this._setupConnection(options)
this.client.request("handshake", { })
.then(res => {
this.emit("connected", res.result)
this.printerInfo = res.result
this.connected = true
switch(options.authMethod){
case "thingiverse":
this._authenticateThingiverse(options.thingiverseToken, options.username)
break
case "access_token":
this._authenticateAccessToken(options.accessToken)
break
case "local_authorization":
default:
this._authenticateLocal()
break
}
})
}
/**
* Authenticate locally by pushing the knob on the printer.
*
* @memberOf MakerbotRpcClient
*/
_authenticateLocal() {
request(`http://${this.printerIp}/auth`, {
qs: {
response_type: "code",
client_id: AUTH_CLIENT_ID,
client_secret: AUTH_CLIENT_SECRET
},
json: true
}, (err, res, codeBody) => {
// poll every 5s until request is either accepted or rejected
this.emit("auth-push-knob")
var poll = setInterval(function() {
request(`http://${this.printerIp}/auth`, {
qs: {
response_type: "answer",
client_id: AUTH_CLIENT_ID,
client_secret: AUTH_CLIENT_SECRET,
answer_code: body.answer_code
},
json: true
}, (err, res, answerBody) => {
if(answerBody.answer === "accepted") {
// we don't need to poll anymore
clearInterval(poll)
request(`http://${this.printerIp}/auth`, {
qs: {
response_type: "token",
client_id: AUTH_CLIENT_ID,
client_secret: AUTH_CLIENT_SECRET,
context: "jsonrpc",
auth_code: answerBody.code
},
json: true
}, (err, res, tokenBody) => {
// complete the JSON-RPC authentication
_authenticateAccessToken(tokenBody.access_token)
})
}
})
}, 5000)
})
}
_authenticateThingiverse(thingiverseToken, username) {
request(`http://${this.printerIp}/auth`, {
qs: {
response_type: "code",
client_id: AUTH_CLIENT_ID,
client_secret: AUTH_CLIENT_SECRET,
thingiverse_token: thingiverseToken,
username: username
},
json: true
}, (err, res, codeBody) => {
request(`http://${this.printerIp}/auth`, {
qs: {
response_type: "answer",
client_id: AUTH_CLIENT_ID,
client_secret: AUTH_CLIENT_SECRET,
answer_code: codeBody.answer_code
},
json: true
}, (err, res, answerBody) => {
if(answerBody.answer === "accepted") {
request(`http://${this.printerIp}/auth`, {
qs: {
response_type: "token",
client_id: AUTH_CLIENT_ID,
client_secret: AUTH_CLIENT_SECRET,
context: "jsonrpc",
auth_code: answerBody.code
},
json: true
}, (err, res, tokenBody) => {
// complete the JSON-RPC authentication
this._authenticateAccessToken(tokenBody.access_token)
})
}
})
})
}
/**
* Authenticate to JSON-RPC with an `access_token`.
*
* @param {string} accessToken The `access_token` obtained via the printer's HTTP API.
*
* @memberOf MakerbotRpcClient
*/
_authenticateAccessToken(accessToken) {
this.client.request("authenticate", { access_token: accessToken })
.then(res => {
this.emit("authenticated", res)
})
}
getMachineConfig() {
return this.client.request("get_machine_config")
}
changeMachineName(machine_name) {
return this.client.request("change_machine_name", { machine_name })
}
loadFilament(tool_index = 0) {
return this.client.request("load_filament", { tool_index })
}
unloadFilament(tool_index = 0) {
return this.client.request("unload_filament", { tool_index })
}
cancel() {
return this.client.request("cancel")
}
startCameraStream() {
console.warn("!!! GETTING CAMERA DATA IS HIGHLY EXPERIMENTAL AND NOT PRODUCTION READY !!!\nYOU HAVE BEEN WARNED!")
return this.client.request("request_camera_stream", { })
}
endCameraStream() {
// this.client.flushMemory()
return this.client.request("end_camera_stream", { })
}
getSingleCameraFrame() {
return new Promise((resolve, reject) => {
this.client.once("binary-data", data => {
this.endCameraStream()
resolve(data)
})
this.startCameraStream()
})
}
printUrl(url) {
// TODO do we know if this works?
// I mean, technically it should, right?
return new Promise((resolve, reject) => {
this.client.request("print", {
filepath: url
}).catch(reject).then(resolve)
})
}
sendPrintPart(index) {
if(index === this.currentPrintBuffers.length) {
// console.log("Done sending print!")
this.client.request("put_term", {
crc: this.currentPrintCrc32,
file_id: "1",
length: this.currentPrintByteLength
})
.then(res => {
this.currentPrintBuffers = [ ]
this.currentPrintByteLength = 0
this.currentPrintCrc32 = ""
// console.log("put_term res", res)
})
} else {
// console.log(`Sending print part ${index + 1}/${this.currentPrintBuffers.length}`)
this.client.request("put_raw", {
file_id: "1",
length: this.currentPrintBuffers[index].byteLength
})
.then(() => {
this.client.conn.write(this.currentPrintBuffers[index], () => {
// console.log(`Done with ${index + 1}/${this.currentPrintBuffers.length}`)
this.sendPrintPart(index + 1)
})
})
}
}
initPrint(data, filename) {
// Split the buffer into multiple pieces
bufferSplit(data, {
bytes: 50000
}, (err, buffers) => {
this.currentPrintBuffers = buffers
this.currentPrintByteLength = data.byteLength
this.currentPrintCrc32 = crc.crc32(data)
this.client.request("print", {
filepath: filename,
transfer_wait: true
})
.then(res => {
// emulate pressing the "start print" button
this.client.request("process_method", {
method: "build_plate_cleared"
})
return this.client.request("put_init", {
block_size: 50000,
file_id: "1",
file_path: `/current_thing/${filename}`,
length: data.byteLength
})
})
.then(() => {
this.sendPrintPart(0)
})
})
// .then(res => {
// this.client.conn.write(data, () => {
// this.client.request("put_term", {
// crc: crc.crc32(data),
// file_id: "1",
// length: data.length
// })
// })
// })
}
printFile(file) {
// TODO what's the max length of the file name?
var filename = path.parse(file).base
// TODO handle errors in this promise
return new Promise((resolve, reject) => {
fs.readFile(file, (err, data) => {
if(err)
reject(err)
else
resolve(this.initPrint(data, filename))
})
})
}
}
module.exports = MakerbotRpcClient