forked from CriMilanese/plotter-frontend
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathindex.js
More file actions
369 lines (322 loc) · 10.9 KB
/
index.js
File metadata and controls
369 lines (322 loc) · 10.9 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
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
const express = require("express")
const bp = require("body-parser")
const app = express()
const { exec } = require("child_process");
const fileUpload = require("express-fileupload");
const fs = require("fs");
const path = require("path");
const morgan = require("morgan");
const Validator = require("validatorjs");
const { nextTick } = require("process");
const { SerialPort } = require('serialport');
const validator = (body, rules, customMessages, callback) => {
const validation = new Validator(body, rules, customMessages);
validation.passes(() => callback(null, true));
validation.fails(() => callback(validation.errors, false));
};
app.use("/static", express.static(path.join(__dirname, "public")));
app.use(bp.json())
app.use(express.urlencoded({extended: true}));
app.use(fileUpload({
limits: {
fileSize: 16 * 1024 * 1024 // 4 MB
},
abortOnLimit: true,
createParentPath: true
}))
app.use(morgan("dev"))
// from https://github.com/expressjs/express/blob/2c47827053233e707536019a15499ccf5496dc9d/examples/route-map/index.js#L14
app.map = function(a, route){
route = route || "";
for (var key in a) {
switch (typeof a[key]) {
// { "/path": { ... }}
case "object":
app.map(a[key], route + key);
break;
// get: function(){ ... }
case "function":
console.log("adding route %s %s", key, route);
app[key](route, a[key]);
break;
}
}
};
app.param("sid", (req, res, next, sid) => {
req.basePath = path.join(__dirname, "files", sid);
req.sid = sid;
fs.mkdir(req.basePath, { recursive: true }, (err) => {
if (err) { return res.status(500).send("Internal server error"); }
else { return next(); }
});
})
const upload = (req, res) => {
if (!req.files) {
return res.status(400).send("No files were uploaded.");
}
const filename = req.files.file.name;
const filepath = path.join(req.basePath, "image.svg");
const extensionName = filename.substring(filename.length - 4); // fetch the file extension
const allowedExtension = [".svg",".SVG"];
if(!allowedExtension.includes(extensionName)){
return res.status(422).send("Invalid Image");
}
req.files.file.mv(filepath, (err) => {
if (err) {
return res.status(500).send("Internal server error");
} else {
return res.send({ status: "success" });
}
});
}
const renderSVG = (req, res) => {
let json = req.body
validator(
json,
{
// validation goes there
"colors_only": "boolean",
"color_key": "regex:/^(#[0-9a-fA-F]{6}\\s?)+$/",
"scale": "required|numeric|min:0.1",
"mirror": "in:on",
"shrink": "in:on",
"cut": "in:on",
"hatch": "in:on",
"hatch_density": "numeric|min:0.1",
"speed": "integer|min:1|max:37",
"angle": "integer|min:0|max:90",
},
{},
(err, status) => {
if (!status) {
res.status(412).send(err);
} else {
let cmd = "./wild_driver_bin";
cmd += " --input " + path.join(req.basePath, "image.svg");
cmd += " --vis " + path.join(req.basePath, "vis.svg");
if (json.colors_only) {
cmd += " --colors_only"
}
console.log(json.color_key)
if (json.color_key) {
cmd += ` --color_key ${json.color_key.replace(/#/g, "\\#")} `
}
cmd += " --scale " + parseFloat(json.scale)
if (json.speed)
{
cmd += " --speed " + parseInt(json.speed)
}
if (json.angle)
{
cmd += " --lift_angle " + parseInt(json.angle)
}
if (json.mirror) {
cmd += " --mirror"
}
if (json.shrink) {
cmd += " --shrink_to_size"
}
if (json.cut) {
cmd += " --cut"
}
if (json.hatch) {
cmd += " --hatch"
}
if (json.hatch_density) {
cmd += " --hatch_density " + parseFloat(json.hatch_density)
}
cmd += " --output " + req.basePath + "/"
exec(cmd + "box.wild --box", (error, stdout, stderr) => {
console.log("====== box ======\n")
console.log(cmd + "box.wild --box\n")
console.log(stdout)
console.log(stderr)
j = JSON.parse(stdout)
if (error) { return res.json({"success": false, "step": 1, "error": j.error}) }
exec(cmd + "dry_run.wild --dry_run", (error, stdout, stderr) => {
console.log("====== dry_run ======\n")
console.log(cmd + "dry_run.wild --dry_run\n")
console.log(stdout)
console.log(stderr)
j = JSON.parse(stdout)
if (error) { return res.json({"success": false, "step": 2, "error": j.error}) }
exec(cmd + "draw.wild", (error, stdout, stderr) => {
console.log("====== draw ======\n")
console.log(cmd + "draw.wild\n")
console.log(stdout)
console.log(stderr)
j = JSON.parse(stdout)
if (error) { return res.json({"success": false, "step": 3, "error": j.error}) }
return res.json({"success": true, "output": j.output})
});
});
});
}
}
)
}
// global state of the plotter (drawing)
let plotterReader = undefined;
let plotterWriter = undefined;
let plotterLastOutput = ""
let plotterAuthor = ""
let plotterSizeCur = 0;
let plotterSizeTotal = 1;
const plotterPort = '/dev/ttyS0';
const plotterRun = (req, res) => {
if(plotterReader !== undefined) { return res.status(409).send("Plotter busy"); }
plotterReader = true;
plotterAuthor = req.sid;
plotterLastOutput = "preparing...";
plotterSizeCur = 0;
plotterSizeTotal = 1;
let tgt = "";
if(req.params.target === "box"){ tgt = "box.wild" }
if(req.params.target === "dry_run"){ tgt = "dry_run.wild" }
if(req.params.target === "draw"){ tgt = "draw.wild" }
if(tgt === ""){ return res.status(404).send("Invalid endpoint") }
let wildfile = path.join(req.basePath, tgt);
let tempWildfile = path.join(__dirname, "files", "current_plot.wild");
// Make a copy of the wildfile so we're sure nobody replace the drawing midway
fs.copyFile(wildfile, tempWildfile, (err) => {
if (err) {
console.error("====== Error while copying ======");
console.error(err);
plotterReader = undefined;
plotterLastOutput = "copy failed";
res.status(500).send("Could not create temporary file");
return;
}
// Read size of file
try {
plotterSizeTotal = fs.statSync(tempWildfile).size;
} catch(err) {
// If we don't get it we don't really care.
console.warn(err);
}
// Configure serial port
const plotterWriter = new SerialPort({
path: plotterPort,
baudRate: 9600,
rtscts: true,
autoOpen: false,
});
plotterWriter.open((err) => {
if (err) {
console.error(`====== Error while opening port ======`);
console.error(err);
plotterReader = undefined;
plotterLastOutput = "setup failed";
res.status(500).send("Could not setup serial port");
return;
}
// Open the copy and the port to be read one byte at a time
// so it can be interrupted whenever
plotterReader = fs.createReadStream(tempWildfile, {highWaterMark: 1});
// When we read something
plotterReader.on('data', (chunk) => {
plotterSizeCur += chunk.length;
plotterWriter.write(chunk);
plotterWriter.drain();
});
// For when errors happen
plotterReader.on('error', (err) => {
console.error("====== Error while reading ======");
console.error(err);
plotterLastOutput = "read failed";
});
plotterWriter.on('error', (err) => {
console.error("====== Error while writing ======");
console.error(err);
plotterLastOutput = "write failed";
});
// For when the file is reached
plotterReader.on('end', () => {
plotterLastOutput = "success";
});
// For when we stop writing
// (either because of error, end reached, or stopped)
plotterReader.on('close', () => {
plotterReader = undefined;
plotterWriter.close();
});
// At this point the process should be started,
// so we answer the HTTP call
plotterLastOutput = "printing...";
plotterAuthor = req.sid;
res.send({status: "success"});
});
});
}
const plotterStatus = (req, res) => {
const busy = plotterReader !== undefined && plotterReader !== true;
return res.json({
"busy": busy,
"last_output" : plotterLastOutput,
"author": plotterAuthor,
"sizeCur": plotterSizeCur,
"sizeTotal": plotterSizeTotal,
"paused": busy && plotterReader.isPaused(),
});
}
const plotterPause = (req, res) => {
if (plotterReader === undefined || plotterReader === true) {
return res.status(409).send("Not running");
}
plotterLastOutput = "paused";
plotterReader.pause();
return res.send({ status: "success" });
}
const plotterResume = (req, res) => {
if (plotterReader === undefined || plotterReader === true) {
return res.status(409).send("Not running");
}
plotterLastOutput = "printing...";
plotterReader.resume();
return res.send({ status: "success" });
}
const plotterStop = (req, res) => {
if (plotterReader === undefined || plotterReader === true) {
return res.status(409).send("Not running");
}
plotterLastOutput = "stopped";
plotterReader.close();
return res.send({ status: "success" });
}
const randomID = () => {
var length = 12;
var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz'.split('');
var str = '';
for (var i = 0; i < length; i++) {
str += chars[Math.floor(Math.random() * chars.length)];
}
return str;
}
app.map({
"/": { get: (req, res) => { res.redirect(`/app/${randomID()}`); } },
"/app/:sid([_a-zA-Z0-9]{1,32})": {
get: (req, res) => { res.sendFile(path.join(__dirname, "html/index.html")); },
"/original/:code?": { get: (req, res) => {
res.setHeader("Content-Type", "image/svg+xml");
res.sendFile(path.join(req.basePath, "image.svg"));
} },
"/preview/:code?": { get: (req, res) => {
res.setHeader("Content-Type", "image/svg+xml");
res.sendFile(path.join(req.basePath, "vis.svg"));
} },
"/upload": { post: upload },
"/render_svg": { post: renderSVG },
"/run/:target": { get: plotterRun }
},
"/plotter": {
"/status": { get: plotterStatus }, // TODO: current session and filename
"/stop": { get: plotterStop },
"/pause": { get: plotterPause },
"/resume": { get: plotterResume },
}
})
const port = process.env.PORT || 8080
app.listen(port, "127.0.0.1", (err) => {
if(err) throw err;
console.log("listening on port " + port);
})