-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
463 lines (392 loc) · 13.2 KB
/
main.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
// Imports
const {config} = require('./config');
const {app, BrowserWindow, Menu, ipcMain, nativeTheme} = require('electron');
const window = require('electron').BrowserWindow;
const path = require('path');
const fs = require('fs');
if (require('electron-squirrel-startup')) return;
// this should be placed at top of main.js to handle setup events quickly
if (handleSquirrelEvent(app)) {
// squirrel event handled and app will exit in 1000ms, so don't do anything else
return;
}
// Set exports
exports.mode = 'light';
exports.savePath = app.getPath('documents');
exports.appConfigPath = app.getPath('userData');
if(nativeTheme.shouldUseDarkColors){
exports.mode = 'dark';
}
let session = {};
let globalMap = [];
let d;
let sessionTimestamp;
let currentIdx;
var sessionSavePath = path.join(app.getPath('documents'), './Nautilus/');
function initSession() {
session = {};
d = new Date();
sessionTimestamp = d.getFullYear() + '_' + d.getMonth() + '_' + d.getDate() + '_' + d.getHours() + '_' + d.getMinutes() + '_' + d.getSeconds();
currentIdx = 0;
}
initSession();
var trackMap = [];
// Set global variables
var connectedToCloud = false;
var connectedToSer = false;
var fetchDataFromSer = true;
var cloudURL = ''
var serPortName = '';
const _sharedObj = {config:config,
session:session,
trackMap:trackMap,
sessionSavePath:sessionSavePath,
cloudURL:cloudURL,
connectedToCloud:connectedToCloud,
connectedToSer:connectedToSer,
serPortName:serPortName,
globalMap:globalMap
};
global.sharedObj = _sharedObj;
try {
let newConfig = JSON.parse(fs.readFileSync(path.join(exports.appConfigPath, './config.json'), 'utf8'));
global.sharedObj.config = newConfig;
console.log("Continuing last session.");
}catch (err){
console.log(err);
console.log("Couldn't load last session.");
}
// Set environment
process.env.NODE_ENV = 'development';
// Cloud Connection
var cloudURL = '';
// Set main process variables
var mainWindow;
var port;
var parser;
var data;
var socket;
// Listen for app to be ready
app.on('ready', function() {
mainWindow = new BrowserWindow({
webPreferences: {
// Enable Node.js integration
nodeIntegration: true,
},
width: 800,
height:700,
icon: __dirname + '/templates/assets/img/Nautilus.ico'
});
// Load html into window
let url = require('url');
mainWindow.loadURL(url.format({
pathname: path.join(__dirname, 'templates/dashboard.html'),
protocol:'file:',
slashes: true
}));
mainWindow.setBackgroundColor('#050715');
mainWindow.once('ready-to-show', function (){
mainWindow.show();
mainWindow.focus();
});
mainWindow.on('closed', function() {
try{
socket.disconnect();
}catch (err) {
console.log("Already disconnected");
}
try {
let mkdirp = require('mkdirp');
var tempPath = sessionSavePath + sessionTimestamp + '.json'
mkdirp(sessionSavePath);
fs.writeFileSync(tempPath, JSON.stringify(session));
}catch (err){
console.log(err);
console.log("Couldn't save session.");
}
console.log('Saving to: ', path.join(exports.appConfigPath, './config.json'))
fs.writeFile(path.join(app.getPath('userData'), './config.json'),
JSON.stringify(global.sharedObj.config),
{ flag: 'w' },
(err) => {
console.log(err)
}
);
});
// Build menu from template
const mainMenu = Menu.buildFromTemplate(mainMenuTemplate);
// Insert menu
Menu.setApplicationMenu(mainMenu);
});
// Create new template
const mainMenuTemplate = [
{
label:'Actions',
submenu:[
{
label: 'Settings',
accelerator: process.platform == 'darwin' ? 'Command+D' : 'Ctrl+D',
click() {
mainWindow.webContents.send('action-port', 'clicked');
}
},
{
role: 'reload'
},
{
label: 'Quit',
accelerator: process.platform == 'darwin' ? 'Command+Q' : 'Ctrl+Q',
click() {
app.quit();
}
}
]
}
];
// If mac, add empty object to menu
if(process.platform == 'darwin') {
mainMenuTemplate.unshift({});
}
// Add developer tools if not in production
if(process.env.NODE_ENV !== 'production') {
mainMenuTemplate.push({
label: 'Developer Tools',
submenu : [
{
label: 'Toggle DevTools',
accelerator: process.platform == 'darwin' ? 'Command+I' : 'Ctrl+I',
click(item, focusedWindow) {
focusedWindow.toggleDevTools();
}
}
]
})
}
// Handle change COM Port
exports.handleForm = function handleForm(targetWindow, com_port) {
try{
try{
port.close();
}catch (_) {
console.log("Already disconnected.");
}
// Set serial port
let SerialPort = require('serialport');
port = null;
parser = null;
port = new SerialPort(com_port, {
baudRate: 9600,
flowControl: false,
parser: new SerialPort.parsers.Readline("\n")
});
// Set serial port handlers
parser = new SerialPort.parsers.Readline();
port.pipe(parser);
port.on('close', function() {
port = null;
parser = null;
});
parser.on('data', function(data) {
data = data.split(',');
if(data[2] > currentIdx) {
currentIdx++;
session[currentIdx] = [];
let focusedWindow = window.getAllWindows()[0];
exports.handleSaveSession(focusedWindow);
}
if(session[currentIdx] == undefined) {
session[currentIdx] = []
}
session[currentIdx].push(data);
if(fetchDataFromSer) {
mainWindow.webContents.send('ser-data', data);
}
});
fetchDataFromSer = true;
global.sharedObj.connectedToCloud = false;
global.sharedObj.connectedToSer = true;
global.sharedObj.serPortName = com_port;
targetWindow.webContents.send('form-received', com_port);
}catch {
targetWindow.webContents.send('form-not-received', com_port);
}
};
exports.handleNewSession = function handleNewSession(targetWindow) {
initSession();
targetWindow.webContents.send('new-session-success');
}
exports.handleConnectToCloud = function handleConnectToCloud(targetWindow, url) {
try{
port.close();
}catch (_) {
console.log("Already disconnected.");
}
url = 'http://' + url;
global.sharedObj.connectedToCloud = true;
global.sharedObj.connectedToSer = false;
fetchDataFromSer = false;
cloudURL = url;
global.sharedObj.cloudURL = url;
// Create socket connection
const io = require('socket.io-client');
socket = io.connect(cloudURL, {
'reconnection': true,
'reconnectionDelay': 500,
'reconnectionAttempts': 100
});
console.log(cloudURL);
socket.on('connect', function() {
socket.emit('join', "{'room':'DJSR'}");
let focusedWindow = window.getAllWindows()[0];
focusedWindow.webContents.send('cloud-connection-success');
});
socket.on('response', function(data) {
console.log("Joined a room!");
});
socket.on('data', function(data) {
if(data['data_string'][2] > currentIdx) {
currentIdx++;
session[currentIdx] = [];
let focusedWindow = window.getAllWindows()[0];
exports.handleSaveSession(focusedWindow);
}
session[currentIdx].push(data['data_string']);
if(!fetchDataFromSer) {
let focusedWindow = window.getAllWindows()[0];
focusedWindow.webContents.send('ser-data', data['data_string']);
}
});
socket.on('reconnecting', function() {
console.log('Reconnecting');
});
socket.on('disconnect', function() {
let focusedWindow = window.getAllWindows()[0];
focusedWindow.webContents.send('cloud-connection-failed');
});
}
exports.handleDisconnectToCloud = function handleDisconnectToCloud(targetWindow) {
cloudURL = '';
global.sharedObj.cloudURL = '';
try{
socket.disconnect();
}catch (_) {
console.log("Already disconnected.");
}
}
exports.handleNameChange = function handleNameChange(targetWindow, sensorID, newName) {
global.sharedObj.config[sensorID] = newName;
targetWindow.webContents.send('name-changed', newName);
}
exports.handleMapChange = function handleMapChange(targetWindow, sensorID, map1, unit1, map2, unit2) {
global.sharedObj.config[sensorID+'_mapping1'] = map1;
global.sharedObj.config[sensorID+'_unit1'] = unit1;
global.sharedObj.config[sensorID+'_mapping2'] = map2;
global.sharedObj.config[sensorID+'_unit2'] = unit2;
targetWindow.webContents.send('map-changed');
}
exports.handleSaveSession = async function handleSaveSession(targetWindow) {
try {
let mkdirp = require('mkdirp');
var tempPath = sessionSavePath + sessionTimestamp + '.json'
mkdirp(sessionSavePath);
fs.writeFileSync(tempPath, JSON.stringify(session));
targetWindow.webContents.send('session-save-success');
}catch (err){
console.log(err);
console.log("Couldn't save session.");
targetWindow.webContents.send('session-save-failure');
}
}
function autoSaveSession() {
try{
let focusedWindow = window.getAllWindows()[0];
exports.handleSaveSession(focusedWindow);
}catch (e){
console.log(e);
}
}
exports.handleChangeSessionPath = function handleChangeSessionPath(targetWindow, pathName) {
sessionSavePath = pathName;
if(process.platform == 'darwin' || process.platform == 'linux') {
sessionSavePath += '/';
}else {
sessionSavePath += '\\';
}
global.sharedObj.config["sessionSavePath"] = sessionSavePath;
global.sharedObj.sessionSavePath = sessionSavePath;
targetWindow.webContents.send('session-change-success');
}
exports.handleLoadConfig = function handleLoadConfig(targetWindow, fileName) {
try {
let newConfig = JSON.parse(fs.readFileSync(fileName, 'utf8'));
global.sharedObj.config = newConfig;
targetWindow.webContents.send('config-success');
}catch (err){
console.log(err);
console.log("Couldn't load config.");
targetWindow.webContents.send('config-failure');
}
}
exports.handleResetConfig = function handleResetConfig(targetWindow) {
global.sharedObj.config = config;
targetWindow.webContents.send('reset-success');
}
exports.handleChangeMode = function handleChangeMode(targetWindow, mode) {
exports.mode = mode;
}
exports.handleChangeTrackMap = function handleChangeTrackMap(targetWindow, map) {
global.sharedObj.trackMap = map;
targetWindow.webContents.send('track-map-change-success');
}
exports.requestSessionData = function requestSessionData(targetWindow) {
return session;
}
function handleSquirrelEvent(application) {
if (process.argv.length === 1) {
return false;
}
const ChildProcess = require('child_process');
const path = require('path');
const appFolder = path.resolve(process.execPath, '..');
const rootAtomFolder = path.resolve(appFolder, '..');
const updateDotExe = path.resolve(path.join(rootAtomFolder, 'Update.exe'));
const exeName = path.basename(process.execPath);
const spawn = function(command, args) {
let spawnedProcess, error;
try {
spawnedProcess = ChildProcess.spawn(command, args, {
detached: true
});
} catch (error) {}
return spawnedProcess;
};
const spawnUpdate = function(args) {
return spawn(updateDotExe, args);
};
const squirrelEvent = process.argv[1];
switch (squirrelEvent) {
case '--squirrel-install':
case '--squirrel-updated':
// Optionally do things such as:
// - Add your .exe to the PATH
// - Write to the registry for things like file associations and
// explorer context menus
// Install desktop and start menu shortcuts
spawnUpdate(['--createShortcut', exeName]);
setTimeout(application.quit, 1000);
return true;
case '--squirrel-uninstall':
// Undo anything you did in the --squirrel-install and
// --squirrel-updated handlers
// Remove desktop and start menu shortcuts
spawnUpdate(['--removeShortcut', exeName]);
setTimeout(application.quit, 1000);
return true;
case '--squirrel-obsolete':
// This is called on the outgoing version of your app before
// we update to the new version - it's the opposite of
// --squirrel-updated
application.quit();
return true;
}
};