Files
appRobotHoming/server/robotActions.js
2026-06-13 00:00:18 +02:00

70 lines
3.1 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* robotActions.js Roboter-Bewegungsaktionen
*
* Alle Bewegungsbefehle laufen hier durch, bevor sie ans Roboter-Backend
* weitergeleitet werden (ROBOT_URL). Solange ROBOT_URL nicht konfiguriert
* ist, werden die Aktionen nur geloggt und eine Stub-Antwort zurückgegeben.
*
* Joint-Namen: 'x-axis' | 'arm1' | 'arm2' | 'elbow' | 'hand'
* Directions: 'left' | 'right' (x-axis, linear)
* 'cw' | 'ccw' (alle Gelenke, rotatorisch)
*/
const ROBOT_URL = process.env.ROBOT_URL || '';
// ── Validierung ───────────────────────────────────────────────────────────────
const VALID_JOINTS = new Set(['x-axis', 'arm1', 'arm2', 'elbow', 'hand']);
const VALID_DIRECTIONS = new Set(['left', 'right', 'cw', 'ccw']);
function validateMove({ joint, direction, steps = 1 }) {
if (!joint) return '"joint" fehlt';
if (!direction) return '"direction" fehlt';
if (!VALID_JOINTS.has(joint)) return `Unbekanntes Joint: "${joint}"`;
if (!VALID_DIRECTIONS.has(direction)) return `Unbekannte Richtung: "${direction}"`;
if (typeof steps !== 'number' || steps < 1 || steps > 100)
return '"steps" muss eine Zahl zwischen 1 und 100 sein';
return null; // ok
}
// ── Ausführung ────────────────────────────────────────────────────────────────
/**
* Sendet einen Bewegungsbefehl.
* Gibt { ok, joint, direction, steps, message } zurück oder wirft einen Fehler.
*/
export async function executeMove({ joint, direction, steps = 1 }) {
const err = validateMove({ joint, direction, steps });
if (err) throw Object.assign(new Error(err), { statusCode: 400 });
const payload = { joint, direction, steps };
console.log(`[robotActions] move: ${JSON.stringify(payload)}`);
if (ROBOT_URL) {
// ── Weiterleitung an das Roboter-Backend ─────────────────────────────────
const url = new URL('/api/move', ROBOT_URL).toString();
const res = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
});
if (!res.ok) {
const text = await res.text().catch(() => '');
throw Object.assign(
new Error(`Robot-Backend: ${res.status} ${text}`),
{ statusCode: 502 }
);
}
const data = await res.json();
return { ok: true, joint, direction, steps, ...data };
}
// ── Stub (ROBOT_URL nicht konfiguriert) ───────────────────────────────────
const label = joint === 'x-axis'
? `X-Achse ${direction === 'left' ? '⬅' : '➡'}`
: `${joint} ${direction === 'ccw' ? '↺ Rauf' : 'Runter ↻'}`;
const message = `[Stub] ${label} ${steps} Schritt(e). ROBOT_URL nicht konfiguriert.`;
console.warn(`[robotActions] ${message}`);
return { ok: true, stub: true, joint, direction, steps, message };
}