led-bot/lights/request.js

39 lines
784 B
JavaScript
Raw Normal View History

2020-11-09 04:15:14 +00:00
import * as net from 'net';
2020-11-08 03:29:13 +00:00
2020-11-09 04:15:14 +00:00
const hostname = '192.168.1.219';
const port = 29999;
function getBinarySize(string) {
return Buffer.byteLength(string, 'utf8');
}
2020-11-08 03:29:13 +00:00
2020-11-09 06:29:38 +00:00
function padLeft(size = 4, str = '') {
let remaining = size - str.length;
return '0'.repeat(remaining) + str;
}
2020-11-08 03:29:13 +00:00
export default function req(data, callback, errorCallback) {
2020-11-09 04:15:14 +00:00
let string_data = JSON.stringify(data);
let size = getBinarySize(string_data);
2020-11-12 09:48:33 +00:00
if (size > 9999) {
errorCallback("too long");
return;
}
2020-11-09 04:15:14 +00:00
let client = new net.Socket();
client.connect(port, hostname, () => {
2020-11-09 06:29:38 +00:00
let res = client.write(padLeft(4, `${size}`));
2020-11-09 04:15:14 +00:00
if (res) {
client.write(string_data);
}
2020-11-09 06:29:38 +00:00
client.destroy();
2020-11-09 06:53:07 +00:00
callback('success.');
});
client.on('error', (e) => {
client.destroy();
errorCallback(e);
2020-11-09 04:15:14 +00:00
});
2020-11-08 03:29:13 +00:00
}