-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
98 lines (77 loc) · 2.77 KB
/
index.js
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
import express from 'express';
import http from 'http';
import { Server as SocketIo } from 'socket.io';
import os from 'os';
import osUtils from 'os-utils';
import { exec } from 'child_process';
import ora from 'ora';
import chalk from 'chalk';
const app = express();
const server = http.createServer(app);
const io = new SocketIo(server);
app.use(express.static(new URL('./public', import.meta.url).pathname));
const loadingAnimation = () => {
const frames = ['🌱', '🚀', '💻', '⚙️', '🌍'];
let i = 0;
const spinner = ora('Initializing...').start();
const interval = setInterval(() => {
spinner.text = `${frames[i++ % frames.length]} Initializing...`;
}, 200);
return { interval, spinner };
};
function getMetrics() {
return new Promise((resolve) => {
const tempCommand = "vcgencmd measure_temp";
exec(tempCommand, (error, stdout) => {
let temp = stdout.trim().replace('temp=', '').replace("'C", '');
if (error) {
temp = 'N/A';
}
// Get CPU usage
osUtils.cpuUsage((cpuUsage) => {
const totalMemory = os.totalmem();
const freeMemory = os.freemem();
const ramUsage = ((totalMemory - freeMemory) / totalMemory * 100).toFixed(2);
const uptimeInSeconds = os.uptime();
const uptimeInMinutes = (uptimeInSeconds / 60).toFixed(2);
resolve({
temp: temp,
cpuUsage: (cpuUsage * 100).toFixed(2),
ramUsage: ramUsage,
uptime: uptimeInMinutes
});
});
});
});
}
// Handle WebSocket connections
io.on('connection', (socket) => {
console.log(chalk.green('Client connected'));
const interval = setInterval(async () => {
const metrics = await getMetrics();
socket.emit('update_metrics', metrics);
}, 1000);
socket.on('reboot_pi', () => {
console.log('Rebooting Raspberry Pi...');
exec('sudo reboot', (error, stdout, stderr) => {
if (error) {
console.error(`Error executing reboot: ${error.message}`);
return;
}
console.log(`Reboot stdout: ${stdout}`);
});
});
socket.on('disconnect', () => {
clearInterval(interval);
console.log(chalk.red('Client disconnected'));
});
});
const PORT = 4000;
const { interval, spinner } = loadingAnimation();
setTimeout(() => {
server.listen(PORT, () => {
clearInterval(interval); // Stop loading animation
spinner.succeed(chalk.green(`Server running on port ${PORT}`));
console.log(chalk.cyan('--- System Metrics Monitoring Started ---'));
});
}, 1000);