-
Notifications
You must be signed in to change notification settings - Fork 0
/
renderer.js
583 lines (536 loc) · 16.7 KB
/
renderer.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
// This file is required by the index.html file and will
// be executed in the renderer process for that window.
// No Node.js APIs are available in this process because
// `nodeIntegration` is turned off. Use `preload.js` to
// selectively enable features needed in the rendering
// process.
const {SerialPort} = require('serialport');
const {ReadlineParser} = require('@serialport/parser-readline');
// const Delimiter = require('@serialport/parser-delimiter');
const createCsvWriter = require('csv-writer').createObjectCsvWriter;
const net = require('net');
const isIp = require('is-ip');
const Store = require('electron-store');
const {ipcRenderer} = window.require('electron');
let csvWriter;
let $ = require('jquery');
let port = null;
let measure = {
'count': 0,
'sum': 0,
'max': 0,
'current': 0
};
let pingMkTimer;
let lastResponseMKTime = 0;
const store = new Store();
$(document).ready(function () {
if (typeof store.get('countChartPoints') === 'undefined') {
store.set('countChartPoints', 20);
store.set('isEnableRpm', 0);
}
$('#countChartPoints').val(store.get('countChartPoints'));
$('#enableRpm').prop('checked', store.get('isEnableRpm'));
$('#connectIp').val(store.get('lastIp')).trigger('input');
if (store.get('isEnableRpm') == 0) {
$('.js-show-rpm').hide();
}
});
// Set a timeout that will check for new serialPorts every 2 seconds.
// This timeout reschedules itself.
ipcRenderer.on('getUsbPorts', (_event, _args) => {
$('#ports').empty();
$('.js-usb-plug').removeClass('text-success');
if (_args.length === 0) {
document.getElementById('error').textContent = 'No ports discovered'
$('#connectPort').addClass('disabled')
} else {
_args.forEach(function (port, index, object) {
if (typeof (port.pnpId) == 'undefined') {
object.splice(index, 1);
return;
}
// console.log(port)
$('#ports').append(`<option value="${port.path}">
${port.path}
</option>`);
$('#connectPort').removeClass('disabled')
$('.js-usb-plug').addClass('text-success');
});
}
})
function listPorts() {
ipcRenderer.send('getUsbPorts')
setTimeout(listPorts, 2000);
}
let searchPorts = setTimeout(listPorts, 2000);
async function readFromPort(data) {
// buffer = Buffer.from(data, 'utf8');
// console.log(data.toString('utf8'));
lastResponseMKTime = Date.now();
data = data.toString('utf8').trim();
data.split('\n').forEach(function (response) {
response = response.split(';');
if (response[0] == '$1') {
setFirmwareVersion(response[1])
} else if (response[0] == '$2') {
loadSettings(response);
} else if (response[0] == '$3') {
// console.log(response);
addMeasure(response);
} else if (response[0] == '$4') {
mkConfirmStopMeasure(response);
} else if (response[0] == '$5') {
console.log('Data: ', response);
} else if (response[0] == '$6') {
console.log('Data: ', response);
} else if (response[0] == '$7') {
console.log('Data: ', response);
} else if (response[0] == '$8') {
setIp(response[1]);
} else if (response[0] == '$9') {
updateThrottle(response[1]);
} else if (response[0] == '$13') {
} else if (response[0] == '$16') {
getCalibrateFactor(response[1]);
} else if (response[0] == '$17') {
getGramms(response[1]);
} else if (response[0] !== '') {
console.log('Data: ', response);
}
});
// console.log(buffer.readUint8(0), buffer.readUint8(1))
// if (buffer.readUint8(0) == '$' && buffer.readUint8(1) == '2') {
// console.log('settings ok');
// }
}
function setIp(data) {
$('#deviceIp').text(data);
if (data.length > 0) {
store.set('lastIp', data);
$('.js-device-wifi').addClass('text-success');
} else {
$('.js-device-wifi').removeClass('text-success');
}
}
function setFirmwareVersion(data) {
loadWindowHide();
$('#firmwareVersion').text(data);
}
function loadSettings(data) {
$('#settingsLoader').hide();
$('#settingsPanel').fadeIn(300);
$('#measureCorrection').val(data[1]);
$('#wifiName').val(data[2]);
$('#wifiPassword').val(data[3]);
$('#minThrottle').val(data[4]);
$('#maxThrottle').val(data[5]);
}
function updateThrottle(data) {
if (data == '') {
data = 0;
}
data = parseInt(data);
$('#motorControl').val(data);
$('#throttlePercent').text(data);
}
function addMeasure(data) {
$('#startMeasure').text('Стоп');
$('#startMeasure').val(1);
let value = parseFloat(data[1]);
measure.count++;
measure.sum += value;
if (measure.max < value) {
measure.max = value;
}
measure.current = data[4];
updateTimeLineChart(value, parseInt(data[2]), parseInt(data[3]), parseFloat(data[4]));
updateMeasureTable();
}
function mkConfirmStopMeasure(data) {
$('#startMeasure').text('Старт');
$('#startMeasure').val(0);
}
function updateMeasureTable() {
$('#measureAvg').text(Number(measure.sum / measure.count).toFixed(3));
$('#measureMax').text(Number(measure.max).toFixed(3));
$('#measureCurrent').text(Number(measure.current).toFixed(2));
}
function connectWindowHide() {
$('.js-window').hide();
$('#loadWindow').fadeIn(300);
clearTimeout(searchPorts);
}
function loadWindowHide() {
if ($('#loadWindow').is(':visible')) {
$('.js-window').hide();
$('#controlWindow').fadeIn(300);
}
}
function pingMK() {
if (Date.now() - lastResponseMKTime >= 2000) {
window.location.reload();
}
port.write('$1\n');
}
function connectSerial() {
connectWindowHide();
port = new SerialPort({
baudRate: 115200,
autoOpen: false,
path: $('#ports').val()
})
port.open(function (err) {
if (err) {
portClose();
return console.log('Error opening port: ', err.message);
}
pingMkTimer = setInterval(() => port.write('$1\n'), 1000);
// Because there's no callback to write, write errors will be emitted on the port:
console.log('Connected Serial');
port.write('$1\n');
port.write('$8\n');
port.write('$9\n');
})
// port.on('data', readFromPort)
port.on('error', showError);
port.on('close', portClose);
// Switches the port into "flowing mode"
// port.on('readable', readFromPort)
// Pipe the data into another stream (like a parser or standard out)
const lineStream = port.pipe(new ReadlineParser({delimiter: '\r\n'}));
lineStream.on('data', readFromPort);
}
$('#connectPort').on('click', function () {
if ($('#connectIp').val() != "") {
connectSocket($('#connectIp').val());
} else if ($('#ports').val() != null) {
connectSerial();
}
});
$('#connectIp').on('input', function () {
if (isIp($(this).val())) {
$('.js-ip-correct').addClass('text-success');
} else {
$('.js-ip-correct').removeClass('text-success');
}
});
$('.js-close-port').on('click', function () {
if (typeof port.close !== "undefined") {
port.close();
} else {
port.destroy();
}
});
$('#startMeasure').on('click', function () {
if ($(this).val() == 0) {
measure = {
'count': 0,
'sum': 0,
'max': 0,
};
const optionsDate = {
year: 'numeric',
month: 'numeric',
day: 'numeric',
timezone: 'UTC',
};
const optionsTime = {
timezone: 'UTC',
hour: 'numeric',
minute: 'numeric',
second: 'numeric'
};
csvWriter = createCsvWriter({
path: ('./logs/' + (new Date()).toLocaleString('ru', optionsDate) + ' ' + (new Date()).toLocaleString('ru', optionsTime) + '.csv').replaceAll(':', ''),
fieldDelimiter: ';',
header: [
{id: 'time', title: 'TIME'},
{id: 'measure', title: 'MEASURE'},
{id: 'throttle', title: 'THROTTLE'},
{id: 'rpm', title: 'RPM'},
{id: 'current', title: 'CURRENT'}
]
});
port.write('$3\n');
} else {
port.write('$4\n');
}
});
$('#saveSettings').on('click', function () {
store.set('countChartPoints', $('#countChartPoints').val());
store.set('isEnableRpm', $('#enableRpm').is(':checked'));
if (store.get('isEnableRpm') == 0) {
$('.js-show-rpm').hide();
} else {
$('.js-show-rpm').show();
}
port.write('$5;' + $('#wifiName').val().trim() + '\n');
port.write('$6;' + $('#wifiPassword').val().trim() + '\n');
port.write('$11;' + $('#minThrottle').val().trim() + '\n');
port.write('$12;' + $('#maxThrottle').val().trim() + '\n');
port.write('$13;' + $('#measureCorrection').val().trim() + '\n');
port.write('$10\n');
port.write('$2\n');
port.write('$7\n');
});
$('#motorControl').on('input', function () {
port.write('$9;' + parseInt($(this).val()) + '\n');
});
function showError(error) {
console.log('Serial port error: ' + error);
}
function portClose() {
// $('.js-window').hide();
// $('#connectWindow').fadeIn(300);
// searchPorts = setTimeout(listPorts, 2000);
window.location.reload();
}
$('#list-settings-list').on('shown.bs.tab', function (e) {
port.write('$2\n');
})
///
var Chart = require('chart.js');
var ctx = document.getElementById('chartPropThrust');
var chartPropThrust = new Chart(ctx, {
type: 'line',
data: {
labels: [],
datasets: [
{
label: 'Тяга, г',
data: [],
backgroundColor: [
'rgb(104,255,99)',
],
borderColor: [
'rgb(104,255,99)',
],
borderWidth: 1
},
{
label: 'Газ, %',
data: [],
backgroundColor: [
'rgb(57,14,210)',
],
borderColor: [
'rgb(57,14,210)',
],
borderWidth: 1
},
{
label: 'Ток, А',
data: [],
backgroundColor: [
'rgb(210,14,37)',
],
borderColor: [
'rgb(210,14,53)',
],
borderWidth: 1
}
]
},
options: {
responsive: true,
maintainAspectRatio: false,
scales: {
y: {
beginAtZero: true,
title: {
display: true,
text: "Тяга"
}
},
x: {
// beginAtZero: true,
title: {
display: true,
text: "Время"
}
}
}
}
});
var chartMotorRpm = new Chart($('#chartMotorRpm'), {
type: 'line',
data: {
labels: [],
datasets: [
{
label: 'Оброты, мин',
data: [],
backgroundColor: [
'rgb(104,255,99)',
],
borderColor: [
'rgb(104,255,99)',
],
borderWidth: 1
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
scales: {
y: {
beginAtZero: true,
title: {
display: true,
text: "Обороты"
}
},
x: {
// beginAtZero: true,
title: {
display: true,
text: "Время"
}
}
}
}
});
//Download Chart Image
document.getElementById("download").addEventListener('click', function () {
/*Get image of canvas element*/
var url_base64jp = document.getElementById("chartPropThrust").toDataURL('image/jpeg', 1.0);
/*get download button (tag: <a></a>) */
var a = document.getElementById("download");
/*insert chart image url to download button (tag: <a></a>) */
a.href = url_base64jp;
});
async function updateTimeLineChart(value, throttle, rpm, current) {
let date = new Date();
let time = date.toLocaleTimeString();
addData(chartPropThrust, time, value, throttle, current);
addDataRpm(chartMotorRpm, time, rpm);
removeData(chartPropThrust);
removeDataRpm(chartMotorRpm);
if (csvWriter) {
await csvWriter.writeRecords([{
'time': time,
'measure': value,
'throttle': throttle,
'rpm': rpm,
'current': current
}])
}
}
function addData(chart, label, data, throttle, current) {
chart.data.labels.push(label);
chart.data.datasets[0].data.push(data);
chart.data.datasets[1].data.push(throttle);
chart.data.datasets[2].data.push(current);
chart.update();
}
function addDataRpm(chart, label, data) {
$('#measureRpm').text(data);
chart.data.labels.push(label);
chart.data.datasets[0].data.push(data);
chart.update();
}
function removeData(chart) {
if (chart.data.datasets[0].data.length > store.get('countChartPoints')) {
chart.data.labels.shift();
chart.data.datasets[0].data.shift();
chart.data.datasets[1].data.shift();
chart.data.datasets[2].data.shift();
chart.update();
}
}
function removeDataRpm(chart) {
if (chart.data.datasets[0].data.length > store.get('countChartPoints')) {
chart.data.labels.shift();
chart.data.datasets[0].data.shift();
chart.update();
}
}
function connectSocket(ip) {
if (port) {
portClose();
}
connectWindowHide();
port = new net.Socket();
port.connect(80, ip, function () {
console.log('Connected Wifi');
pingMkTimer = setInterval(() => port.write('$1\n'), 1000);
port.write('$1\n');
port.write('$8\n');
port.write('$9\n');
});
port.on('data', function (data) {
readFromPort(data)
});
port.on('close', function () {
console.log('Connection closed');
portClose();
});
}
/////////////Калибровка
$('#calibrateBack').on('click', function () {
port.write('$2\n');
$('.js-window').hide();
$('#controlWindow').fadeIn(300);
});
$('#startCalibrate').on('click', function () {
$('.js-window').hide();
$('#calibrateWindow').fadeIn(300);
});
$('#calibrate-step-2').on('click', function () {
$('.js-calibrate-step-1').hide();
$('.js-calibrate-step-2').fadeIn(300);
port.write('$15\n');
});
$('#calibrate-step-3').on('click', function () {
if (parseFloat($('#controlWeight').val()) > 0) {
$('#controlWeight').removeClass('is-invalid').addClass('is-valid').prop('disabled', true);
} else {
$('#controlWeight').addClass('is-invalid')
}
$(this).hide();
$('.js-calibrate-step-3').fadeIn(300);
});
$('#calibrate-step-4').on('click', function () {
$('#calibrate-step-4').hide();
$('.js-calibrate-step-4').fadeIn(300);
port.write('$16;' + parseFloat($('#controlWeight').val()) + '\n');
});
$('#calibrateSuccess').on('click', function () {
port.write('$13;' + $('#calibrateFactor').text().trim() + '\n');
port.write('$10\n');
$('.js-calibrate-step-5').hide();
$('.js-calibrate-step-6').fadeIn(300);
});
$('#calibrateFinish').on('click', function () {
$('.js-window').hide();
$('#controlWindow').fadeIn(300);
});
$('#additionalMeasure').on('click', function () {
$('.js-additional-measure-1').hide();
$('.js-additional-measure-2').fadeIn(300);
});
$('#startAdditionalMeasure').on('click', function () {
$('.js-additional-measure-2').hide();
$('.js-additional-measure-3').fadeIn(300);
port.write('$17\n');
});
$('#additionalMeasureToo').on('click', function () {
$('.js-additional-measure-3').hide();
$('.js-additional-measure-2').fadeIn(300);
});
$('#calibrateIncorrect').on('click', function () {
$('.js-calibrate-step-5').hide();
$('#calibrate-step-4').fadeIn(300);
$('.js-calibrate-step-3').fadeIn(300);
// port.write('$15\n');
});
function getCalibrateFactor(data) {
$('.js-calibrate-step-4').hide();
$('.js-calibrate-step-5').fadeIn(300);
$('#calibrateFactor').text(data);
}
function getGramms(data) {
$('#measureControlWeight').text(data);
$('.js-measure-weight').text(data);
}