This repository was archived by the owner on Dec 23, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNodeServer.js
95 lines (79 loc) · 2.37 KB
/
NodeServer.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
'use strict';
const express = require('express');
const app = express();
const SerialPort = require("serialport");
//------------------------------------------------------------------------
app.listen(9001, function () {
console.log('REST Server is Listening ...\n');
});
// noinspection JSUnresolvedFunction
app.get('/:action', function (req, res) {
let action = req.params.action || req.param('action');
if (action === 'w') {
socket.write("w");
return res.send('White calibration ...');
}
if (action === 'b') {
socket.write("b");
return res.send("Black calibration ...");
}
if (action === 'n') {
socket.write("n");
return res.send("Do sampling ...");
}
return res.send('Action: ' + action);
});
app.get('/get/:action', function (req, res) {
let action = req.params.action || req.param('action');
if (action === 'w') {
return res.send({result: whiteJSONData});
}
if (action === 'b') {
return res.send({result: blackJSONData});
}
if (action === 'n') {
return res.send({result: sampleJSONData});
}
});
//------------------------------------------------------------------------
let socket = new SerialPort("COM4", {
baudRate: 9600
});
socket.on('open', function () {
console.log('Serial Server is Listening ...\n');
});
let sampleJSONData = {};
let blackJSONData = {};
let whiteJSONData = {};
//FIXME: need Semaphore
let d = "";
socket.on('data', function (data) {
data = data.toString();
d += data;
if (d.indexOf("$") > -1) {
d = d.replaceAll('\r\n', '');
d = d.replaceAll('\r', '');
d = d.replaceAll('\n', '');
d = d.replaceAll(' ', '');
d = d.replaceAll("$", "\n");
console.log(d);
let k = d.split('~')[0];
let j = d.split('~')[1].split('$')[0];
j=j.replaceAll("\'","\"");
j=JSON.parse(j);
if (k === 'SAMPLE') {
sampleJSONData = j;
} else if (k === 'BLACK') {
blackJSONData = j;
} else if (k === 'WHITE') {
whiteJSONData = j;
}
d = "";
console.log(j);
}
});
//------------------------------------------------------------------------
String.prototype.replaceAll = function (search, replacement) {
let target = this;
return target.replace(new RegExp(search, 'g'), replacement);
};