-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathmonitorConnection.js
More file actions
58 lines (49 loc) · 2.04 KB
/
Copy pathmonitorConnection.js
File metadata and controls
58 lines (49 loc) · 2.04 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
// Import required libraries
const axios = require('axios');
require('dotenv').config();
// Function to connect to the Pi Network
async function connectToPiNetwork() {
try {
const response = await axios.get(`${process.env.PI_NETWORK_URL}/api/connect`, {
headers: {
'Authorization': `Bearer ${process.env.PI_NETWORK_API_KEY}`
}
});
console.log('Connected to Pi Network:', response.data);
return true; // Return true if connected successfully
} catch (error) {
console.error('Error connecting to Pi Network:', error.response ? error.response.data : error.message);
return false; // Return false if connection failed
}
}
// Auto-reconnect logic with retry mechanism
async function autoReconnect(retries = process.env.RETRY_COUNT || 5, delay = process.env.RETRY_DELAY || 5000) {
retries = parseInt(retries, 10);
delay = parseInt(delay, 10);
for (let i = 0; i < retries; i++) {
console.log(`Attempting to connect to Pi Network... (Attempt ${i + 1})`);
const isConnected = await connectToPiNetwork();
if (isConnected) {
console.log('Successfully connected to Pi Network!');
return; // Exit if connected successfully
}
// Wait before retrying
console.log(`Retrying in ${delay / 1000} seconds...`);
await new Promise(resolve => setTimeout(resolve, delay));
}
console.error('Failed to connect to Pi Network after multiple attempts.');
}
// Function to monitor connection status
async function monitorConnection(interval = process.env.MONITOR_INTERVAL || 10000) {
interval = parseInt(interval, 10);
setInterval(async () => {
console.log('Checking connection status...');
const isConnected = await connectToPiNetwork();
if (!isConnected) {
console.log('Connection lost. Attempting to reconnect...');
await autoReconnect();
}
}, interval);
}
// Start monitoring the connection status
monitorConnection();