-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
300 lines (257 loc) · 7.75 KB
/
server.js
File metadata and controls
300 lines (257 loc) · 7.75 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
import express from 'express';
import cors from 'cors';
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import WebSocket from 'ws';
import multer from 'multer';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const app = express();
const PORT = 3001;
const WS_PORT = 24; // WebSocket port from config.ini
// Middleware
app.use(cors());
app.use(express.json());
// WebSocket connection to machine
let ws = null;
let wsConnected = false;
const connectWebSocket = () => {
ws = new WebSocket(`ws://localhost:${WS_PORT}`);
ws.on('open', () => {
wsConnected = true;
console.log(`Connected to machine at ws://localhost:${WS_PORT}`);
});
ws.on('message', (data) => {
console.log('Machine response:', data.toString());
});
ws.on('error', (error) => {
console.error('Machine connection error:', error.message);
wsConnected = false;
});
ws.on('close', () => {
console.log('Machine disconnected. Reconnecting in 5s...');
wsConnected = false;
setTimeout(connectWebSocket, 5000);
});
};
// Initialize WebSocket connection
connectWebSocket();
// Ensure config directory exists
const configDir = path.join(__dirname, 'config');
if (!fs.existsSync(configDir)) {
fs.mkdirSync(configDir, { recursive: true });
}
// Ensure gcode directory exists
const gcodeDir = path.join(__dirname, 'gcode');
if (!fs.existsSync(gcodeDir)) {
fs.mkdirSync(gcodeDir, { recursive: true });
}
// Configure multer for file uploads
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, gcodeDir);
},
filename: (req, file, cb) => {
// Keep original filename
cb(null, file.originalname);
}
});
const upload = multer({
storage: storage,
fileFilter: (req, file, cb) => {
// Accept .gcode, .nc, .txt, .g, .gc files
const ext = path.extname(file.originalname).toLowerCase();
if (ext === '.gcode' || ext === '.nc' || ext === '.txt' || ext === '.g' || ext === '.gc') {
cb(null, true);
} else {
cb(new Error('Only .gcode, .nc, .g, .gc, or .txt files are allowed'));
}
}
});
// POST endpoint to save config.ini
app.post('/api/config/save', (req, res) => {
try {
const { content, filename } = req.body;
if (!content || !filename) {
return res.status(400).json({ error: 'Missing content or filename' });
}
const filePath = path.join(configDir, filename);
// Write the config file
fs.writeFileSync(filePath, content, 'utf8');
console.log(`Config saved successfully to: ${filePath}`);
res.json({
success: true,
message: 'Config saved successfully',
path: filePath
});
} catch (error) {
console.error('Error saving config:', error);
res.status(500).json({
error: 'Failed to save config',
details: error.message
});
}
});
// GET endpoint to read config.ini
app.get('/api/config/load', (req, res) => {
try {
const filePath = path.join(configDir, 'config.ini');
if (!fs.existsSync(filePath)) {
return res.status(404).json({ error: 'Config file not found' });
}
const content = fs.readFileSync(filePath, 'utf8');
res.json({ success: true, content });
} catch (error) {
console.error('Error loading config:', error);
res.status(500).json({
error: 'Failed to load config',
details: error.message
});
}
});
// POST endpoint to upload G-code file
app.post('/api/gcode/upload', upload.single('file'), (req, res) => {
try {
if (!req.file) {
return res.status(400).json({ error: 'No file uploaded' });
}
console.log(`G-code file uploaded: ${req.file.filename} (${req.file.size} bytes)`);
res.json({
success: true,
message: 'File uploaded successfully',
fileName: req.file.filename,
fileSize: `${(req.file.size / 1024).toFixed(1)}kb`
});
} catch (error) {
console.error('Error uploading file:', error);
res.status(500).json({
error: 'Failed to upload file',
details: error.message
});
}
});
// GET endpoint to list all G-code files
app.get('/api/gcode/files', (req, res) => {
try {
const files = fs.readdirSync(gcodeDir).map(filename => {
const filePath = path.join(gcodeDir, filename);
const stats = fs.statSync(filePath);
return {
name: filename,
size: `${(stats.size / 1024).toFixed(1)}kb`,
modified: stats.mtime
};
});
res.json({ success: true, files });
} catch (error) {
console.error('Error listing files:', error);
res.status(500).json({
error: 'Failed to list files',
details: error.message
});
}
});
// GET endpoint to load a specific G-code file
app.get('/api/gcode/load/:filename', (req, res) => {
try {
const filename = req.params.filename;
const filePath = path.join(gcodeDir, filename);
if (!fs.existsSync(filePath)) {
return res.status(404).json({ error: 'File not found' });
}
const fileContent = fs.readFileSync(filePath, 'utf8');
const lines = fileContent.split('\n').filter(line => line.trim());
const stats = fs.statSync(filePath);
res.json({
success: true,
fileName: filename,
fileSize: `${(stats.size / 1024).toFixed(1)}kb`,
totalLines: lines.length,
gCodeLines: lines
});
} catch (error) {
console.error('Error loading file:', error);
res.status(500).json({
error: 'Failed to load file',
details: error.message
});
}
});
// GET endpoint to download a G-code file
app.get('/api/gcode/download/:filename', (req, res) => {
try {
const filename = req.params.filename;
const filePath = path.join(gcodeDir, filename);
if (!fs.existsSync(filePath)) {
return res.status(404).json({ error: 'File not found' });
}
res.download(filePath, filename);
} catch (error) {
console.error('Error downloading file:', error);
res.status(500).json({
error: 'Failed to download file',
details: error.message
});
}
});
// DELETE endpoint to delete a G-code file
app.delete('/api/gcode/delete/:filename', (req, res) => {
try {
const filename = req.params.filename;
const filePath = path.join(gcodeDir, filename);
if (!fs.existsSync(filePath)) {
return res.status(404).json({ error: 'File not found' });
}
fs.unlinkSync(filePath);
console.log(`G-code file deleted: ${filename}`);
res.json({
success: true,
message: 'File deleted successfully'
});
} catch (error) {
console.error('Error deleting file:', error);
res.status(500).json({
error: 'Failed to delete file',
details: error.message
});
}
});
// POST endpoint to send G-code commands
app.post('/api/gcode/send', (req, res) => {
try {
const { command } = req.body;
if (!command) {
return res.status(400).json({ error: 'Missing command' });
}
console.log(`G-code: ${command}`);
// Send command via WebSocket
if (wsConnected && ws.readyState === WebSocket.OPEN) {
ws.send(command);
console.log(`Sent to machine: ${command}`);
res.json({
success: true,
message: 'Command sent',
command: command
});
} else {
console.warn('Machine not connected. Command logged only.');
res.json({
success: false,
message: 'Machine not connected',
command: command
});
}
} catch (error) {
console.error('Error sending G-code:', error);
res.status(500).json({
error: 'Failed to send command',
details: error.message
});
}
});
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
console.log(`Config directory: ${configDir}`);
console.log(`G-code directory: ${gcodeDir}`);
});