UNPKG

homebridge-pse-energy

Version:

Homebridge plugin to display Puget Sound Energy data via Opower API

67 lines (66 loc) 2.2 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.PSEClient = void 0; const node_fetch_1 = require("node-fetch"); class PSEClient { constructor(config) { this.config = config; this.headers = { 'Content-Type': 'application/json', 'Cookie': this.config.cookie, }; } async fetchUsageData() { const usageData = {}; const query = ` query($agreementIds: [ID!]!) { customerAgreements(agreementIds: $agreementIds) { agreementId usageSummary { currentUsage { value unit } projectedCost { value unit } } } } `; const agreementIds = [ this.config.electricityAgreementId, this.config.gasAgreementId, ].filter(Boolean); const body = JSON.stringify({ query, variables: { agreementIds }, }); const res = await (0, node_fetch_1.default)('https://pse.opower.com/ei/edge/apis/dsm-graphql-v1/cws/graphql', { method: 'POST', headers: this.headers, body, }); if (!res.ok) { throw new Error(`Failed to fetch data: ${res.status} ${res.statusText}`); } const json = await res.json(); for (const agreement of json.data?.customerAgreements || []) { const usage = parseFloat(agreement.usageSummary?.currentUsage?.value || '0'); const cost = parseFloat(agreement.usageSummary?.projectedCost?.value || '0'); const id = agreement.agreementId; if (id === this.config.electricityAgreementId) { usageData.electricityUsage = usage; usageData.electricityBill = cost; } else if (id === this.config.gasAgreementId) { usageData.gasUsage = usage; usageData.gasBill = cost; } } usageData.totalBill = (usageData.electricityBill || 0) + (usageData.gasBill || 0); return usageData; } } exports.PSEClient = PSEClient;