-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
636 lines (584 loc) · 20.7 KB
/
index.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
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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
const { SerialPort } = require('serialport')
const Avrgirl = require("@sienci/avrgirl-arduino");
const { app, BrowserWindow, ipcMain, nativeTheme, Tray, Menu, dialog, shell} = require("electron");
const Store = require('electron-store');
const store = new Store();
const path = require("path");
const parts = require("./parts.json");
const layouts = require("./layouts.json");
const supportedVersions = require("./supportedVersions.json");
const {usb} = require('usb');
const { readFileSync } = require('fs');
const { join } = require('path');
const fs = require("fs");
const AdmZip = require("adm-zip");
const PluginManager = require("./plugins")
const {autoUpdater} = require("electron-updater");
const os = require("os");
let mainWindow;
const processLock = app.requestSingleInstanceLock();
let tray = null;
if (!processLock){
app.quit()
}
else{
app.on('second-instance', () => {
mainWindow.show();
});
}
onFirstRun();
initializeStores();
global.devices = store.get("devices");
let serialPorts = {};
for (let i = 0; i < devices.length; i++){
devices[i].status = "disconnected";
}
let colorTheme = store.get("colorTheme");
nativeTheme.themeSource = colorTheme;
global.userMacros = store.get("userMacros");
function onFirstRun(){
if (!store.has("first-run")){
setOpenAtLogin(null, true);
store.set("first-run", true);
}
}
function initializeStores(){
if (!store.has("devices")){
store.set("devices", []);
}
if (!store.has("colorTheme")){
store.set("colorTheme", "system")
}
if (!store.has("userMacros")){
store.set("userMacros", []);
}
if (!store.has("installedPlugins")){
store.set("installedPlugins", []);
}
if (!store.has("autoUpdateFirmware")){
store.set("autoUpdateFirmware", true);
}
}
function addPluginDialog(){
let selected = dialog.showOpenDialogSync(mainWindow, {
properties: ['openFile'],
filters: [{name: "Mimacro Extensions", extensions:["zip"]}]
});
if (!selected){
return null;
}
try{
let pluginZip = new AdmZip(selected[0]);
let packageJson = JSON.parse(pluginZip.readAsText("package.json"));
packageJson.path = selected[0];
pluginZip.extractEntryTo(packageJson.icon, "temp", true, true);
console.log(packageJson)
return packageJson;
}
catch (e){
console.log(e)
return false;
}
}
function flashDevice(event, index){
if (serialPorts[index].isOpen){
serialPorts[index].close();
}
devices[index].status = "updating";
refreshRendererDevices();
// Delay to ensure port is closed
setTimeout(()=>{
if (devices[index].mimacroType === "Arduino Uno"){
let avrgirl = new Avrgirl(
{
board: "uno",
port: devices[index].port
}
);
avrgirl.flash(join(app.getAppPath(), "/public/firmware/arduino/uno/build/arduino.avr.uno/uno.ino.hex"), function(e){
setTimeout(()=>{
refreshDevices();
if (e){
console.log(e);
mainWindow.webContents.send("flashResult", false);
}
else{
console.log("Flash complete.");
mainWindow.webContents.send("flashResult", true);
}
}, 5000)
});
}
}, 1000);
}
function flashPort(event, port, type){
if (type === "Arduino Uno"){
console.log(port)
let avrgirl = new Avrgirl(
{
board: "uno",
port: port
}
);
try{
avrgirl.flash(join(app.getAppPath(), "/public/firmware/arduino/uno/build/arduino.avr.uno/uno.ino.hex"), function(e){
if (e){
console.log(e);
mainWindow.webContents.send("portFlashResult", false);
}
else{
console.log("Flash complete.");
setTimeout(() => {let tempPort = new SerialPort({path: port, baudRate: 9600});
tempPort.write("MEMRESET\n");
setTimeout(() => {if (tempPort.isOpen){
tempPort.close();
}}, 1000);}, 4000);
setTimeout(()=> {
mainWindow.webContents.send("portFlashResult", true);
}, 15000);
}
});
}
catch (e) {
console.log(e);
mainWindow.webContents.send("portFlashResult", false);
}
}
}
// Detect mimacro and Arduino devices.
function autoDetectPorts(callback, timeout){
let detectedPorts = {
"mimacro": [],
"uno": [],
"other": []
}
let closePorts = [];
SerialPort.list().then(
(ports) => {
ports.forEach((port) => {
if (deviceExists(port.serialNumber)){
return;
}
port.mimacroVersion = "Not installed."
if (port.friendlyName.includes("Uno")){
port.looksCompatible = true;
port.mimacroType = "Arduino Uno";
port.flashed = false;
detectedPorts["uno"].push(port);
autoDetectListener(port, detectedPorts, closePorts, "uno");
}
else{
port.looksCompatible = false;
port.flashed = false;
port.mimacroType = "Unknown";
detectedPorts["other"].push(port);
}
});
}
);
setTimeout(function(){
for (let i = 0; i < closePorts.length; i++){
try{
if (closePorts[i].isOpen){
closePorts[i].close();
}
console.log(closePorts[i].isOpen)
}
catch(e){
console.log(e);
}
}
callback(detectedPorts);
}, timeout);
}
function deviceExists(serial){
for (let i = 0; i < devices.length; i++){
if (devices[i].serialNumber === serial){
return true;
}
}
return false;
}
// Checks if arduino at port has mimacro software flashed.
function autoDetectListener(port, detectedPorts, closePorts, deviceType){
try{
let sp = new SerialPort({path: port.path, baudRate: 9600});
let temp = "";
let isMimacro = false;
let line = 0;
let index = 0;
sp.on("data", function (data){
temp += data.toString();
// Runs when data is done being received
if (data.toString().includes("\n")){
line++;
temp = temp.split("\n")[0].replace("\r", "");
if (temp === "mimacro" && line === 1){
port.flashed = true;
isMimacro = true;
detectedPorts[deviceType].splice(detectedPorts[deviceType].indexOf(port), 1);
detectedPorts["mimacro"].push(port);
index = detectedPorts["mimacro"].indexOf(port);
}
if (isMimacro && line === 2){
detectedPorts["mimacro"][index].mimacroVersion = temp;
}
temp = data.toString().split("\n")[1];
}
});
closePorts.push(sp);
}
catch(e){
}
}
function sendAutoPorts(ports){
mainWindow.webContents.send("autoDetectResult", ports)
}
function addDevice(device){
device.status = "disconnected";
devices.push(device);
store.set("devices", devices)
refreshDevices();
refreshRendererDevices();
}
function removeDevice(event, deviceIndex){
devices.splice(deviceIndex, 1);
store.set("devices", devices);
try{
if (serialPorts[deviceIndex].isOpen){
serialPorts[deviceIndex].close()
}
}
catch(e){
console.log(e);
}
refreshRendererDevices();
}
function renameDevice(event, deviceIndex, deviceName){
devices[deviceIndex].nickname = deviceName;
store.set("devices", devices);
refreshRendererDevices();
}
function getDevices(){
return devices;
}
function setColorTheme(event, mode){
colorTheme = mode;
store.set("colorTheme", mode);
nativeTheme.themeSource = mode;
}
function connectToDevices(){
let serialNumbers = [];
for (let i = 0; i < devices.length; i++){
serialNumbers.push(devices[i].serialNumber);
}
SerialPort.list().then((ports) => {
for (let i = 0; i < ports.length; i++){
if (serialNumbers.includes(ports[i].serialNumber)){
listenToDevice(serialNumbers.indexOf(ports[i].serialNumber), ports[i].path);
}
}
})
}
function refreshRendererDevices(){
mainWindow.webContents.send("refreshDevices");
}
function listenToDevice(index, devicePath){
let thisDevice = devices[index];
devices[index].port = devicePath;
devices[index].pinOut = {}
devices[index].pinProperties = {
"digital": {},
"analog": {}
}
let sp = new SerialPort({path: devicePath, baudRate: 9600});
serialPorts[index] = sp;
console.log(thisDevice.nickname);
let temp = "";
let line = 0;
let outdated = false;
sp.on("data", function (data){
temp += data.toString();
// Runs when data is done being received
if (data.toString().includes("\n")){
if (temp === "MEMRESET"){
return;
}
if (line < 8){
line++;
}
temp = temp.split("\n")[0].replace("\r", "");
if (devices[index].status === "connected"){
PluginManager.handleTriggers(temp, devices[index]);
}
if (line === 2){
devices[index].mimacroVersion = temp;
if (!supportedVersions.includes(devices[index].mimacroVersion)){
outdated = true;
if (sp.isOpen){
sp.close()
}
// Automatically update an outdated device.
if (store.get("autoUpdateFirmware")){
setTimeout(()=>{
flashDevice(null, index);
}, 5000)
}
}
}
if (line === 3){
devices[index].pinOut.digital = temp.split(", ").map(Number);
}
if (line === 4){
devices[index].pinOut.analog = temp.split(", ").map(Number);
}
if (line === 5){
devices[index].pinProperties.digital.timeout = temp.split(", ").map(Number);
}
if (line === 6){
devices[index].pinProperties.analog.timeout = temp.split(", ").map(Number);
}
if (line === 7){
devices[index].pinProperties.analog.minChange = temp.split(", ").map(Number);
devices[index].status = "connected";
store.set("devices", devices);
refreshRendererDevices();
}
temp = data.toString().split("\n")[1];
}
});
let onCloseListener = () => {
if (outdated){
devices[index].status = "outdated";
}
else if (devices[index].status !== "updating"){
devices[index].status = "disconnected";
}
refreshRendererDevices();
sp.removeListener("close", onCloseListener);
}
sp.on("close", onCloseListener);
}
function deviceOpen(device){
for (let j = 0; j < devices.length; j++){
if (device.serialNumber === devices[j].serialNumber){
console.log(devices[j].status)
if (devices[j].status === "connected"){
console.log("yes yes")
return true;
}
}
}
return false;
}
function refreshDevices(){
SerialPort.list().then((ports) => {
let serialNumbers = [];
for (let i = 0; i < devices.length; i++){
serialNumbers.push(devices[i].serialNumber);
}
for (let i = 0; i < ports.length; i++){
if (serialNumbers.includes(ports[i].serialNumber)) {
if (!deviceOpen(serialNumbers.indexOf(ports[i].serialNumber))) {
listenToDevice(serialNumbers.indexOf(ports[i].serialNumber), ports[i].path);
}
}
}
});
}
function writeDevice(event, device, message){
serialPorts[device].write(message+"\n", ()=>{});
}
function setDevicePinOut(event, device, config){
let pinMod = 0;
for (let i = 0; i < config.digital.length; i++){
if (config.digital[i] !== String(devices[device].pinOut.digital[i])){
console.log("DPIN S " + String(layouts[devices[device].mimacroType]["digital"][i]+pinMod).padStart(2, "0") + " " + String(config.digital[i]).padStart(2, "0"))
writeDevice(null, device, "DPIN S " + String(layouts[devices[device].mimacroType]["digital"][i]+pinMod).padStart(2, "0") + " " + String(config.digital[i]).padStart(2, "0"))
}
}
// TODO
// Modify pin code for Arduino software (temp solution)
pinMod = 0;
if (devices[device].mimacroType === "Arduino Uno"){
pinMod = -14;
}
for (let i = 0; i < config.analog.length; i++){
if (config.analog[i] !== String(devices[device].pinOut.analog[i])){
console.log("APIN S " + String(layouts[devices[device].mimacroType]["analog"][i]+pinMod).padStart(2, "0") + " " + String(config.analog[i]).padStart(2, "0"))
writeDevice(null, device, "APIN S " + String(layouts[devices[device].mimacroType]["analog"][i]+pinMod).padStart(2, "0") + " " + String(config.analog[i]).padStart(2, "0"))
}
}
devices[device].pinOut = config;
refreshRendererDevices();
}
function setDevicePinProperties(event, device, config){
for (let i = 0; i < config.digital.timeout.length; i++){
let newConf = config.digital.timeout[i];
if (newConf !== devices[device].pinProperties.digital.timeout[i]){
console.log("DPIN T " + String(layouts[devices[device].mimacroType]["digital"][i]).padStart(2, "0") + " " + String(config.digital.timeout[i]).padStart(3, "0"))
writeDevice(null, device, "DPIN T " + String(layouts[devices[device].mimacroType]["digital"][i]).padStart(2, "0") + " " + String(config.digital.timeout[i]).padStart(3, "0"))
}
}
// TODO
// Modify pin code for Arduino software (temp solution)
let pinMod = 0;
if (devices[device].mimacroType === "Arduino Uno"){
pinMod = -14;
}
for (let i = 0; i < config.analog.timeout.length; i++){
let newConf = config.analog.timeout[i];
if (newConf !== devices[device].pinProperties.analog.timeout[i]){
console.log("APIN T " + String(layouts[devices[device].mimacroType]["analog"][i]+pinMod).padStart(2, "0") + " " + String(config.analog.timeout[i]).padStart(3, "0"))
writeDevice(null, device, "APIN T " + String(layouts[devices[device].mimacroType]["analog"][i]+pinMod).padStart(2, "0") + " " + String(config.analog.timeout[i]).padStart(3, "0"))
}
}
for (let i = 0; i < config.analog.minChange.length; i++){
let newConf = config.analog.minChange[i];
if (newConf !== devices[device].pinProperties.analog.minChange[i]){
console.log("APIN V " + String(layouts[devices[device].mimacroType]["analog"][i]+pinMod).padStart(2, "0") + " " + String(config.analog.minChange[i]).padStart(3, "0"))
writeDevice(null, device, "APIN V " + String(layouts[devices[device].mimacroType]["analog"][i]+pinMod).padStart(2, "0") + " " + String(config.analog.minChange[i]).padStart(3, "0"))
}
}
devices[device].pinProperties = config;
}
usb.on('attach', () => {
refreshDevices();
});
function saveMacro(event, macro){
global.userMacros.push(JSON.parse(macro));
store.set("userMacros", global.userMacros);
}
function setMacros(event, macros) {
global.userMacros = JSON.parse(macros);
store.set("userMacros", global.userMacros);
}
function removeMacro(event, uuid) {
global.userMacros = userMacros.filter(macro => macro.uuid !== uuid);
store.set("userMacros", global.userMacros);
}
function getMacros(){
return global.userMacros;
}
function setOpenAtLogin(event, shouldRun){
app.setLoginItemSettings({
openAtLogin: shouldRun
});
}
function getOpenAtLogin(){
return app.getLoginItemSettings().openAtLogin;
}
function getAutoUpdateFirmware(){
return store.get("autoUpdateFirmware");
}
function setAutoUpdateFirmware(event, value){
store.set("autoUpdateFirmware", value);
}
function getAllActions(){
let allActions = PluginManager.fireEvent("onGetActions")
let fullList = [];
for (let i = 0; i < allActions.length; i++){
if (allActions[i] !== undefined){
fullList = fullList.concat(allActions[i]);
}
}
return fullList;
}
function openLinkInBrowser(event, link){
shell.openExternal(link);
}
function isAppBundled(){
return app.getAppPath().endsWith(".asar");
}
function installUpdates(){
if (os.platform() !== "win32"){
openLinkInBrowser(null, "https://github.com/atticuscornett/mimacro/releases/latest");
return;
}
autoUpdater.checkForUpdates();
autoUpdater.on("update-downloaded", () => {
autoUpdater.quitAndInstall();
});
}
connectToDevices();
global.writeDevice = writeDevice;
ipcMain.on("autoDetectDevices", () => autoDetectPorts(sendAutoPorts, 5000))
ipcMain.on("addDevice", (event, device) => addDevice(device));
ipcMain.handle("getDevices", getDevices);
ipcMain.handle("setColorTheme", setColorTheme);
ipcMain.handle("getColorTheme", () => {return colorTheme;})
ipcMain.handle("saveMacro", saveMacro);
ipcMain.handle("setMacros", setMacros);
ipcMain.handle("getMacros", getMacros);
ipcMain.handle("removeMacro", removeMacro);
ipcMain.handle("getLayouts", ()=>{return layouts;});
ipcMain.handle("getParts", ()=>{return parts;});
ipcMain.handle("removeDevice", removeDevice);
ipcMain.handle("renameDevice", renameDevice);
ipcMain.handle("flashDevice", flashDevice);
ipcMain.handle("flashPort", flashPort);
ipcMain.handle("writeDevice", writeDevice);
ipcMain.handle("setDevicePinOut", setDevicePinOut);
ipcMain.handle("setDevicePinProperties", setDevicePinProperties);
ipcMain.handle("getInstalledPlugins", PluginManager.getInstalledPlugins);
ipcMain.handle("enablePlugin", PluginManager.enablePlugin);
ipcMain.handle("disablePlugin", PluginManager.disablePlugin);
ipcMain.handle("uninstallPlugin", PluginManager.uninstallPlugin);
ipcMain.handle("addPluginDialog", addPluginDialog);
ipcMain.handle("addPluginFromFile", PluginManager.addPluginFromFile);
ipcMain.handle("setOpenAtLogin", setOpenAtLogin);
ipcMain.handle("getOpenAtLogin", getOpenAtLogin);
ipcMain.handle("setAutoUpdateFirmware", setAutoUpdateFirmware);
ipcMain.handle("getAutoUpdateFirmware", getAutoUpdateFirmware);
ipcMain.handle("getPluginREADME", PluginManager.getPluginREADME);
ipcMain.handle("getPlugin", (event, packageName)=>{return JSON.parse(JSON.stringify(PluginManager.getPlugin(packageName)))});
ipcMain.handle("getPluginSettings", PluginManager.getPluginSettings);
ipcMain.handle("setPluginSettings", PluginManager.setPluginSettings);
ipcMain.handle("getLoadedPlugins", PluginManager.getLoadedPlugins);
ipcMain.handle("getAllActions", getAllActions);
ipcMain.handle("openLinkInBrowser", openLinkInBrowser);
ipcMain.handle("isAppBundled", isAppBundled);
ipcMain.handle("getAppVersion", app.getVersion);
ipcMain.handle("installUpdates", installUpdates);
app.on("ready", () => {
tray = new Tray(__dirname + "/icon.png");
tray.setToolTip("mimacro");
const trayMenuTemplate = [{
label: 'mimacro',
enabled: true,
click: () => {
mainWindow.show()
}
},
{
label: 'Quit',
enabled: true,
click: () => {
PluginManager.fireEvent("onDisable");
app.quit()
process.exit(0);
}
}
];
let trayMenu = Menu.buildFromTemplate(trayMenuTemplate)
tray.setContextMenu(trayMenu);
tray.on('click', function(){
mainWindow.show()
}
);
mainWindow = new BrowserWindow({
webPreferences: {
preload: path.join(__dirname, "preload.js")
},
autoHideMenuBar: true,
minWidth: 800,
minHeight: 600,
icon: __dirname + "/icon.png",
show: !getOpenAtLogin()
});
mainWindow.on('close', e => {
e.preventDefault();
mainWindow.hide();
});
mainWindow.loadFile(path.join(__dirname, "public/index.html"));
});