Initial effects

This commit is contained in:
osiu97
2026-07-08 21:02:48 +02:00
parent 1a94ca3947
commit 0ef1e99daf
8 changed files with 243 additions and 78 deletions
+3 -2
View File
@@ -190,7 +190,8 @@ hamburger (`☰`) button. It contains `<button data-route="...">` nav items that
Centralised trajectory generation and streaming module.
- **Why**: Moving side-to-side linearly in joint space causes the arms to arc dangerously out-of-bounds at the top.
- **How it works**: Intercepts `Motion.goto(x, y)`, slices the Cartesian straight line into small segments (max `25 mm` by default, configurable in `Motion.CONFIG.SEGMENT_SIZE_MM`), and streams them to the ESP32.
- **Dynamic Blending**: It monitors `P:` positional updates from the ESP32 and fires the next waypoint *before* `AccelStepper` decelerates (when within `BLEND_THRESHOLD_STEPS`). This produces a seamless Cartesian trajectory with no MCU code changes and allows for future "visual flavor" movement effects (e.g. snaky, erratic).
- **Dynamic Blending**: It monitors `P:` positional updates from the ESP32 and fires the next waypoint *before* `AccelStepper` decelerates (when within `BLEND_THRESHOLD_STEPS`). This produces a seamless Cartesian trajectory with no MCU code changes.
- **Motion Effects**: The `Motion.goto(x, y, mode)` method accepts visual flavor modes (snaky, erratic, jumpy, hesitant, overshoot, random, direct). The system translates these into path perturbations and dynamic speed/acceleration modifiers (`SPD:` and `ACC:` BLE commands injected during execution) to create complex behavior over the linkage while maintaining safety limits.
- **Simulation Sync**: In simulation mode, `Motion.goto()` instantly updates its internal steps and manually dispatches a fake `ble:status` event containing `P:s1,s2`. This allows all UI components to effortlessly sync their visual state using their existing BLE listeners.
---
@@ -405,7 +406,7 @@ The router currently only has three routes. These sections need to be created/ex
### `board-control` section (implemented)
- Uses predefined background maps (SVG/PNG) with corresponding JSON config files specifying clickable coordinates in physical mm.
- Click a spot on the map or select from a compact list → IK move to coordinates.
- Supports movement modes (e.g., Direct, Erratic, Random, Snaky).
- Supports movement modes (e.g., Direct, Snaky, Erratic, Jumpy, Hesitant, Overshoot, Random).
- Requires arm to be homed; homing state is persisted across sessions via `localStorage`.
### `input-text` section (implemented)
+173 -67
View File
@@ -1,6 +1,7 @@
import BLE from './ble.js';
import IK from './kinematics.js';
import UI from './ui.js';
import Settings from './settings.js';
const CONFIG = {
SEGMENT_SIZE_MM: 25, // Maximum distance between waypoints to prevent out-of-bounds joint-space arcs
@@ -47,11 +48,19 @@ let motionQueue = [];
let isMoving = false;
let currentResolve = null;
let queueCheckInterval = null;
let currentMotionMode = 'direct';
let hasHesitated = false;
async function executeQueue() {
if (motionQueue.length === 0) {
isMoving = false;
if (queueCheckInterval) clearInterval(queueCheckInterval);
// Restore speed if it was altered
if (BLE.isConnected() && ['jumpy', 'hesitant', 'overshoot'].includes(currentMotionMode)) {
try { await BLE.write(`SPD:${Settings.speed}`); } catch(e){}
}
if (currentResolve) currentResolve(true);
currentResolve = null;
return;
@@ -60,102 +69,184 @@ async function executeQueue() {
isMoving = true;
let target = motionQueue.shift();
const cmd = `X:${target.s1},${target.s2}`;
if (BLE.isConnected()) {
try {
await BLE.write(cmd);
} catch (e) {
UI.log(`BLE error: ${e.message}`, 'error');
motionQueue = []; // clear queue on error
isMoving = false;
if (queueCheckInterval) clearInterval(queueCheckInterval);
if (currentResolve) currentResolve(false);
currentResolve = null;
return;
}
// Setup interval to monitor progress
if (queueCheckInterval) clearInterval(queueCheckInterval);
queueCheckInterval = setInterval(async () => {
// Calculate distance to target in steps
const dist1 = Math.abs(target.s1 - steps1);
const dist2 = Math.abs(target.s2 - steps2);
const maxDist = Math.max(dist1, dist2);
let delayBeforeSend = 0;
if (target.mode === 'hesitant' && target.fraction >= 0.45 && !hasHesitated) {
hasHesitated = true;
delayBeforeSend = 400;
} else if (target.mode === 'overshoot_settle') {
delayBeforeSend = 200; // brief pause before returning
}
if (motionQueue.length > 0) {
// We have more waypoints. Blend!
if (target.mode === 'direct') {
if (maxDist <= CONFIG.BLEND_THRESHOLD_STEPS) {
clearInterval(queueCheckInterval);
executeQueue(); // start next waypoint early
}
} else if (target.mode === 'erratic') {
if (maxDist <= 5) { // wait for full stop
clearInterval(queueCheckInterval);
setTimeout(executeQueue, 150); // slight pause for erratic effect
const doSend = async () => {
const cmd = `X:${target.s1},${target.s2}`;
if (BLE.isConnected()) {
if (target.mode === 'overshoot_settle') {
try { await BLE.write(`SPD:${Math.floor(Math.max(100, Settings.speed * 0.4))}`); } catch(e){}
}
try {
await BLE.write(cmd);
} catch (e) {
UI.log(`BLE error: ${e.message}`, 'error');
motionQueue = []; // clear queue on error
isMoving = false;
if (queueCheckInterval) clearInterval(queueCheckInterval);
if (currentResolve) currentResolve(false);
currentResolve = null;
return;
}
// Setup interval to monitor progress
if (queueCheckInterval) clearInterval(queueCheckInterval);
queueCheckInterval = setInterval(async () => {
// Calculate distance to target in steps
const dist1 = Math.abs(target.s1 - steps1);
const dist2 = Math.abs(target.s2 - steps2);
const maxDist = Math.max(dist1, dist2);
if (motionQueue.length > 0) {
// We have more waypoints. Blend or wait depending on mode.
if (target.mode === 'erratic') {
if (maxDist <= 5) { // wait for full stop
clearInterval(queueCheckInterval);
setTimeout(executeQueue, 50 + Math.random() * 100);
}
} else if (target.mode === 'jumpy') {
if (maxDist <= 5) { // stop and go rhythm
clearInterval(queueCheckInterval);
setTimeout(executeQueue, 100);
}
} else {
// direct, snaky, hesitant, etc default to direct blending
if (maxDist <= CONFIG.BLEND_THRESHOLD_STEPS) {
clearInterval(queueCheckInterval);
executeQueue();
}
}
} else {
// Default to direct blending
if (maxDist <= CONFIG.BLEND_THRESHOLD_STEPS) {
clearInterval(queueCheckInterval);
executeQueue();
// Last waypoint. Wait until closely reached.
if (maxDist <= 10) {
clearInterval(queueCheckInterval);
motionQueue = [];
executeQueue(); // Will trigger resolve
}
}
} else {
// Last waypoint. Wait until closely reached.
if (maxDist <= 10) {
clearInterval(queueCheckInterval);
motionQueue = [];
executeQueue(); // Will trigger resolve
}
}, 40); // check ~25 times a second
} else {
// Simulation: instantly jump to final target
const finalTarget = motionQueue.length > 0 ? motionQueue[motionQueue.length - 1] : target;
steps1 = finalTarget.s1;
steps2 = finalTarget.s2;
console.log(`[sim] Jumped to X:${steps1},${steps2} via trajectory`);
// Trigger pseudo-status event for the UI to update markers
document.dispatchEvent(new CustomEvent('ble:status', { detail: `P:${steps1},${steps2}` }));
motionQueue = [];
isMoving = false;
if (currentResolve) {
currentResolve(true);
currentResolve = null;
}
}, 40); // check ~25 times a second
} else {
// Simulation: instantly jump to final target
const finalTarget = motionQueue.length > 0 ? motionQueue[motionQueue.length - 1] : target;
steps1 = finalTarget.s1;
steps2 = finalTarget.s2;
console.log(`[sim] Jumped to X:${steps1},${steps2} via trajectory`);
// Trigger pseudo-status event for the UI to update markers
document.dispatchEvent(new CustomEvent('ble:status', { detail: `P:${steps1},${steps2}` }));
motionQueue = [];
isMoving = false;
if (currentResolve) {
currentResolve(true);
currentResolve = null;
}
};
if (delayBeforeSend > 0) {
setTimeout(doSend, delayBeforeSend);
} else {
doSend();
}
}
function buildSegments(startX, startY, endX, endY, mode) {
const dx = endX - startX;
const dy = endY - startY;
let actualEndX = endX;
let actualEndY = endY;
if (mode === 'overshoot') {
const totalDx = endX - startX;
const totalDy = endY - startY;
const totalDist = Math.sqrt(totalDx * totalDx + totalDy * totalDy);
if (totalDist > 0) {
actualEndX = endX + (totalDx / totalDist) * 15;
actualEndY = endY + (totalDy / totalDist) * 15;
const wsCheck = IK.checkWorkspace(actualEndX, actualEndY);
if (!wsCheck.ok) {
actualEndX = endX;
actualEndY = endY;
}
}
}
const dx = actualEndX - startX;
const dy = actualEndY - startY;
const distance = Math.sqrt(dx * dx + dy * dy);
let numSegments = Math.ceil(distance / CONFIG.SEGMENT_SIZE_MM);
if (mode === 'snaky' || mode === 'erratic') {
numSegments = Math.max(numSegments, Math.ceil(distance / 10)); // 10mm segments max for finer resolution
}
if (numSegments === 0) numSegments = 1;
let segs = [];
const nx = -dy / distance || 0;
const ny = dx / distance || 0;
for (let i = 1; i <= numSegments; i++) {
const fraction = i / numSegments;
const px = startX + dx * fraction;
const py = startY + dy * fraction;
let px = startX + dx * fraction;
let py = startY + dy * fraction;
if (mode === 'snaky') {
const cycles = Math.max(1, Math.floor(distance / 50));
const offset = Math.sin(fraction * Math.PI * 2 * cycles) * 15;
px += nx * offset;
py += ny * offset;
} else if (mode === 'erratic') {
px += (Math.random() - 0.5) * 10;
py += (Math.random() - 0.5) * 10;
}
const wsCheck = IK.checkWorkspace(px, py);
if (!wsCheck.ok) return null;
if (!wsCheck.ok) {
px = startX + dx * fraction;
py = startY + dy * fraction;
}
const res = IK.solve(px, py);
if (!res.reachable || IK.armsCrossed(res.theta1, res.theta2)) return null;
if (!res.reachable || IK.armsCrossed(res.theta1, res.theta2)) {
px = startX + dx * fraction;
py = startY + dy * fraction;
const fallbackRes = IK.solve(px, py);
if (!fallbackRes.reachable || IK.armsCrossed(fallbackRes.theta1, fallbackRes.theta2)) {
return null;
}
segs.push({
s1: IK.radToStepsAbsolute(fallbackRes.theta1, 1),
s2: IK.radToStepsAbsolute(fallbackRes.theta2, 2),
mode,
fraction
});
continue;
}
const s1 = IK.radToStepsAbsolute(res.theta1, 1);
const s2 = IK.radToStepsAbsolute(res.theta2, 2);
segs.push({ s1, s2, mode });
segs.push({ s1, s2, mode, fraction });
}
if (mode === 'overshoot') {
const res = IK.solve(endX, endY);
if (res.reachable && !IK.armsCrossed(res.theta1, res.theta2)) {
const s1 = IK.radToStepsAbsolute(res.theta1, 1);
const s2 = IK.radToStepsAbsolute(res.theta2, 2);
segs.push({ s1, s2, mode: 'overshoot_settle', fraction: 1.1 });
}
}
return segs;
}
@@ -170,6 +261,14 @@ async function goto(targetX, targetY, mode = 'direct') {
return false;
}
if (mode === 'random') {
const modes = ['direct', 'snaky', 'erratic', 'jumpy', 'hesitant', 'overshoot'];
mode = modes[Math.floor(Math.random() * modes.length)];
}
currentMotionMode = mode;
hasHesitated = false;
// Quick check on final destination
const destCheck = IK.checkWorkspace(targetX, targetY);
if (!destCheck.ok) {
@@ -218,6 +317,13 @@ async function goto(targetX, targetY, mode = 'direct') {
motionQueue = segments;
if (BLE.isConnected()) {
if (mode === 'jumpy' || mode === 'hesitant') {
const fastSpeed = Math.min(2000, Settings.speed * 1.5);
try { await BLE.write(`SPD:${Math.floor(fastSpeed)}`); } catch(e){}
}
}
return new Promise((resolve) => {
currentResolve = resolve;
executeQueue();
+11 -1
View File
@@ -1,6 +1,16 @@
import SequenceRunner from './sequence-runner.js';
import UI from './ui.js';
function getGlobalMode() {
const m1 = document.getElementById('mode-select');
if (m1) return m1.value;
const m2 = document.getElementById('seq-mode-select');
if (m2) return m2.value;
const m3 = document.getElementById('text-mode-select');
if (m3) return m3.value;
return 'direct';
}
export function buildQuickSequencesHTML() {
return `
<div class="card" id="quick-sequences-card" style="margin-bottom: 16px;">
@@ -49,7 +59,7 @@ export async function initQuickSequences(bgName, getSpots, getSteps, onStepCompl
if (seq) {
stopBtn.style.display = 'block';
const { steps1, steps2 } = getSteps();
await SequenceRunner.run(seq, getSpots(), steps1, steps2, onStepComplete);
await SequenceRunner.run(seq, getSpots(), steps1, steps2, getGlobalMode(), onStepComplete);
stopBtn.style.display = 'none';
}
});
+6 -3
View File
@@ -132,9 +132,12 @@ function buildHTML() {
<label class="form-label">Movement Mode</label>
<select id="mode-select" class="form-input" style="width:100%;">
<option value="direct">Direct (Normal)</option>
<option value="erratic">Erratic (Coming Soon)</option>
<option value="random">Random (Coming Soon)</option>
<option value="snaky">Snaky (Coming Soon)</option>
<option value="snaky">Snaky</option>
<option value="erratic">Erratic</option>
<option value="jumpy">Jumpy</option>
<option value="hesitant">Hesitant</option>
<option value="overshoot">Overshoot</option>
<option value="random">Random</option>
</select>
</div>
+16 -1
View File
@@ -128,6 +128,19 @@ function buildHTML() {
<option value="portrait-right">Right Side Test (Portrait)</option>
</select>
</div>
<div class="form-group" style="margin-bottom: 12px;">
<label class="form-label">Movement Mode</label>
<select id="text-mode-select" class="form-input" style="width:100%;">
<option value="direct">Direct (Normal)</option>
<option value="snaky">Snaky</option>
<option value="erratic">Erratic</option>
<option value="jumpy">Jumpy</option>
<option value="hesitant">Hesitant</option>
<option value="overshoot">Overshoot</option>
<option value="random">Random</option>
</select>
</div>
<!-- Settings -->
<div style="background: var(--surface-2); padding: 10px; border-radius: var(--radius-sm); margin-bottom: 12px;">
@@ -266,7 +279,9 @@ function delay(ms) {
async function executeMove(spot) {
UI.log(`Spelling: ${spot.label}`, 'info');
return await Motion.goto(spot.x, spot.y);
const modeEl = document.getElementById('text-mode-select');
const mode = modeEl ? modeEl.value : 'direct';
return await Motion.goto(spot.x, spot.y, mode);
}
async function spellText(text) {
+17 -1
View File
@@ -261,6 +261,19 @@ function buildHTML() {
</select>
<div style="font-size: 0.7rem; color: var(--text-muted); margin-top: 4px;">Provides available spots for the editor.</div>
</div>
<div class="form-group" style="margin-bottom: 12px;">
<label class="form-label">Global Movement Mode</label>
<select id="seq-mode-select" class="form-input" style="width:100%;">
<option value="direct">Direct (Normal)</option>
<option value="snaky">Snaky</option>
<option value="erratic">Erratic</option>
<option value="jumpy">Jumpy</option>
<option value="hesitant">Hesitant</option>
<option value="overshoot">Overshoot</option>
<option value="random">Random</option>
</select>
</div>
<div style="background: var(--surface-2); padding: 10px; border-radius: var(--radius-sm);">
<div class="setting-row">
@@ -671,8 +684,11 @@ export default {
btnPlay.style.display = 'none';
btnStop.style.display = 'inline-block';
const modeEl = document.getElementById('seq-mode-select');
const mode = modeEl ? modeEl.value : 'direct';
await sendSettings();
await SequenceRunner.run(sequence, spots, steps1, steps2, (s1, s2) => {
await SequenceRunner.run(sequence, spots, steps1, steps2, mode, (s1, s2) => {
steps1 = s1; steps2 = s2;
updatePositionReadout();
});
+15 -1
View File
@@ -195,7 +195,10 @@ async function moveToXY(targetX, targetY) {
return false;
}
return await Motion.goto(targetX, targetY);
const modeEl = document.getElementById('test-mode-select');
const mode = modeEl ? modeEl.value : 'direct';
return await Motion.goto(targetX, targetY, mode);
}
// ─────────────────────────────────────────────────────────────────
@@ -526,6 +529,17 @@ function buildHTML() {
<div class="card">
<div class="card-header"><span class="card-title">Move to XY</span></div>
<div style="display:flex;flex-direction:column;gap:8px">
<div class="form-group" style="margin-bottom: 4px;">
<select id="test-mode-select" class="form-input" style="width:100%; font-size: 0.9rem;">
<option value="direct">Effect: Direct</option>
<option value="snaky">Effect: Snaky</option>
<option value="erratic">Effect: Erratic</option>
<option value="jumpy">Effect: Jumpy</option>
<option value="hesitant">Effect: Hesitant</option>
<option value="overshoot">Effect: Overshoot</option>
<option value="random">Effect: Random</option>
</select>
</div>
<div style="display:flex;gap:6px;align-items:center">
<label class="form-label" style="width:18px">X</label>
<input class="form-input" type="number" id="input-x"
+2 -2
View File
@@ -14,7 +14,7 @@ export default {
get isRunning() { return isRunning; },
stop() { isRunning = false; },
async run(sequence, spotsData, currentSteps1, currentSteps2, onStepComplete) {
async run(sequence, spotsData, currentSteps1, currentSteps2, mode, onStepComplete) {
if (isRunning) {
UI.log('A sequence is already running.', 'warn');
return false;
@@ -55,7 +55,7 @@ export default {
UI.log(`Seq step: ${label}`, 'info');
const success = await Motion.goto(targetX, targetY, step.mode || 'direct');
const success = await Motion.goto(targetX, targetY, mode || 'direct');
if (!success) {
isRunning = false;
return false;