2025-03-04 17:14:07 +13:00
|
|
|
import Constants from "../src/constants.js";
|
2025-04-08 14:28:43 +12:00
|
|
|
import TCPConnection from "../src/connection/tcp_connection.js";
|
|
|
|
|
import NodeJSSerialConnection from "../src/connection/nodejs_serial_connection.js";
|
2025-03-04 17:14:07 +13:00
|
|
|
|
2025-04-08 14:28:43 +12:00
|
|
|
// create connection
|
|
|
|
|
// const connection = new TCPConnection("10.1.0.226", 5000);
|
|
|
|
|
const connection = new NodeJSSerialConnection("/dev/cu.usbmodem14401");
|
2025-03-04 17:14:07 +13:00
|
|
|
|
|
|
|
|
// wait until connected
|
|
|
|
|
connection.on("connected", async () => {
|
|
|
|
|
|
|
|
|
|
// we are now connected
|
2025-04-08 14:28:43 +12:00
|
|
|
console.log("Connected");
|
2025-03-04 17:14:07 +13:00
|
|
|
|
2025-04-08 14:39:12 +12:00
|
|
|
// update clock on meshcore device
|
|
|
|
|
await connection.syncDeviceTime();
|
|
|
|
|
|
2025-03-04 17:14:07 +13:00
|
|
|
// send flood advert when connected
|
|
|
|
|
await connection.sendFloodAdvert();
|
|
|
|
|
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// listen for new messages
|
|
|
|
|
connection.on(Constants.PushCodes.MsgWaiting, async () => {
|
|
|
|
|
try {
|
2025-03-04 17:36:22 +13:00
|
|
|
const waitingMessages = await connection.getWaitingMessages();
|
|
|
|
|
for(const message of waitingMessages){
|
2025-03-04 17:14:07 +13:00
|
|
|
if(message.contactMessage){
|
|
|
|
|
await onContactMessageReceived(message.contactMessage);
|
|
|
|
|
} else if(message.channelMessage) {
|
|
|
|
|
await onChannelMessageReceived(message.channelMessage);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
} catch(e) {
|
|
|
|
|
console.log(e);
|
|
|
|
|
}
|
2025-03-04 17:36:22 +13:00
|
|
|
});
|
2025-03-04 17:14:07 +13:00
|
|
|
|
|
|
|
|
async function onContactMessageReceived(message) {
|
|
|
|
|
|
|
|
|
|
console.log("Received contact message", message);
|
|
|
|
|
|
|
|
|
|
// find first contact matching pub key prefix
|
2025-03-04 17:36:22 +13:00
|
|
|
const contact = await connection.findContactByPublicKeyPrefix(message.pubKeyPrefix);
|
2025-03-04 17:14:07 +13:00
|
|
|
if(!contact){
|
|
|
|
|
console.log("Did not find contact for received message");
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// send it back
|
|
|
|
|
await connection.sendTextMessage(contact.publicKey, message.text, Constants.TxtTypes.Plain);
|
|
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async function onChannelMessageReceived(message) {
|
|
|
|
|
console.log(`Received channel message`, message);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// todo auto reconnect on disconnect
|
|
|
|
|
|
|
|
|
|
// connect to meshcore device
|
|
|
|
|
await connection.connect();
|