EverydayTech Platform - Developer Reference
Complete Source Code Documentation - All Applications
Loading...
Searching...
No Matches
check-meshcentral-devices.js
Go to the documentation of this file.
1const WebSocket = require('ws');
2const https = require('https');
3const { URL } = require('url');
4
5// Load environment variables
6require('dotenv').config();
7
8const MESHCENTRAL_URL = process.env.MESHCENTRAL_URL;
9const USERNAME = process.env.MESHCENTRAL_USERNAME;
10const PASSWORD = process.env.MESHCENTRAL_PASSWORD;
11
12/**
13 *
14 */
15async function login() {
16 const loginUrl = new URL('/login', MESHCENTRAL_URL);
17
18 const postData = `action=login&username=${encodeURIComponent(USERNAME)}&password=${encodeURIComponent(PASSWORD)}&token=`;
19
20 const options = {
21 method: 'POST',
22 headers: {
23 'Content-Type': 'application/x-www-form-urlencoded',
24 'Content-Length': Buffer.byteLength(postData)
25 }
26 };
27
28 return new Promise((resolve, reject) => {
29 const req = https.request(loginUrl, options, (res) => {
30 let cookie = null;
31
32 if (res.headers['set-cookie']) {
33 const cookies = res.headers['set-cookie'];
34 for (const c of cookies) {
35 if (c.startsWith('xid=')) {
36 cookie = c.split(';')[0].replace('xid=', '');
37 break;
38 }
39 }
40 }
41
42 let data = '';
43 res.on('data', chunk => data += chunk);
44 res.on('end', () => resolve(cookie));
45 });
46
47 req.on('error', reject);
48 req.write(postData);
49 req.end();
50 });
51}
52
53/**
54 *
55 * @param cookie
56 */
57async function connectWebSocket(cookie) {
58 const wsUrl = MESHCENTRAL_URL.replace('https://', 'wss://') + '/control.ashx';
59
60 console.log('šŸ”Œ Connecting to WebSocket:', wsUrl);
61 console.log('šŸ”‘ Using cookie:', cookie ? 'present' : 'missing');
62
63 const ws = new WebSocket(wsUrl, {
64 headers: {
65 'Cookie': `xid=${cookie}`
66 }
67 });
68
69 return new Promise((resolve, reject) => {
70 const timeout = setTimeout(() => {
71 ws.close();
72 reject(new Error('WebSocket connection timeout'));
73 }, 10000);
74
75 ws.on('open', () => {
76 console.log('āœ… WebSocket connected');
77 clearTimeout(timeout);
78
79 // Send authentication
80 ws.send(JSON.stringify({
81 action: 'authcookie',
82 cookie: cookie
83 }));
84
85 // Request nodes
86 setTimeout(() => {
87 console.log('šŸ“” Requesting nodes...');
88 ws.send(JSON.stringify({
89 action: 'nodes'
90 }));
91 }, 1000);
92
93 resolve(ws);
94 });
95
96 ws.on('message', (data) => {
97 try {
98 const msg = JSON.parse(data.toString());
99 console.log('šŸ“© Received:', JSON.stringify(msg, null, 2));
100
101 if (msg.action === 'nodes' || msg.nodes) {
102 console.log('\nāœ… Found devices:', Object.keys(msg.nodes || {}).length);
103 Object.entries(msg.nodes || {}).forEach(([id, node]) => {
104 console.log(` - ${node.name || id}: ${node.ip || 'no IP'} (${node.state || 'unknown state'})`);
105 });
106 ws.close();
107 }
108 } catch (err) {
109 console.log('šŸ“© Raw message:', data.toString());
110 }
111 });
112
113 ws.on('error', (err) => {
114 console.error('āŒ WebSocket error:', err.message);
115 clearTimeout(timeout);
116 reject(err);
117 });
118
119 ws.on('close', () => {
120 console.log('šŸ”Œ WebSocket closed');
121 clearTimeout(timeout);
122 });
123 });
124}
125
126/**
127 *
128 */
129async function main() {
130 try {
131 console.log('šŸ”§ Checking MeshCentral devices...\n');
132
133 const cookie = await login();
134 if (!cookie) {
135 throw new Error('Login failed - no cookie received');
136 }
137
138 console.log('āœ… Login successful\n');
139
140 await connectWebSocket(cookie);
141
142 setTimeout(() => {
143 console.log('\nā±ļø Timeout - no response from server');
144 process.exit(0);
145 }, 15000);
146
147 } catch (error) {
148 console.error('āŒ Error:', error.message);
149 process.exit(1);
150 }
151}
152
153main();