feat: Implement command acknowledgment and improve command polling reliability for turtles

This commit is contained in:
MayaTheShy
2026-02-19 23:27:23 -05:00
parent 6e50a109dc
commit 4bda9c536b
2 changed files with 104 additions and 20 deletions

View File

@@ -254,10 +254,20 @@ app.get('/api/turtle/:id/commands', (req, res) => {
commands.forEach(cmd => console.log(` - ${cmd.command}`, cmd.param ? `(${cmd.param})` : ''));
}
// Clear pending commands
turtle.pendingCommands = [];
res.json({ commands });
// Mark commands as sent but don't clear them yet - they'll be cleared on next poll if turtle is processing
// This allows the webbridge to retry if the turtle didn't receive them
if (!turtle.lastCommandPollTime || (Date.now() - turtle.lastCommandPollTime) > 5000) {
// First poll or more than 5 seconds since last poll - send commands
turtle.lastCommandPollTime = Date.now();
res.json({ commands });
} else {
// Recent poll - assume previous commands were received, clear them
if (commands.length > 0) {
console.log(`✅ Clearing ${commands.length} command(s) for turtle ${turtleID} (acknowledged)`);
turtle.pendingCommands = [];
}
res.json({ commands: [] });
}
} else {
res.json({ commands: [] });
}
@@ -267,6 +277,30 @@ app.get('/api/turtle/:id/commands', (req, res) => {
}
});
// Acknowledge commands were delivered (clears them)
app.post('/api/turtle/:id/commands/ack', (req, res) => {
try {
const turtleID = parseInt(req.params.id);
if (turtleData.has(turtleID)) {
const turtle = turtleData.get(turtleID);
const clearedCount = (turtle.pendingCommands || []).length;
if (clearedCount > 0) {
console.log(`✅ Turtle ${turtleID} acknowledged ${clearedCount} command(s)`);
turtle.pendingCommands = [];
}
res.json({ success: true, cleared: clearedCount });
} else {
res.status(404).json({ error: 'Turtle not found' });
}
} catch (error) {
console.error('❌ Error acknowledging commands:', error);
res.status(500).json({ error: error.message });
}
});
// Get all turtles
app.get('/api/turtles', (req, res) => {
res.json({