changed discord bot stuff

This commit is contained in:
legop3
2026-01-03 12:29:47 -05:00
parent 4f2907a105
commit ec0e1564d7
+181 -32
View File
@@ -8,7 +8,7 @@ const {
const logger = require('../globals/logger').child('discordBot'); const logger = require('../globals/logger').child('discordBot');
const { loadConfig } = require('../helpers/configLoader'); const { loadConfig } = require('../helpers/configLoader');
const { subscribe } = require('./eventBus'); const { subscribe } = require('./eventBus');
const { getRoster, lockRover } = require('./roverManager'); const { getRoster, lockRover, rovers } = require('./roverManager');
const { MODES, getMode, setMode } = require('./modeManager'); const { MODES, getMode, setMode } = require('./modeManager');
const { sendExternalMessage } = require('./chatService'); const { sendExternalMessage } = require('./chatService');
@@ -48,12 +48,74 @@ function sanitizeMentions(text) {
.replace(/@here/gi, '[here]'); .replace(/@here/gi, '[here]');
} }
function formatRoverStatus(rover) { function formatVoltage(voltageMv) {
if (!rover) return 'Unknown rover'; if (voltageMv == null) return 'n/a';
const percent = rover.batteryState?.percentDisplay; return `${(voltageMv / 1000).toFixed(2)}V`;
const battery = percent != null ? `${percent}%` : 'n/a'; }
const lockLabel = rover.locked ? '🔒 locked' : '🔓 unlocked';
return `**${rover.name || rover.id}** — ${lockLabel} — battery ${battery}`; function formatCurrent(currentMa) {
if (currentMa == null) return 'n/a';
const amps = currentMa / 1000;
return `${amps.toFixed(2)}A`;
}
function formatChargeState(batteryState) {
if (!batteryState) return 'n/a';
const charge = batteryState.charge;
const capacity = batteryState.capacity;
const percent = batteryState.percentDisplay;
const chargeText = charge != null && capacity != null ? `${charge}/${capacity}mAh` : 'n/a';
const percentText = percent != null ? `${percent}%` : 'n/a';
return `${chargeText} (${percentText})`;
}
function isCharging(sensors) {
const label = sensors?.chargingState?.label?.toLowerCase();
const chargingByLabel =
label === 'waiting' || label === 'full charging' || label === 'trickle charging';
const code = sensors?.chargingState?.code;
const chargingByCode = code === 2 || code === 3 || code === 4;
return chargingByLabel || chargingByCode;
}
function buildRoverStatusSnapshot(record) {
if (!record) return null;
const sensors = record.lastSensor?.decoded || record.lastSensor?.sensors || null;
const docked = Boolean(sensors?.chargingSources?.homeBase);
const charging = isCharging(sensors);
const chargingLabel = sensors?.chargingState?.label || 'unknown';
const oiMode = sensors?.oiMode?.label || 'unknown';
return {
id: record.id,
name: record.meta?.name || record.id,
locked: record.locked,
lockReason: record.lockReason,
docked,
charging,
chargingLabel,
voltageMv: sensors?.voltageMv ?? null,
currentMa: sensors?.currentMa ?? null,
batteryState: record.batteryState,
oiMode,
};
}
function formatRoverStatus(snapshot) {
if (!snapshot) return 'Unknown rover';
const lockLabel = snapshot.locked
? `locked${snapshot.lockReason ? ` (${snapshot.lockReason})` : ''}`
: 'unlocked';
const dockLabel = snapshot.docked ? 'docked' : 'undocked';
const chargingLabel = snapshot.charging ? `charging (${snapshot.chargingLabel})` : 'not charging';
return [
`**${snapshot.name}** — ${lockLabel}`,
`dock: ${dockLabel}`,
`charge: ${chargingLabel}`,
`battery: ${formatChargeState(snapshot.batteryState)}`,
`voltage: ${formatVoltage(snapshot.voltageMv)}`,
`current: ${formatCurrent(snapshot.currentMa)}`,
`oi: ${snapshot.oiMode}`,
].join(' — ');
} }
function countReady() { function countReady() {
@@ -117,23 +179,28 @@ function formatHelp() {
].join('\n'); ].join('\n');
} }
function findRover(id) { function findRoverRecord(id) {
const roster = getRoster();
if (!id) return null; if (!id) return null;
return roster.find((r) => String(r.id) === String(id) || String(r.name) === String(id)); for (const record of rovers.values()) {
if (String(record.id) === String(id) || String(record.meta?.name) === String(id)) {
return record;
}
}
return null;
} }
async function handleStatusCommand(message, roverId) { async function handleStatusCommand(message, roverId) {
const roster = getRoster();
if (!roverId) { if (!roverId) {
const summary = roster.map((r) => formatRoverStatus(r)).join('\n') || 'No rovers online.'; const snapshots = Array.from(rovers.values()).map(buildRoverStatusSnapshot).filter(Boolean);
const summary = snapshots.map((snapshot) => formatRoverStatus(snapshot)).join('\n') || 'No rovers online.';
await message.reply({ await message.reply({
content: sanitizeMentions(summary.slice(0, 1900)), content: sanitizeMentions(summary.slice(0, 1900)),
allowedMentions: { parse: [], repliedUser: false }, allowedMentions: { parse: [], repliedUser: false },
}); });
return; return;
} }
const rover = findRover(roverId); const record = findRoverRecord(roverId);
const rover = buildRoverStatusSnapshot(record);
await message.reply({ await message.reply({
content: sanitizeMentions(formatRoverStatus(rover).slice(0, 1900)), content: sanitizeMentions(formatRoverStatus(rover).slice(0, 1900)),
allowedMentions: { parse: [], repliedUser: false }, allowedMentions: { parse: [], repliedUser: false },
@@ -256,15 +323,81 @@ function buildEmbed({ title, description, color }) {
return embed; return embed;
} }
async function announce({ channelId, content, pingRoleId, color, title, description }) { function buildBatteryStatusEmbed(color) {
const embed = buildEmbed({ title: 'Rover Battery Status', color: color || 0x2196f3 });
const snapshots = Array.from(rovers.values()).map(buildRoverStatusSnapshot).filter(Boolean);
if (snapshots.length === 0) {
embed.setDescription('No rovers online.');
return embed;
}
snapshots.forEach((snapshot) => {
const lockLabel = snapshot.locked
? `locked${snapshot.lockReason ? ` (${snapshot.lockReason})` : ''}`
: 'unlocked';
const dockLabel = snapshot.docked ? 'docked' : 'undocked';
const chargingLabel = snapshot.charging ? `charging (${snapshot.chargingLabel})` : 'not charging';
const lines = [
`Dock: ${dockLabel}`,
`Charging: ${chargingLabel}`,
`Battery: ${formatChargeState(snapshot.batteryState)}`,
`Voltage: ${formatVoltage(snapshot.voltageMv)}`,
`Current: ${formatCurrent(snapshot.currentMa)}`,
`OI: ${snapshot.oiMode}`,
`Lock: ${lockLabel}`,
];
embed.addFields({ name: snapshot.name, value: lines.join('\n'), inline: false });
});
return embed;
}
function buildBatteryCaption(type, payload) {
const roverId = payload?.roverId || 'unknown';
const record = rovers.get(roverId) || findRoverRecord(roverId);
const snapshot = buildRoverStatusSnapshot(record);
const base = snapshot?.name || roverId;
const percent = snapshot?.batteryState?.percentDisplay;
const percentLabel = percent != null ? `${percent}%` : 'n/a';
const dockLabel = snapshot?.docked ? 'docked' : 'undocked';
const chargingLabel = snapshot?.charging ? 'charging' : 'not charging';
const voltage = formatVoltage(snapshot?.voltageMv ?? null);
const current = formatCurrent(snapshot?.currentMa ?? null);
const charge = formatChargeState(snapshot?.batteryState ?? null);
const detail = `${dockLabel}, ${chargingLabel}, ${voltage}, ${current}, ${charge}`;
switch (type) {
case 'battery.warn':
return `Battery warn: ${base} at ${percentLabel}. ${detail}`;
case 'battery.urgent':
return `Battery urgent: ${base} at ${percentLabel}. ${detail}`;
case 'battery.docked':
return `Docked: ${base}. ${detail}`;
case 'battery.undocked':
return `Undocked: ${base}. ${detail}`;
case 'battery.charging.start':
return `Charging started: ${base}. ${detail}`;
case 'battery.charging.stop':
return `Charging stopped: ${base}. ${detail}`;
case 'battery.locked':
return `Locked for charging: ${base}. ${detail}`;
case 'battery.unlocked':
return `Unlocked after charging: ${base}. ${detail}`;
default:
return `Battery update: ${base}. ${detail}`;
}
}
async function announce({ channelId, content, pingRoleId, color, title, description, embeds }) {
if (!channelId) return; if (!channelId) return;
const prefix = pingRoleId ? `<@&${pingRoleId}> ` : ''; const prefix = pingRoleId ? `<@&${pingRoleId}> ` : '';
const embed = buildEmbed({ title, description, color }); const payloadEmbeds =
Array.isArray(embeds) && embeds.length > 0
? embeds
: [buildEmbed({ title, description, color })];
const allowedMentions = pingRoleId ? { roles: [pingRoleId], parse: [] } : { parse: [] }; const allowedMentions = pingRoleId ? { roles: [pingRoleId], parse: [] } : { parse: [] };
await sendToChannel( await sendToChannel(
channelId, channelId,
`${prefix}${content || ''}`.trim(), `${prefix}${content || ''}`.trim(),
{ embeds: [embed] }, { embeds: payloadEmbeds },
allowedMentions, allowedMentions,
!pingRoleId, // keep role mention intact when pinging !pingRoleId, // keep role mention intact when pinging
); );
@@ -334,8 +467,10 @@ function handleBusEvent(event) {
channelId: channels.adminAlerts, channelId: channels.adminAlerts,
pingRoleId: roles.adminPing || null, pingRoleId: roles.adminPing || null,
color: 0xf0b651, color: 0xf0b651,
title: 'Battery Warn', content: buildBatteryCaption(type, payload),
description: `${payload?.roverId} at ${payload?.batteryState?.percentDisplay ?? 'low'}%.`, title: 'Battery Status',
description: null,
embeds: [buildBatteryStatusEmbed(0xf0b651)],
}); });
break; break;
case 'battery.urgent': case 'battery.urgent':
@@ -343,48 +478,60 @@ function handleBusEvent(event) {
channelId: channels.adminAlerts, channelId: channels.adminAlerts,
pingRoleId: roles.adminPing || null, pingRoleId: roles.adminPing || null,
color: 0xe53935, color: 0xe53935,
title: 'Battery Urgent', content: buildBatteryCaption(type, payload),
description: `${payload?.roverId} at ${payload?.batteryState?.percentDisplay ?? 'urgent'}%.`, title: 'Battery Status',
description: null,
embeds: [buildBatteryStatusEmbed(0xe53935)],
}); });
break; break;
case 'battery.docked': case 'battery.docked':
announce({ announce({
channelId: channels.adminAlerts, channelId: channels.adminAlerts,
color: 0x2196f3, color: 0x2196f3,
title: 'Docked', content: buildBatteryCaption(type, payload),
description: `${payload?.roverId} docked.`, title: 'Battery Status',
description: null,
embeds: [buildBatteryStatusEmbed(0x2196f3)],
}); });
break; break;
case 'battery.undocked': case 'battery.undocked':
announce({ announce({
channelId: channels.adminAlerts, channelId: channels.adminAlerts,
color: 0x2196f3, color: 0x2196f3,
title: 'Undocked', content: buildBatteryCaption(type, payload),
description: `${payload?.roverId} undocked.`, title: 'Battery Status',
description: null,
embeds: [buildBatteryStatusEmbed(0x2196f3)],
}); });
break; break;
case 'battery.charging.start': case 'battery.charging.start':
announce({ announce({
channelId: channels.adminAlerts, channelId: channels.adminAlerts,
color: 0x2196f3, color: 0x2196f3,
title: 'Charging Started', content: buildBatteryCaption(type, payload),
description: `${payload?.roverId} started charging.`, title: 'Battery Status',
description: null,
embeds: [buildBatteryStatusEmbed(0x2196f3)],
}); });
break; break;
case 'battery.charging.stop': case 'battery.charging.stop':
announce({ announce({
channelId: channels.adminAlerts, channelId: channels.adminAlerts,
color: 0xf0b651, color: 0xf0b651,
title: 'Charging Stopped', content: buildBatteryCaption(type, payload),
description: `${payload?.roverId} stopped charging.`, title: 'Battery Status',
description: null,
embeds: [buildBatteryStatusEmbed(0xf0b651)],
}); });
break; break;
case 'battery.locked': case 'battery.locked':
announce({ announce({
channelId: channels.adminAlerts, channelId: channels.adminAlerts,
color: 0xf0b651, color: 0xf0b651,
title: 'Locked for Charging', content: buildBatteryCaption(type, payload),
description: `${payload?.roverId} locked for charging.`, title: 'Battery Status',
description: null,
embeds: [buildBatteryStatusEmbed(0xf0b651)],
}); });
updatePresence(); updatePresence();
break; break;
@@ -392,8 +539,10 @@ function handleBusEvent(event) {
announce({ announce({
channelId: channels.adminAlerts, channelId: channels.adminAlerts,
color: 0x4caf50, color: 0x4caf50,
title: 'Unlocked after Charging', content: buildBatteryCaption(type, payload),
description: `${payload?.roverId} unlocked after charging.`, title: 'Battery Status',
description: null,
embeds: [buildBatteryStatusEmbed(0x4caf50)],
}); });
updatePresence(); updatePresence();
break; break;