forked from espruino/BangleApps
-
Notifications
You must be signed in to change notification settings - Fork 0
/
apploader.js
executable file
·255 lines (233 loc) · 7.3 KB
/
apploader.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
#!/usr/bin/nodejs
/* Simple Command-line app loader for Node.js
===============================================
NOTE: This needs the '@abandonware/noble' library to be installed.
However we don't want this in package.json (at least
as a normal dependency) because we want `sanitycheck.js`
to be able to run *quickly* in travis for every commit,
and we don't want NPM pulling in (and compiling native modules)
for Noble.
*/
var SETTINGS = {
pretokenise : true
};
var Utils = require("../js/utils.js");
var AppInfo = require("../js/appinfo.js");
var noble;
try {
noble = require('@abandonware/noble');
} catch (e) {}
if (!noble) try {
noble = require('noble');
} catch (e) { }
if (!noble) {
console.log("You need to:")
console.log(" npm install @abandonware/noble")
console.log("or:")
console.log(" npm install noble")
}
var apps;
function ERROR(msg) {
console.error(msg);
process.exit(1);
}
try {
apps = JSON.parse(require("fs").readFileSync(__dirname+"/../apps.json"));
} catch(e) {
ERROR("'apps.json' could not be loaded");
}
var args = process.argv;
if (args.length==3 && args[2]=="list") cmdListApps();
else if (args.length==3 && args[2]=="devices") cmdListDevices();
else if (args.length==4 && args[2]=="install") cmdInstallApp(args[3]);
else if (args.length==5 && args[2]=="install") cmdInstallApp(args[3], args[4]);
else {
console.log(`apploader.js
-------------
USAGE:
apploader.js list
- list available apps
apploader.js devices
- list available device addresses
apploader.js install appname [de:vi:ce:ad:dr:es]
`);
process.exit(0);
}
function cmdListApps() {
console.log(apps.map(a=>a.id).join("\n"));
}
function cmdListDevices() {
var foundDevices = [];
noble.on('discover', function(dev) {
if (!dev.advertisement) return;
if (!dev.advertisement.localName) return;
var a = dev.address.toString();
if (foundDevices.indexOf(a)>=0) return;
foundDevices.push(a);
console.log(a,dev.advertisement.localName);
});
noble.startScanning([], true);
setTimeout(function() {
noble.stopScanning();
}, 2000);
}
function cmdInstallApp(appId, deviceAddress) {
var app = apps.find(a=>a.id==appId);
if (!app) ERROR(`App ${JSON.stringify(appId)} not found`);
if (app.custom) ERROR(`App ${JSON.stringify(appId)} requires HTML customisation`);
return AppInfo.getFiles(app, {
fileGetter:function(url) {
return Promise.resolve(require("fs").readFileSync(url).toString());
}, settings : SETTINGS}).then(files => {
//console.log(files);
var command = files.map(f=>f.cmd).join("\n")+"\n";
bangleSend(command, deviceAddress).then(() => process.exit(0));
});
}
function bangleSend(command, deviceAddress) {
var log = function() {
var args = [].slice.call(arguments);
console.log("UART: "+args.join(" "));
}
var RESET = true;
var DEVICEADDRESS = "";
if (deviceAddress!==undefined)
DEVICEADDRESS = deviceAddress;
var complete = false;
var foundDevices = [];
var flowControlPaused = false;
var btDevice;
var txCharacteristic;
var rxCharacteristic;
return new Promise((resolve,reject) => {
function foundDevice(dev) {
if (btDevice!==undefined) return;
log("Connecting to "+dev.address);
noble.stopScanning();
connect(dev, function() {
// Connected!
function writeCode() {
log("Writing code...");
write(command, function() {
complete = true;
btDevice.disconnect();
});
}
if (RESET) {
setTimeout(function() {
log("Resetting...");
write("\x03\x10reset()\n", function() {
setTimeout(writeCode, 1000);
});
}, 500);
} else
setTimeout(writeCode, 1000);
});
}
function connect(dev, callback) {
btDevice = dev;
log("BT> Connecting");
btDevice.on('disconnect', function() {
log("Disconnected");
setTimeout(function() {
if (complete) resolve();
else reject("Disconnected but not complete");
}, 500);
});
btDevice.connect(function (error) {
if (error) {
log("BT> ERROR Connecting",error);
btDevice = undefined;
return;
}
log("BT> Connected");
btDevice.discoverAllServicesAndCharacteristics(function(error, services, characteristics) {
function findByUUID(list, uuid) {
for (var i=0;i<list.length;i++)
if (list[i].uuid==uuid) return list[i];
return undefined;
}
var btUARTService = findByUUID(services, "6e400001b5a3f393e0a9e50e24dcca9e");
txCharacteristic = findByUUID(characteristics, "6e400002b5a3f393e0a9e50e24dcca9e");
rxCharacteristic = findByUUID(characteristics, "6e400003b5a3f393e0a9e50e24dcca9e");
if (error || !btUARTService || !txCharacteristic || !rxCharacteristic) {
log("BT> ERROR getting services/characteristics");
log("Service "+btUARTService);
log("TX "+txCharacteristic);
log("RX "+rxCharacteristic);
btDevice.disconnect();
txCharacteristic = undefined;
rxCharacteristic = undefined;
btDevice = undefined;
return openCallback();
}
rxCharacteristic.on('data', function (data) {
var s = "";
for (var i=0;i<data.length;i++) {
var ch = data[i];
if (ch==19) {
log("XOFF");
flowControlPaused = 200;
} else if (ch==17) {
log("XON");
flowControlPaused = false;
} else
s+=String.fromCharCode(ch);
}
log("Received", JSON.stringify(s));
});
rxCharacteristic.subscribe(function() {
callback();
});
});
});
};
function write(data, callback) {
var amt = 0;
var total = data.length;
var progress=0;
function writeAgain() {
if (flowControlPaused) {
flowControlPaused--;
if (flowControlPaused==0)
log("TIMEOUT - sending");
setTimeout(writeAgain,50);
return;
}
if (!data.length) return callback();
var d = data.substr(0,20);
data = data.substr(20);
var buf = new Buffer(d.length);
progress++;
if (progress>=10) {
log("Writing "+amt+"/"+total);
progress=0;
}
//log("Writing ",JSON.stringify(d));
amt += d.length;
for (var i = 0; i < buf.length; i++)
buf.writeUInt8(d.charCodeAt(i), i);
txCharacteristic.write(buf, false, writeAgain);
}
writeAgain();
}
function disconnect() {
btDevice.disconnect();
}
log("Discovering...");
noble.on('discover', function(dev) {
if (!dev.advertisement) return;
if (!dev.advertisement.localName) return;
var a = dev.address.toString();
if (foundDevices.indexOf(a)>=0) return;
foundDevices.push(a);
log("Found device: ",a,dev.advertisement.localName);
if (a == DEVICEADDRESS)
return foundDevice(dev);
else if (DEVICEADDRESS=="" && dev.advertisement.localName.indexOf("Bangle.js")==0) {
return foundDevice(dev);
}
});
noble.startScanning([], true);
});
}