-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
261 lines (213 loc) · 6.69 KB
/
main.js
File metadata and controls
261 lines (213 loc) · 6.69 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
require('dotenv').config(); // for local testing only
const express = require('express');
const { createServer } = require('http');
const { Server } = require('socket.io');
const { spawn } = require('child_process');
const readline = require('readline');
const app = express();
const httpServer = createServer(app);
const io = new Server(httpServer, {
cors: {
origin: "*",
methods: ["GET", "POST"]
}
});
const PORT = process.env.PORT || 3000;
app.use(express.static('public'));
app.use(express.json());
let currentMode = { useRealHardware: false };
app.get('/api/mode', (req, res) => {
res.json(currentMode);
});
app.get('/api/hardware-status', async (req, res) => {
const bridgeUrl = process.env.BRIDGE_URL;
if (!bridgeUrl) {
return res.json({
bridge_online: false,
hardware_connected: false,
error: 'BRIDGE_URL not configured on Heroku'
});
}
try {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 10000);
const response = await fetch(`${bridgeUrl}/api/status`, {
signal: controller.signal
});
clearTimeout(timeout);
if (!response.ok) {
throw new Error(`Bridge returned ${response.status}`);
}
const data = await response.json();
res.json(data);
} catch (error) {
res.json({
bridge_online: false,
hardware_connected: false,
error: error.name === 'AbortError'
? 'Bridge timeout - is ngrok running?'
: `Bridge unreachable: ${error.message}`
});
}
});
app.post('/api/mode', (req, res) => {
const { useRealHardware } = req.body;
if (typeof useRealHardware !== 'boolean') {
return res.status(400).json({ success: false, error: 'useRealHardware must be a boolean' });
}
currentMode = { useRealHardware };
console.log(`Mode changed to: ${useRealHardware ? 'HARDWARE' : 'SIMULATION'}`);
if (pythonProcess) {
const proc = pythonProcess;
pythonProcess = null;
if (restartTimeout) {
clearTimeout(restartTimeout);
restartTimeout = null;
}
proc.kill();
}
if (!useRealHardware && io.engine.clientsCount > 0) {
startPythonStream();
}
io.emit('mode_changed', currentMode);
res.json({ success: true, useRealHardware });
});
let pythonProcess = null;
let restartTimeout = null;
let bridgeRequestPending = false;
async function forwardToBridge(data, socket) {
const bridgeUrl = process.env.BRIDGE_URL;
if (!bridgeUrl) {
return socket.emit('error', { message: 'BRIDGE_URL not configured' });
}
if (!Array.isArray(data.knob_values)) {
return socket.emit('error', { message: 'Invalid knob_values' });
}
if (bridgeRequestPending) return;
bridgeRequestPending = true;
try {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 60000); // Is there any wiser way to deal with this?
const response = await fetch(`${bridgeUrl}/api/hardware/execute`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ knob_values: data.knob_values }),
signal: controller.signal
});
clearTimeout(timeout);
if (!response.ok) {
throw new Error(`Bridge returned ${response.status}`);
}
const result = await response.json();
if (result.success && result.data) {
io.emit('numerical_data', result.data);
} else {
socket.emit('error', { message: result.error || 'Bridge error' });
}
} catch (error) {
const message = error.name === 'AbortError'
? 'Bridge timeout - is ngrok running?'
: `Bridge unreachable: ${error.message}`;
console.error('Bridge forwarding error:', message);
socket.emit('error', { message });
} finally {
bridgeRequestPending = false;
}
}
function startPythonStream() {
if (pythonProcess) {
console.log('Python process already running');
return;
}
console.log('Starting Python script...');
const pythonEnv = {
...process.env,
USE_REAL_HARDWARE: 'false'
};
pythonProcess = spawn('python', ['device_controller.py'], { env: pythonEnv });
pythonProcess.on('error', (err) => {
console.error('Failed to start Python process:', err);
pythonProcess = null;
});
const rl = readline.createInterface({ input: pythonProcess.stdout });
rl.on('line', (line) => {
try {
const parsed = JSON.parse(line);
console.log('Emitting data:', parsed);
io.emit('numerical_data', parsed);
} catch (e) {
console.warn('Non-JSON output from Python:', line);
}
});
pythonProcess.stderr.on('data', (data) => {
console.error(`Python stderr: ${data.toString()}`);
});
pythonProcess.on('exit', (code) => {
console.log(`Python script exited with code ${code}`);
const wasIntentional = (pythonProcess === null);
pythonProcess = null;
if (!wasIntentional && io.engine.clientsCount > 0) {
console.log('Unexpected exit, restarting in 2s...');
if (restartTimeout) clearTimeout(restartTimeout);
restartTimeout = setTimeout(() => {
restartTimeout = null;
startPythonStream();
}, 2000);
}
});
}
io.on('connection', (socket) => {
console.log('Client connected:', socket.id);
if (!pythonProcess && !currentMode.useRealHardware) {
startPythonStream();
}
socket.on('disconnect', () => {
console.log('Client disconnected:', socket.id);
if (io.engine.clientsCount === 0 && pythonProcess) {
console.log('Last client disconnected, stopping Python process.');
const proc = pythonProcess;
pythonProcess = null;
if (restartTimeout) {
clearTimeout(restartTimeout);
restartTimeout = null;
}
proc.kill();
}
});
// TouchDesigner sends { "knob_values": [v1, v2, v3] }
socket.on('knobs', (data) => {
if (currentMode.useRealHardware) {
forwardToBridge(data, socket).catch((err) => {
console.error('Error on the bridge side: ', err);
});
} else if (pythonProcess && pythonProcess.stdin) {
try {
pythonProcess.stdin.write(JSON.stringify(data) + '\n');
} catch (e) {
console.error('Failed to write to Python: ', e);
}
}
});
socket.on('request_data', () => {
console.log('Data requested by client');
if (!pythonProcess && !currentMode.useRealHardware) {
startPythonStream();
}
});
});
process.on('SIGTERM', () => {
console.log('SIGTERM received, shutting down...');
if (restartTimeout) {
clearTimeout(restartTimeout);
restartTimeout = null;
}
if (pythonProcess) {
const proc = pythonProcess;
pythonProcess = null;
proc.kill();
}
httpServer.close(() => process.exit(0));
});
httpServer.listen(PORT, () => {
console.log(`Socket.IO server running on port ${PORT}`);
});