diff --git a/src/app.ts b/src/app.ts index d1b126d..2aa8bd4 100644 --- a/src/app.ts +++ b/src/app.ts @@ -7,6 +7,7 @@ import { fileURLToPath } from 'url'; import { Config } from './config.js'; import { mqtt as MQTT } from './mqtt.js'; import { createServer } from './server.js'; +import { xfinityUsage } from './xfinity.js'; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); @@ -21,6 +22,7 @@ try { process.exit(1); } +export let usage: xfinityUsage | undefined; const { xfinity: xfinityConfig, mqtt: mqttConfig, imap: imapConfig } = config.getConfig(); const intervalMs = xfinityConfig.interval * 60000; const fetch = () => { @@ -34,6 +36,7 @@ const fetch = () => { break; case 'usage': console.log('Usage updated'); + usage = data.usage as xfinityUsage; eventBus.emit(DATA_UPDATED, data.usage); break; case 'error': @@ -42,6 +45,7 @@ const fetch = () => { break; } if (['usage', 'error'].includes(type)) { + xfinity.kill(); console.log(`Next fetch in ${xfinityConfig.interval} minutes @ ${nextAt}`); } }); @@ -51,7 +55,7 @@ fetch(); setInterval(fetch, intervalMs); if (config.useHttp) { - createServer(eventBus); + createServer(); } if (config.useMqtt && mqttConfig) { diff --git a/src/server.ts b/src/server.ts index 6dd988d..bb41f95 100644 --- a/src/server.ts +++ b/src/server.ts @@ -1,21 +1,14 @@ -import EventEmitter from 'events'; import Http from 'http'; -import { URL } from 'url'; -import { DATA_UPDATED } from './app.js'; -import { xfinityUsage } from './xfinity.js'; +import { usage } from './app.js'; -let usage: xfinityUsage | undefined; - -export const createServer = (eventBus: EventEmitter): void => { +export const createServer = (): void => { Http.createServer((req, res) => { - const url = new URL(req.url ?? ''); - const path = url.pathname; - const homeassistant = path === '/homeassistant'; + const homeassistant = req.url === '/homeassistant'; - console.log(`HTTP request: ${path}`); + console.log(`HTTP request: ${req.url}`); - if (path !== '/' && !homeassistant) { + if (req.url !== '/' && !homeassistant) { res.writeHead(404); res.end(); return; @@ -49,8 +42,4 @@ export const createServer = (eventBus: EventEmitter): void => { res.end(); }).listen(7878); console.log('http server started'); - - eventBus.on(DATA_UPDATED, (data: xfinityUsage) => { - usage = data; - }); };