leds/server.js

63 lines
1.8 KiB
JavaScript
Raw Normal View History

import * as net from 'net';
2021-05-27 18:27:02 +00:00
import * as fs from 'fs';
2021-05-27 18:26:12 +00:00
import Logger, { levels } from './logger.js';
2021-06-04 19:22:48 +00:00
import parse from './parse.js'
2021-05-27 18:26:12 +00:00
const cfg = JSON.parse(fs.readFileSync('./config.json'));
const log = new Logger("server", cfg.log_level ? levels[cfg.log_level] : levels.INFO);
const hostname = '0.0.0.0';
2021-05-26 00:32:56 +00:00
const port = 29999;
2021-05-26 00:32:56 +00:00
export function recv(callback, errorCallback) {
let server = new net.Server();
server.listen(port, hostname, () => {
server.on('connection', (con) => {
console.log('connection recieved: ' +
con.remoteAddress + ":" + con.remotePort);
2021-06-04 19:22:48 +00:00
// let data = [];
// for (let key of Object.keys(functions)) {
// data.push({
// n: key.toUpperCase(),
// a: reqs[key.toLowerCase()] != undefined ? reqs[key.toLowerCase()] : true
// });
// }
// let functions_str = JSON.stringify(data);
// con.write(functions_str);
// log.debug(`sending ${functions_str}`);
2021-05-26 00:32:56 +00:00
con.on('data', (data) => {
2021-06-04 19:39:53 +00:00
let parsed_data = parse(String(data));
2021-06-04 19:22:48 +00:00
2021-06-05 02:02:13 +00:00
if (parsed_data.errors != undefined && parsed_data.errors.length > 0) {
2021-06-05 02:14:18 +00:00
con.write(`error ..\n${JSON.stringify(parsed_data)}`);
2021-06-04 19:22:48 +00:00
errorCallback(parsed_data);
}
else {
2021-06-05 02:14:18 +00:00
con.write(`success ..\n${JSON.stringify(parsed_data)}`);
2021-06-04 19:22:48 +00:00
callback(data);
}
2021-05-26 00:32:56 +00:00
});
con.on('close', () => {
console.log('recieved close for ' +
con.remoteAddress + ":" + con.remotePort);
con.destroy();
});
server.getConnections((err, cons) => {
if (err) {
console.error(err);
}
else {
console.log(`connections: ${cons}`);
}
})
})
2021-05-26 00:32:56 +00:00
server.on('error', (e) => {
server.close();
errorCallback(e);
});
});
}