-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
101 lines (83 loc) · 2.36 KB
/
server.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
/**
*
*/
const { exec } = require('child_process');
const SerialPort = require('serialport');
const process = require('process');
const path = require('path');
const express = require('express');
const app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http);
const multer = require('multer');
const upload = multer({ dest: '/tmp/' });
const PORT = 5000;
const PAYLOAD = 'PAYLOAD';
const MODEM = 'MODEM';
const PAYLOAD_PORT = process.argv[2];
const MODEM_PORT = process.argv[3];
// server
/**
* Serve static files
*/
app.use(express.static('.'));
/**
* Firmware upload endpoint
*/
app.post('/firmware', upload.single('firmware'), (req, res) => {
const { filename } = req.file;
const { device } = req.body;
flashFirmware(path.join('/tmp', filename), device)
.then(({ stdout, stderr }) => {
res.json({ stdout, stderr });
})
.catch(err => {
res.error({ error: err })
});
});
io.on('connection', socket => {
console.log('new client');
});
http.listen(PORT, function(){
console.log('listening on *:' + PORT);
});
// serial comms
let payloadPort = new SerialPort(PAYLOAD_PORT, { baudRate: 57600, });
let modemPort = new SerialPort(MODEM_PORT, { baudRate: 57600, });
payloadPort.on('data', data => {
io.sockets.emit('payload-log', data.toString());
});
modemPort.on('data', data => {
io.sockets.emit('modem-log', data.toString());
});
// flashing
function flashFirmware(filename, device) {
return new Promise((resolve, reject) => {
payloadPort.close(err => {
if (err)
return reject(err);
filename = '/var/folders/ph/nzyskt3x6h7fvz00ry339k0c0000gn/T/arduino_build_771952/Payload.ino.hex'
const cmd = `avrdude ` +
`-vvv ` +
`-patmega328p ` +
`-carduino ` +
`-P${device === PAYLOAD ? PAYLOAD_PORT : MODEM_PORT} ` +
`-b115200 ` +
`-D ` +
`-Uflash:w:${filename}:i`;
exec(cmd, (err, stdout, stderr) => {
if (err) {
return reject(err);
}
console.log(stdout);
console.log(stderr);
// reopen the serial connection after flashing
payloadPort = new SerialPort(PAYLOAD_PORT, { baudRate: 57600, });
payloadPort.on('data', data => {
io.sockets.emit('payload-log', data.toString());
});
resolve({ stdout, stderr });
});
});
});
}