-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
413 lines (337 loc) · 14.5 KB
/
Copy pathserver.js
File metadata and controls
413 lines (337 loc) · 14.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
const express = require('express');
const http = require('http');
const WebSocket = require('ws');
const cors = require('cors');
const path = require('path');
const app = express();
const port = process.env.PORT || 5005;
app.use(cors());
app.use(express.json());
app.use(express.static(path.join(__dirname, 'public')));
// Store latest state in server memory
let latestState = {
x: 2500,
y: 2500,
rotation: 0,
action: 4,
monitors: [null, null, null, null, null, null, null],
timestamp: 0,
method: 'none'
};
let defaultMonitorDelayMs = 1500; // Default 1.5s delay between sequential monitors
let autoMonitorIndexCounter = 0;
// Create HTTP server
const server = http.createServer(app);
// Create WebSocket server attached to HTTP server
const wss = new WebSocket.Server({ noServer: true });
// Scheduled Broadcast function: sends absolute execution timestamp (executeAt) for sequential monitors
function broadcastScheduled(stateData, monitorDelayMs) {
const baseTime = Date.now();
const stepDelay = typeof monitorDelayMs === 'number' ? monitorDelayMs : defaultMonitorDelayMs;
const monitorsArr = Array.isArray(stateData.monitors) ? stateData.monitors : [];
let index = 0;
wss.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
// Use client's registered monitorIndex or fall back to client sequence
const monitorIndex = typeof client.monitorIndex === 'number' ? client.monitorIndex : index;
const executeAt = baseTime + (monitorIndex * stepDelay);
// Extract specific historical snapshot (x, y, rotation, action) for THIS monitor from the 1.5s Shift Queue
const item = monitorsArr[monitorIndex];
const targetSnapshot = (item && typeof item === 'object') ? item : (typeof item === 'number' ? { action: item } : null);
const scheduledPayload = {
type: 'state',
scheduledType: 'scheduled_state',
monitorIndex: monitorIndex,
executeAt: executeAt,
delayMs: stepDelay,
...stateData,
// Override state parameters so Monitor N receives THAT exact moment's X, Y, Rotation, and Action!
x: targetSnapshot && typeof targetSnapshot.x === 'number' ? targetSnapshot.x : stateData.x,
y: targetSnapshot && typeof targetSnapshot.y === 'number' ? targetSnapshot.y : stateData.y,
rotation: targetSnapshot && typeof targetSnapshot.rotation === 'number' ? targetSnapshot.rotation : stateData.rotation,
action: targetSnapshot && typeof targetSnapshot.action === 'number' ? targetSnapshot.action : stateData.action,
snapshot: targetSnapshot,
currentMonitorAction: targetSnapshot && typeof targetSnapshot.action === 'number' ? targetSnapshot.action : null,
globalAction: stateData.action
};
client.send(JSON.stringify(scheduledPayload));
index++;
}
});
}
// HTTP POST endpoint for state updates
app.post('/api/state', (req, res) => {
const { x, y, rotation, action, monitors, timestamp, monitorDelay } = req.body;
if (typeof x !== 'number' || typeof y !== 'number' || typeof rotation !== 'number') {
return res.status(400).json({ error: 'Invalid state format. Require x, y, rotation numbers.' });
}
const actionCode = typeof action === 'number' ? action : 4;
if (typeof monitorDelay === 'number') {
defaultMonitorDelayMs = monitorDelay;
}
latestState = {
x,
y,
rotation,
action: actionCode,
monitors: Array.isArray(monitors) ? monitors : [actionCode, null, null, null, null, null, null],
timestamp: timestamp || Date.now(),
method: 'HTTP POST'
};
// Log receipt in a formatted way
logState('HTTP', latestState);
// Broadcast with absolute timestamps to all WebSocket monitors (TouchDesigner)
broadcastScheduled(latestState, defaultMonitorDelayMs);
res.json({ status: 'ok', received: latestState, monitorDelay: defaultMonitorDelayMs });
});
// Enhanced HTTP GET endpoint supporting per-monitor index queries (?monitor=N or /api/state/N)
app.get(['/api/state', '/api/state/:monitorIndex'], (req, res) => {
const reqMon = req.params.monitorIndex !== undefined ? req.params.monitorIndex : req.query.monitor;
const mons = Array.isArray(latestState.monitors) ? latestState.monitors : [latestState.action, null, null, null, null, null, null];
if (reqMon !== undefined && reqMon !== null && reqMon !== '') {
const mIdx = parseInt(reqMon, 10);
if (!isNaN(mIdx) && mIdx >= 0 && mIdx < 7) {
const item = mons[mIdx];
const snapshot = (item && typeof item === 'object') ? item : { action: item, x: latestState.x, y: latestState.y, rotation: latestState.rotation };
const executeAt = latestState.timestamp + (mIdx * defaultMonitorDelayMs);
return res.json({
status: 'ok',
monitorIndex: mIdx,
executeAt: executeAt,
delayMs: defaultMonitorDelayMs,
x: snapshot && typeof snapshot.x === 'number' ? snapshot.x : latestState.x,
y: snapshot && typeof snapshot.y === 'number' ? snapshot.y : latestState.y,
rotation: snapshot && typeof snapshot.rotation === 'number' ? snapshot.rotation : latestState.rotation,
action: snapshot && typeof snapshot.action === 'number' ? snapshot.action : latestState.action,
snapshot: snapshot,
globalState: latestState
});
}
}
res.json({
...latestState,
monitorDelay: defaultMonitorDelayMs,
monitorActions: {
"0": mons[0] !== undefined ? mons[0] : null,
"1": mons[1] !== undefined ? mons[1] : null,
"2": mons[2] !== undefined ? mons[2] : null,
"3": mons[3] !== undefined ? mons[3] : null,
"4": mons[4] !== undefined ? mons[4] : null,
"5": mons[5] !== undefined ? mons[5] : null,
"6": mons[6] !== undefined ? mons[6] : null
}
});
});
server.on('upgrade', (request, socket, head) => {
if (request.url === '/ws') {
wss.handleUpgrade(request, socket, head, (ws) => {
wss.emit('connection', ws, request);
});
} else {
socket.destroy();
}
});
wss.on('connection', (ws) => {
// Assign default sequential monitor index
ws.monitorIndex = autoMonitorIndexCounter++;
console.log(`\x1b[36m[WS] Client connected (Assigned Monitor Index: ${ws.monitorIndex})\x1b[0m`);
// Send latest state to newly connected client (TouchDesigner) immediately
const initialExecuteAt = Date.now() + (ws.monitorIndex * defaultMonitorDelayMs);
ws.send(JSON.stringify({
type: 'state',
scheduledType: 'scheduled_state',
monitorIndex: ws.monitorIndex,
executeAt: initialExecuteAt,
delayMs: defaultMonitorDelayMs,
...latestState
}));
ws.on('message', (message) => {
try {
const data = JSON.parse(message);
// Handle client registration / monitor index override
if (data.type === 'register') {
if (typeof data.monitorIndex === 'number') {
ws.monitorIndex = data.monitorIndex;
console.log(`\x1b[32m[WS] Client updated Monitor Index to ${ws.monitorIndex}\x1b[0m`);
ws.send(JSON.stringify({ status: 'registered', monitorIndex: ws.monitorIndex }));
}
return;
}
const { x, y, rotation, action, timestamp, monitorDelay } = data;
const actionCode = typeof action === 'number' ? action : 4;
if (typeof monitorDelay === 'number') {
defaultMonitorDelayMs = monitorDelay;
}
latestState = { x, y, rotation, action: actionCode, timestamp: timestamp || Date.now(), method: 'WebSocket' };
logState('WS', latestState);
// Broadcast scheduled state to all connected clients
broadcastScheduled(latestState, defaultMonitorDelayMs);
// Echo back acknowledgment to sender
ws.send(JSON.stringify({ status: 'ack', timestamp: latestState.timestamp }));
} catch (err) {
ws.send(JSON.stringify({ error: 'Invalid JSON format' }));
}
});
ws.on('close', () => {
console.log(`\x1b[31m[WS] Client disconnected (Monitor Index was: ${ws.monitorIndex})\x1b[0m`);
});
});
// Helper function to print values with nice formatting in console
function logState(type, state) {
const timeStr = new Date(state.timestamp).toISOString().split('T')[1].slice(0, -1);
const xStr = state.x.toFixed(1).padStart(6, ' ');
const yStr = state.y.toFixed(1).padStart(6, ' ');
const rStr = state.rotation.toFixed(0).padStart(3, ' ');
const aStr = String(state.action !== undefined ? state.action : 4).padStart(2, ' ');
const monStr = Array.isArray(state.monitors)
? state.monitors.map((m, idx) => m === null ? `M${idx}:Null` : `M${idx}:A${m.action}(${m.x.toFixed(0)},${m.y.toFixed(0)},${m.rotation}°)`).join(' ')
: '';
let typeColor = '\x1b[33m'; // Default Yellow
if (type === 'WS') typeColor = '\x1b[32m'; // Green
if (type === 'SERIAL') typeColor = '\x1b[36m'; // Cyan
console.log(`${typeColor}[${type}]\x1b[0m Time: ${timeStr} | Pos: (\x1b[35mX:${xStr}\x1b[0m, \x1b[35mY:${yStr}\x1b[0m) | Angle: \x1b[36m${rStr}°\x1b[0m | Action: \x1b[33m${aStr}\x1b[0m | Monitors: [\x1b[32m${monStr}\x1b[0m]`);
}
// --- Serial Port Integration (Node.js backend) ---
let SerialPort = null;
let ReadlineParser = null;
try {
const serialModule = require('serialport');
const parserModule = require('@serialport/parser-readline');
SerialPort = serialModule.SerialPort;
ReadlineParser = parserModule.ReadlineParser;
} catch (e) {
console.log('\x1b[33m[SERIAL] serialport module not available or native dependencies missing.\x1b[0m');
}
let activeSerialPort = null;
let activeSerialParser = null;
let activePortPath = null;
function parseSerialLine(line) {
const trimmed = line.trim();
if (!trimmed) return null;
let x = null, y = null, rotation = null, action = 4;
// 1. Try JSON format: {"x":2500, "y":2500, "rotation":90}
if (trimmed.startsWith('{') && trimmed.endsWith('}')) {
try {
const obj = JSON.parse(trimmed);
if (typeof obj.x === 'number') x = obj.x;
if (typeof obj.y === 'number') y = obj.y;
if (typeof obj.rotation === 'number') rotation = obj.rotation;
else if (typeof obj.r === 'number') rotation = obj.r;
else if (typeof obj.deg === 'number') rotation = obj.deg;
if (typeof obj.action === 'number') action = obj.action;
else if (typeof obj.a === 'number') action = obj.a;
} catch (err) {}
}
// 2. Try Tagged Key-Value format: X:2500 Y:2500 R:90
if (x === null || y === null || rotation === null) {
const xMatch = trimmed.match(/(?:x|posx|x_val)[:=]\s*(-?\d+(?:\.\d+)?)/i);
const yMatch = trimmed.match(/(?:y|posy|y_val)[:=]\s*(-?\d+(?:\.\d+)?)/i);
const rMatch = trimmed.match(/(?:r|rot|deg|angle|rotation)[:=]\s*(-?\d+(?:\.\d+)?)/i);
const aMatch = trimmed.match(/(?:a|act|action)[:=]\s*(\d+)/i);
if (xMatch) x = parseFloat(xMatch[1]);
if (yMatch) y = parseFloat(yMatch[1]);
if (rMatch) rotation = parseFloat(rMatch[1]);
if (aMatch) action = parseInt(aMatch[1], 10);
}
// 3. Try CSV format: 508, 10, 179 or 2500, 2500, 90
if (x === null || y === null || rotation === null) {
const parts = trimmed.split(/[\s,]+/).filter(Boolean);
if (parts.length >= 3) {
const v1 = parseFloat(parts[0]);
const v2 = parseFloat(parts[1]);
const v3 = parseFloat(parts[2]);
if (!isNaN(v1) && !isNaN(v2) && !isNaN(v3)) {
// Default to Y, Rotation, X (1:Y, 2:Rotation, 3:X) -> Swapped X and Y
y = v1;
rotation = v2;
x = v3;
if (parts.length >= 4 && !isNaN(parseInt(parts[3]))) {
action = parseInt(parts[3], 10);
}
}
}
}
if (x !== null && y !== null && rotation !== null) {
x = Math.max(0, Math.min(5000, x));
y = Math.max(0, Math.min(5000, y));
rotation = ((rotation % 360) + 360) % 360;
return { x, y, rotation, action, timestamp: Date.now(), method: 'SerialPort' };
}
return null;
}
// Endpoint: List available serial ports
app.get('/api/serial/ports', async (req, res) => {
if (!SerialPort) {
return res.status(501).json({ error: 'SerialPort module not installed on server' });
}
try {
const ports = await SerialPort.list();
res.json({ ports });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// Endpoint: Get active serial status
app.get('/api/serial/status', (req, res) => {
res.json({
connected: !!(activeSerialPort && activeSerialPort.isOpen),
port: activePortPath
});
});
// Endpoint: Connect to serial port
app.post('/api/serial/connect', (req, res) => {
if (!SerialPort) {
return res.status(501).json({ error: 'SerialPort module not installed on server' });
}
const { path: portPath, baudRate } = req.body;
if (!portPath) {
return res.status(400).json({ error: 'port path is required' });
}
// Close existing port if open
if (activeSerialPort && activeSerialPort.isOpen) {
try { activeSerialPort.close(); } catch (e) {}
}
const rate = parseInt(baudRate, 10) || 115200;
try {
activeSerialPort = new SerialPort({ path: portPath, baudRate: rate });
activeSerialParser = activeSerialPort.pipe(new ReadlineParser({ delimiter: '\n' }));
activePortPath = portPath;
activeSerialParser.on('data', (line) => {
const parsed = parseSerialLine(line);
if (parsed) {
latestState = parsed;
logState('SERIAL', latestState);
broadcastScheduled(latestState, defaultMonitorDelayMs);
}
});
activeSerialPort.on('error', (err) => {
console.error(`\x1b[31m[SERIAL] Error on ${portPath}: ${err.message}\x1b[0m`);
});
activeSerialPort.on('close', () => {
console.log(`\x1b[33m[SERIAL] Connection closed: ${portPath}\x1b[0m`);
activePortPath = null;
});
console.log(`\x1b[32m[SERIAL] Connected to ${portPath} at ${rate} bps\x1b[0m`);
res.json({ status: 'connected', port: portPath, baudRate: rate });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// Endpoint: Disconnect serial port
app.post('/api/serial/disconnect', (req, res) => {
if (activeSerialPort && activeSerialPort.isOpen) {
activeSerialPort.close((err) => {
if (err) return res.status(500).json({ error: err.message });
activePortPath = null;
res.json({ status: 'disconnected' });
});
} else {
res.json({ status: 'already disconnected' });
}
});
server.listen(port, () => {
console.log(`\n\x1b[1;32m====================================================\x1b[0m`);
console.log(`\x1b[1;32m 5Hz API Control Server running on port ${port} \x1b[0m`);
console.log(`\x1b[1;32m Web Interface: http://localhost:${port} \x1b[0m`);
console.log(`\x1b[1;32m====================================================\x1b[0m\n`);
});