import config from './config.js'; import ACInfinityClient from './ac-client.js'; import WSClient from './ws-client.js'; console.log('='.repeat(50)); console.log('AC Infinity Agent'); console.log('='.repeat(50)); // Validate configuration if (!config.apiKey) { console.error('Error: API_KEY is required'); process.exit(1); } if (!config.acEmail || !config.acPassword) { console.error('Error: AC_EMAIL and AC_PASSWORD are required'); process.exit(1); } // Initialize clients const acClient = new ACInfinityClient( config.acApiHost, config.acEmail, config.acPassword ); const wsClient = new WSClient(config.serverUrl, config.apiKey); // Polling function async function pollSensors() { try { const readings = await acClient.getSensorReadings(); if (readings.length > 0) { console.log(`[Poll] Sending ${readings.length} readings`); wsClient.sendReadings(readings); } else { console.log('[Poll] No readings available'); } } catch (err) { console.error('[Poll] Error:', err.message); // Re-login if authentication failed if (err.message.includes('not logged in')) { console.log('[Poll] Attempting re-login...'); try { await acClient.login(); } catch (loginErr) { console.error('[Poll] Re-login failed:', loginErr.message); } } } } // Main function async function main() { try { // Login to AC Infinity await acClient.login(); // Connect to WebSocket server await wsClient.connect(); // Start polling console.log(`[Main] Starting polling every ${config.pollIntervalMs / 1000}s`); // Poll immediately await pollSensors(); // Then poll at interval setInterval(pollSensors, config.pollIntervalMs); } catch (err) { console.error('[Main] Fatal error:', err.message); process.exit(1); } } // Graceful shutdown function shutdown() { console.log('\n[Agent] Shutting down...'); wsClient.close(); process.exit(0); } process.on('SIGINT', shutdown); process.on('SIGTERM', shutdown); // Start main();