feat: Add setTurtleState and execOnTurtle functions for REST API integration

This commit is contained in:
MayaTheShy
2026-02-20 02:02:40 -05:00
parent df00a6be70
commit 67498b93bf

View File

@@ -172,7 +172,7 @@ export const useTurtleStore = create((set, get) => ({
sendCommand: async (turtleId, command, param = null) => {
const { ws } = get();
console.log(`🎮 Sending command to turtle ${turtleId}: ${command}`, param ? `(param: ${param})` : '');
console.log(`🎮 Sending command to turtle ${turtleId}: ${command}`, param ? `(param: ${JSON.stringify(param)})` : '');
if (ws && ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({
@@ -198,6 +198,49 @@ export const useTurtleStore = create((set, get) => ({
}
},
// Set turtle state machine state via REST API
setTurtleState: async (turtleId, stateName, stateData = {}) => {
console.log(`🔄 Setting state for turtle ${turtleId}: ${stateName}`, stateData);
try {
const response = await fetch(`${API_URL}/turtle/${turtleId}/state`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ state: stateName, data: stateData })
});
const result = await response.json();
console.log(' ✅ State set:', result);
return result;
} catch (error) {
console.error(' ❌ Error setting state:', error);
// Fallback: send via WebSocket as a command
const { ws } = get();
if (ws && ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({
type: 'command',
turtleID: turtleId,
command: 'set_state',
param: { state: stateName, data: stateData }
}));
}
}
},
// Execute arbitrary Lua code on a turtle
execOnTurtle: async (turtleId, code) => {
console.log(`💻 Exec on turtle ${turtleId}:`, code);
try {
const response = await fetch(`${API_URL}/turtle/${turtleId}/exec`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ code })
});
return await response.json();
} catch (error) {
console.error(' ❌ Error executing:', error);
return { success: false, error: error.message };
}
},
// Helper getters
getTurtleArray: () => {
return Object.values(get().turtles);