Files
meshcore-bot/meshcore-bot.js
2025-08-30 20:48:59 +02:00

83 lines
2.4 KiB
JavaScript

import { Constants, NodeJSSerialConnection } from "@liamcottle/meshcore.js";
// get port from cli arguments
/*eslint no-undef: "off"*/
const port = process.argv[2] || "/dev/cu.usbmodem1101";
console.log(`Connecting to ${port}`);
// create connection
const connection = new NodeJSSerialConnection(port);
let reconnectInterval;
// wait until connected
connection.on("connected", async () => {
// we are now connected
console.log("Connected");
// clear reconnect interval if it exists
if (reconnectInterval) {
clearInterval(reconnectInterval);
reconnectInterval = null;
}
// update clock on meshcore device
await connection.syncDeviceTime();
});
// auto reconnect on disconnect
connection.on("disconnected", () => {
console.log("Disconnected, trying to reconnect...");
if (reconnectInterval) {
clearInterval(reconnectInterval);
}
reconnectInterval = setInterval(async () => {
await connection.connect();
}, 3000);
});
// listen for new messages
connection.on(Constants.PushCodes.MsgWaiting, async () => {
try {
const waitingMessages = await connection.getWaitingMessages();
for(const message of waitingMessages){
if(message.contactMessage){
await onContactMessageReceived(message.contactMessage);
} else if(message.channelMessage) {
await onChannelMessageReceived(message.channelMessage);
}
}
} catch(e) {
console.log(e);
}
});
async function onContactMessageReceived(message) {
console.log("[" + (new Date()).toISOString() + "] Contact message", message);
}
async function onChannelMessageReceived(message) {
message.senderTimestampISO = (new Date(message.senderTimestamp * 1000)).toISOString();
console.log("[" + (new Date()).toISOString() + "] Channel message", message);
// handle commands only in own channels, not in public channel with id 0
if(message.channelIdx > 0){
if(message.text.includes(".ping")){
await connection.sendChannelTextMessage(message.channelIdx, "PONG! 🏓 (" + message.pathLen + ")");
return;
}
if(message.text.includes(".date")){
await connection.sendChannelTextMessage(message.channelIdx, (new Date()).toISOString());
return;
}
}
}
// connect to meshcore device
try {
await connection.connect();
} catch (e) {
console.error("Failed to connect initially", e);
}