forked from LJNGDAHL/robotkodarn-chrome-app
-
Notifications
You must be signed in to change notification settings - Fork 1
/
background.js
121 lines (92 loc) · 2.81 KB
/
background.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
const uploader = require('./lib/flash');
const serial = require('./lib/serial');
const Avrgirl = require('avrgirl-arduino');
const customBoards = require('./lib/boards');
const checkZumoBootloaderMode = (done) => {
let retries = 30;
const performCheck = () => {
Avrgirl.list((error, ports) => {
if(error) return done(error.message);
const zumoBootPort = ports.filter((port) => port.productId === '0x101' && port.comName.indexOf("tty") > -1).length;
retries--;
if(!zumoBootPort) {
// Send back the status of the flash to the webpage so it knows when it's done/errored.
done();
} else if(retries <= 0) {
done('timeout');
} else {
setTimeout(() => performCheck(), 1000);
}
});
}
performCheck();
};
/**
* When the webpage sends a message and we recive it,
* pass info to uploader and request a flash to the device.
*/
chrome.runtime.onConnectExternal.addListener(port => {
port.onMessage.addListener(msg => {
switch (msg.type) {
// If the message type is flash
case 'flash':
serial.close(() => {
let board = msg.board;
if(msg.board in customBoards) {
board = customBoards[msg.board];
}
// Call flash process
uploader.flash(board, msg.file, error => {
// Prepare the response object
let message = error ? { error: error.message } : { success: true };
if(error) return port.postMessage(message);
const done = (error) => {
if(error) message = {error};
port.postMessage(message);
}
checkZumoBootloaderMode(done);
});
});
break;
// If the message type is ping
case 'ping':
port.postMessage({
success: true
});
break;
// If the message type is list
case 'list':
Avrgirl.list((error, ports) => {
const message = error ? { error: error } : { usbPorts: ports };
port.postMessage(message);
});
break;
case 'serial':
serial.close(() => {
serial.listen({
board: msg.board,
baudrate: msg.baudrate
}, (error, data) => {
if(error) {
const message = {error};
console.log(`failed to open: ${error.message}`)
return port.postMessage(message);
}
port.postMessage({
serialData: new TextDecoder("utf-8").decode(data)
});
});
});
break;
case 'version':
const version = chrome.runtime.getManifest().version;
port.postMessage({
version
});
break;
default:
console.log( 'Recieved ' + msg)
break;
}
});
});