76 lines
2.1 KiB
JavaScript
76 lines
2.1 KiB
JavaScript
const dgram = require("dgram");
|
|
const cellularChunking = require("./cellularChunking");
|
|
|
|
let message_id = 0
|
|
|
|
const socket = dgram.createSocket("udp4");
|
|
|
|
function handleMessage(message, rinfo) {
|
|
try {
|
|
str_msg = message.toString('utf8')
|
|
console.log('str_msg: ', str_msg)
|
|
console.log("parsed message: ", JSON.parse(str_msg))
|
|
} catch (e) {
|
|
console.log('some error parsing message: ', e)
|
|
}
|
|
try {
|
|
str_msg = message.toString('utf8')
|
|
msg = JSON.parse(JSON.parse(str_msg)) // WHAT THE HELL?
|
|
message_id = message_id + 1
|
|
theMsg = {
|
|
'data': {
|
|
'mi': 360,
|
|
'mo': 0,
|
|
'wl': 4
|
|
},
|
|
'target': msg['source'],
|
|
'msg_type': 'settings'
|
|
}
|
|
console.log('to reply: ', theMsg)
|
|
const theRespChunks = cellularChunking.chunk_message(JSON.stringify(theMsg), message_id);
|
|
thisSend(theRespChunks, socket, rinfo)
|
|
} catch (e) {
|
|
console.log('some error sending reply message: ', e)
|
|
}
|
|
|
|
}
|
|
|
|
function thisSend(theChunks, socket, rinfo, thisFilePath, fileList) {
|
|
console.log("Send response")
|
|
socket.send(theChunks[0], rinfo.port, rinfo.address, (err) => {
|
|
if (err) {
|
|
console.log(err);
|
|
} else {
|
|
console.log("send chunk");
|
|
if (theChunks.length > 1) {
|
|
setTimeout(
|
|
thisSend,
|
|
1000,
|
|
theChunks.slice(1),
|
|
socket,
|
|
rinfo,
|
|
thisFilePath,
|
|
fileList,
|
|
);
|
|
}/* else if (fileList.length > 1) {
|
|
sendFile(socket, rinfo, thisFilePath, fileList.slice(1));
|
|
}*/
|
|
}
|
|
});
|
|
}
|
|
|
|
socket.on("listening", () => {
|
|
let addr = socket.address();
|
|
console.log(`Listening for UDP packets at ${addr.address}:${addr.port}`);
|
|
});
|
|
|
|
socket.on("error", (err) => {
|
|
console.error(`UDP error: ${err.stack}`);
|
|
});
|
|
|
|
socket.on("message", function(msg, rinfo) {
|
|
console.log("string message: \n", Buffer.from(msg, 'hex').toString('utf8').trim())
|
|
cellularChunking.receive_chunk(Buffer.from(msg, 'hex').toString('utf8').trim(), handleMessage, rinfo);
|
|
});
|
|
socket.bind(52321);
|