This repository has been archived by the owner on Feb 3, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathclient.ts
89 lines (76 loc) · 1.96 KB
/
client.ts
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
//#!tsc --target ES5 --module commonjs client.ts && node client.js
///<reference path="./typings/bundle.d.ts"/>
import * as websocket from 'websocket';
import events = require("events");
class GrblClient extends events.EventEmitter {
client : websocket.client;
connection: websocket.connection;
id: number;
requests: { [id: number ]: any };
constructor() {
super();
this.client = new websocket.client();
this.id = 0;
this.requests = {};
}
connect(uri: string): GrblClient {
this.client.connect(uri, null);
this.client.on('connect', (connection) => {
this.connection = connection;
this.emit('connect');
connection.on('message', (message) => {
console.log(message.utf8Data);
var data = JSON.parse(message.utf8Data);
if (data.id) {
try {
if (data.hasOwnProperty('error')) {
this.requests[data.id].reject(data.error);
} else {
this.requests[data.id].resolve(data.result);
}
} catch (e) {
console.log(e);
}
}
});
this.request({ method: 'config' }).
then( (config) => {
console.log(config);
});
this.request({ method: 'gcode', params: {} }).
then( (res) => {
console.log('gcode res', res);
});
this.request({ method: 'command', params: { command: '$X' } }).
then( (res) => {
console.log('gcode res', res);
});
this.request({ method: 'gcode', params: {
gcode : "G01 X0.000 Y0.000 F500\n"
} }).
then( (res) => {
console.log('gcode res', res);
});
});
this.client.on('connectFailed', (err) => {
console.log(err);
this.emit('error', err);
});
return this;
}
request(req: any):Promise<any> {
return new Promise( (resolve, reject) => {
var id = this.id++;
this.requests[id] = {
resolve: resolve,
reject: reject,
};
this.connection.sendUTF(JSON.stringify({
id: id,
method: req.method,
params: req.params,
}));
});
}
}
var client = new GrblClient().connect('ws://localhost:8080');