@balmli/homey-utility-prices 0.0.0-stage → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,10 @@
1
+ {
2
+ "permissions": {
3
+ "allow": [
4
+ "Bash(npm run build)",
5
+ "Bash(npm test)"
6
+ ],
7
+ "deny": [],
8
+ "ask": []
9
+ }
10
+ }
package/.mocharc.json ADDED
@@ -0,0 +1,9 @@
1
+ {
2
+ "node-option": [
3
+ "import=tsx"
4
+ ],
5
+ "spec": [
6
+ "tests/**/*.*"
7
+ ],
8
+ "timeout": 10000
9
+ }
package/.nvmrc ADDED
@@ -0,0 +1 @@
1
+ 24
package/AGENT.md ADDED
@@ -0,0 +1,37 @@
1
+ # AI Agent Guide
2
+
3
+ Welcome! This document captures the minimum context an AI coding agent needs before touching `@balmli/homey-utility-prices`.
4
+
5
+ ## Project Snapshot
6
+ - TypeScript sources live under `lib/`; compiled CJS + typings are emitted to `dist/`.
7
+ - Tests run with `mocha` + `tsx` (config in `.mocharc.json`). Primary entry points are `lib/NordpoolApi.ts`, `lib/PriceApi.ts`, and `lib/PriceComparer.ts`.
8
+ - The package fetches day-ahead electricity prices from Nord Pool’s Data Portal, caches data in Homey device storage, and exposes helpers for price analytics and heating automation.
9
+
10
+ ## Task Workflow
11
+ 1. **Inspect Before Editing**
12
+ - Skim `lib/` and current tests to confirm assumptions.
13
+ - Check `README.md` and `specs/quarter-hour-support.md` for background on the upcoming 15-minute slot change.
14
+ - Avoid modifying `dist/` directly; rebuild via `npm run build` if Delivery requires it.
15
+ 2. **Coding Guidelines**
16
+ - TypeScript target: `tsconfig.json` defaults (ES2019). Stick to CommonJS module semantics.
17
+ - Preserve existing moment-timezone usage; new dependencies require explicit justification.
18
+ - Keep comments succinct; favour self-explanatory code.
19
+ - Update or add tests whenever behaviour changes. Use fixtures under `tests/` or create new ones mirroring existing structure.
20
+ 3. **Testing**
21
+ - Run `npm test` before concluding major edits.
22
+ - For targeted suites use scripts in `package.json` (e.g., `npm run test2` for `tests2/`).
23
+ 4. **Hourly → 15-Minute Migration**
24
+ - Many helpers assume exactly 24 hourly entries. When touching these areas, ensure compatibility with quarter-hour slots per the spec in `specs/quarter-hour-support.md`.
25
+ - When adding new fields (e.g., `durationMinutes`), remember to update cache serialization and typings.
26
+ 5. **Common Pitfalls**
27
+ - `PriceFetcher.scheduleFetchData` currently requires guarding against `fetchTime` being `undefined`.
28
+ - `PriceApi.priceRatio` should handle missing current slots gracefully (Index of `-1`).
29
+ - Tests under `tests/` rely on deterministic moment inputs; ensure new tests use fixed timestamps.
30
+
31
+ ## Done Checklist
32
+ - [ ] TypeScript compilation succeeds: `npm run build`.
33
+ - [ ] All relevant test suites pass.
34
+ - [ ] README/spec docs updated if API or observable behaviour changes.
35
+ - [ ] No unintended edits in `dist/` or unrelated files.
36
+
37
+ Happy shipping!***
@@ -0,0 +1,60 @@
1
+ # Using @balmli/homey-utility-prices with 15-Minute Nord Pool Slots
2
+
3
+ This guide summarises the practical steps for Homey apps and scripts upgrading to the quarter-hour capable release described in `specs/quarter-hour-support.md`.
4
+
5
+ ## What Changed
6
+ - Every spot price item now carries slot metadata: `startsAt`, `endsAt`, `durationMinutes`, `price`.
7
+ - All core helpers (`NordpoolApi`, `PricesFetchClient`, `PriceApi`, `PriceComparer`, `PriceFetcher`) respect variable slot durations.
8
+ - **Price fetching runs hourly** to get Nord Pool data (since prices are updated hourly).
9
+ - **Price update events fire every 15 minutes** (00:03, 15:03, 30:03, 45:03) to support quarter-hour slots.
10
+
11
+ ## Adopting the New Version
12
+ 1. **Install the update**
13
+ ```bash
14
+ npm install @balmli/homey-utility-prices@latest
15
+ ```
16
+
17
+ 2. **Adjust your price consumers**
18
+ - Treat `NordpoolPrice.time` as the slot start (Unix seconds), but prefer `startsAt`/`endsAt` for comparisons.
19
+ - Persist the full object if you store prices yourself; downstream logic may need `durationMinutes`.
20
+
21
+ 3. **Configure fetch timing (optional)**
22
+ ```ts
23
+ priceFetcher.setFetchTime(30); // seconds past the hour to fetch (default: 3)
24
+ ```
25
+ - Fetching happens **once per hour** at the configured offset (e.g., XX:00:30 if set to 30)
26
+ - Price update events (`priceChanged`) fire **automatically every 15 minutes** at 00:03, 15:03, 30:03, 45:03
27
+ - No need to configure `fetchIntervalMinutes` - it has been removed for simplicity
28
+
29
+ 4. **Handle new comparer behaviour**
30
+ - Helpers like `lowHoursComparer` still accept hours, but internally translate to slot counts. Ensure requested hours are multiples of the slot duration (e.g., `0.5` for 30 minutes is invalid).
31
+ - Guard any custom code against `hoursToSlotCount` throwing when misaligned.
32
+
33
+ 5. **Caching / storage**
34
+ - `PricesFetchClient` now writes and reads the additional fields. No action needed unless you manipulate Homey store values directly; in that case, include `endsAt` and `durationMinutes`.
35
+
36
+ ## Compatibility Notes
37
+ - Legacy hourly data still works; missing `durationMinutes` defaults to 60.
38
+ - `priceFetcherOptions.fetchTime` is "seconds past the hour" (not "seconds into interval").
39
+ - Error handling: requesting time windows not aligned with slot duration throws. Catch and adjust user input accordingly.
40
+
41
+ ## Fetch Schedule Details
42
+
43
+ ### Price Fetching (from Nord Pool API)
44
+ - **Frequency**: Once per hour
45
+ - **Timing**: At `fetchTime` seconds past the hour (default: 3 seconds)
46
+ - **Example**: 10:00:03, 11:00:03, 12:00:03, etc.
47
+ - **Event**: Emits `prices` event with all fetched prices
48
+
49
+ ### Price Updates (priceChanged event)
50
+ - **Frequency**: Four times per hour
51
+ - **Timing**: At 3 seconds after each quarter-hour
52
+ - **Example**: 10:00:03, 10:15:03, 10:30:03, 10:45:03
53
+ - **Event**: Emits `priceChanged` event with current price (Nordpool only)
54
+
55
+ ## Suggested Validation
56
+ - Run `npm test` (or targeted suites) after integrating to confirm automation flows still pass.
57
+ - In production, monitor the `priceChanged` event to ensure it fires four times per hour once Nord Pool migrates.
58
+ - Verify fetch timing by checking logs for "Price Fetcher: fetch time" messages.
59
+
60
+ Questions? Check the detailed design in `specs/quarter-hour-support.md` or the bug fix documentation in `specs/price-fetcher-bugs-and-fixes.md`, or open an issue on the repo.
package/README.md CHANGED
@@ -1,3 +1,86 @@
1
- # Temporary Holding Version
1
+ # @balmli/homey-utility-prices
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Utility helpers for Homey apps that need Nordic electricity spot prices and related analytics. It wraps Nord Pool's Data Portal API, handles caching on Homey devices, and exposes tooling for comparing prices, heating schedules, and aggregations.
4
+
5
+ - Fetch day-ahead spot prices (yesterday/today/tomorrow) and daily averages from Nord Pool.
6
+ - Normalise data into `NordpoolPrice` records with timestamps, slot duration metadata, price levels, and optional financial support adjustments.
7
+ - Cache prices in Homey device store via `PricesFetchClient` and orchestrate fetch/update intervals with `PriceFetcher`.
8
+ - Analyse prices with `PriceApi` / `PriceComparer` helpers (e.g., find lowest hours, compute averages, decide heating strategy).
9
+ - Provide heating schedule calculations with public-holiday awareness.
10
+
11
+ ## Installation
12
+
13
+ ```bash
14
+ npm install @balmli/homey-utility-prices
15
+ ```
16
+
17
+ The package is published as CommonJS with bundled type declarations in `dist/`.
18
+
19
+ ## Usage
20
+
21
+ ### Fetch day-ahead spot prices
22
+
23
+ ```ts
24
+ import moment from 'moment-timezone';
25
+ import {NordpoolApi, Currency} from '@balmli/homey-utility-prices';
26
+
27
+ const api = new NordpoolApi({logger: console});
28
+ const today = moment().tz('Europe/Oslo').startOf('day');
29
+
30
+ const prices = await api.fetchPrices(today, {
31
+ priceArea: 'Bergen',
32
+ currency: Currency.NOK,
33
+ });
34
+
35
+ console.log(prices[0].startsAt.format(), prices[0].price);
36
+ ```
37
+
38
+ ### Cache prices on a Homey device
39
+
40
+ ```ts
41
+ import moment from 'moment-timezone';
42
+ import {PriceFetcher, PricesFetchClient, PriceFetcherMethod} from '@balmli/homey-utility-prices';
43
+
44
+ const priceFetcher = new PriceFetcher({
45
+ logger: console,
46
+ pricesFetchClient: new PricesFetchClient({logger: console}),
47
+ device: homeyDevice,
48
+ });
49
+
50
+ priceFetcher.setNordpoolOptions({priceArea: 'Oslo', currency: 'NOK'});
51
+ priceFetcher.setFetchMethod(PriceFetcherMethod.nordpool);
52
+ priceFetcher.setFetchTime(30); // optional: seconds past the hour to fetch (default: 3)
53
+ priceFetcher.start();
54
+
55
+ // Fetches prices hourly (e.g., at 10:00:30, 11:00:30, etc.)
56
+ priceFetcher.on('prices', prices => {
57
+ console.log(`Received ${prices.length} price periods`);
58
+ });
59
+
60
+ // Emits current price every 15 minutes (00:03, 15:03, 30:03, 45:03)
61
+ priceFetcher.on('priceChanged', currentPrice => {
62
+ console.log(`Current price: ${currentPrice.price}`);
63
+ });
64
+ ```
65
+
66
+ ### Price comparisons
67
+
68
+ `PriceApi` and `PriceComparer` expose helpers to identify lowest/highest periods, compare against averages, and feed Homey automation flows. See the tests in `tests/` for worked examples.
69
+
70
+ ## Development
71
+
72
+ - Build: `npm run build`
73
+ - Test: `npm test`
74
+ - TypeScript sources live in `lib/`; compiled artifacts are written to `dist/`.
75
+
76
+ ## Slot duration handling
77
+
78
+ As of the Nord Pool policy change on **1 October 2025**, the Day Ahead API switches to 15-minute intervals. The library now stores slot metadata (`durationMinutes`, `endsAt`) across fetch, cache, and comparer helpers so Homey apps continue to work seamlessly with both hourly archives and quarter-hour futures.
79
+
80
+ ### Fetch and Update Schedule
81
+
82
+ - **Price fetching**: Runs once per hour at the configured offset (default: 3 seconds past the hour). Example: 10:00:03, 11:00:03, 12:00:03.
83
+ - **Price updates**: The `priceChanged` event fires every 15 minutes at 00:03, 15:03, 30:03, 45:03 to support quarter-hour slots.
84
+ - No configuration needed - the library automatically handles the appropriate intervals.
85
+
86
+ Review `specs/` and `QUARTER_HOUR_USAGE.md` for detailed design notes and migration guidance.
@@ -0,0 +1,5 @@
1
+ import { Moment } from 'moment-timezone';
2
+ import { HeatingOptions, HeatingResult } from "./types";
3
+ export declare const isWorkDay: (aDate: Moment, opts: HeatingOptions) => boolean;
4
+ export declare const isHoliday: (aDate: Moment, opts: HeatingOptions) => boolean;
5
+ export declare const calcHeating: (aDate: Moment, atHome: boolean | undefined, homeOverride: boolean | undefined, opts: HeatingOptions) => HeatingResult;
@@ -0,0 +1,60 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.calcHeating = exports.isHoliday = exports.isWorkDay = void 0;
7
+ var moment_timezone_1 = __importDefault(require("moment-timezone"));
8
+ var homey_public_holidays_1 = require("@balmli/homey-public-holidays");
9
+ var types_1 = require("./types");
10
+ var isDay = function (aDate, opts) {
11
+ var hour = aDate.hour() + aDate.minute() / 60 + aDate.second() / 3600;
12
+ var workdayToday = (0, exports.isWorkDay)(aDate, opts);
13
+ var workdayTomorrow = (0, exports.isWorkDay)((0, moment_timezone_1.default)(aDate).add(1, 'day'), opts);
14
+ var startHour = workdayToday ? opts.workday.startHour : opts.notWorkday.startHour;
15
+ var endHour = workdayToday ? opts.workday.endHour : opts.notWorkday.endHour;
16
+ var endHour1 = startHour <= endHour ? 0 : endHour;
17
+ var endHour2 = workdayTomorrow ? (opts.workday.startHour <= opts.workday.endHour ? opts.workday.endHour : 24) :
18
+ (opts.notWorkday.startHour <= opts.notWorkday.endHour ? opts.notWorkday.endHour : 24);
19
+ return hour < endHour1 || hour >= startHour && hour < endHour2;
20
+ };
21
+ var isWorkDay = function (aDate, opts) {
22
+ return opts.holiday_today === types_1.HolidayToday.not_holiday ||
23
+ !(0, exports.isHoliday)(aDate, opts) && aDate.day() >= 1 && aDate.day() <= 5;
24
+ };
25
+ exports.isWorkDay = isWorkDay;
26
+ var isWorkTime = function (aDate, opts) {
27
+ var hour = aDate.hour() + aDate.minute() / 60 + aDate.second() / 3600;
28
+ return (0, exports.isWorkDay)(aDate, opts) &&
29
+ (opts.workHours.startHour <= opts.workHours.endHour ?
30
+ hour >= opts.workHours.startHour && hour < opts.workHours.endHour :
31
+ hour >= opts.workHours.startHour || hour < opts.workHours.endHour);
32
+ };
33
+ var isHoliday = function (aDate, opts) {
34
+ if (opts.holiday_today === types_1.HolidayToday.holiday || opts.holiday_today === types_1.HolidayToday.not_holiday) {
35
+ return opts.holiday_today === types_1.HolidayToday.holiday;
36
+ }
37
+ var hd = homey_public_holidays_1.holidays.isHoliday(opts.country || 'NO', aDate.toDate());
38
+ if (hd === false) {
39
+ return false;
40
+ }
41
+ var hdd = hd;
42
+ return (hdd.type === 'public' || hdd.type === 'bank');
43
+ };
44
+ exports.isHoliday = isHoliday;
45
+ var calcHeating = function (aDate, atHome, homeOverride, opts) {
46
+ var day = isDay(aDate, opts);
47
+ var night = !day;
48
+ var atWork = isWorkTime(aDate, opts);
49
+ return {
50
+ date: aDate.toISOString(),
51
+ lDate: aDate.format('YYYY-MM-DDTHH:mm:ss'),
52
+ atHome: atHome === true,
53
+ homeOverride: homeOverride === true,
54
+ day: day,
55
+ night: night,
56
+ atWork: atWork,
57
+ heating: (atHome === true) && !night && !atWork || (homeOverride === true) && !night
58
+ };
59
+ };
60
+ exports.calcHeating = calcHeating;
@@ -0,0 +1,35 @@
1
+ import { MomentInput } from 'moment-timezone';
2
+ import { NordpoolOptions, NordpoolPrices } from "./types";
3
+ export declare class NordpoolApi {
4
+ private readonly API_URL;
5
+ logger: any;
6
+ constructor({ logger }: {
7
+ logger: any;
8
+ });
9
+ /**
10
+ * Fetch prices from Nordpool, for yesterday, today and tomorrow.
11
+ *
12
+ * @param aDate
13
+ * @param opts
14
+ */
15
+ fetchPrices: (aDate: MomentInput, opts: NordpoolOptions) => Promise<NordpoolPrices>;
16
+ /**
17
+ * Fetch prices from Nordpool for a single day.
18
+ *
19
+ * @param aDate
20
+ * @param opts
21
+ */
22
+ fetchPricesForDay: (aDate: MomentInput, opts: NordpoolOptions) => Promise<NordpoolPrices | undefined>;
23
+ /**
24
+ * Fetch daily average prices for a month.
25
+ *
26
+ * @param aDate
27
+ * @param opts
28
+ */
29
+ fetchDailyPrices: (aDate: MomentInput, opts: NordpoolOptions) => Promise<NordpoolPrices | undefined>;
30
+ private getSpotPricesForDay;
31
+ private parseSpotResult;
32
+ private getDailyPrices;
33
+ private parseDailyResult;
34
+ private mapPriceArea;
35
+ }
@@ -0,0 +1,254 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __generator = (this && this.__generator) || function (thisArg, body) {
12
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
13
+ return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
+ function verb(n) { return function (v) { return step([n, v]); }; }
15
+ function step(op) {
16
+ if (f) throw new TypeError("Generator is already executing.");
17
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
18
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
+ if (y = 0, t) op = [op[0] & 2, t.value];
20
+ switch (op[0]) {
21
+ case 0: case 1: t = op; break;
22
+ case 4: _.label++; return { value: op[1], done: false };
23
+ case 5: _.label++; y = op[1]; op = [0]; continue;
24
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
+ default:
26
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
+ if (t[2]) _.ops.pop();
31
+ _.trys.pop(); continue;
32
+ }
33
+ op = body.call(thisArg, _);
34
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
+ }
37
+ };
38
+ var __importDefault = (this && this.__importDefault) || function (mod) {
39
+ return (mod && mod.__esModule) ? mod : { "default": mod };
40
+ };
41
+ Object.defineProperty(exports, "__esModule", { value: true });
42
+ exports.NordpoolApi = void 0;
43
+ var moment_timezone_1 = __importDefault(require("moment-timezone"));
44
+ var types_1 = require("./types");
45
+ var http = require('http.min');
46
+ var NordpoolApi = /** @class */ (function () {
47
+ function NordpoolApi(_a) {
48
+ var logger = _a.logger;
49
+ var _this = this;
50
+ this.API_URL = "https://dataportal-api.nordpoolgroup.com/api";
51
+ /**
52
+ * Fetch prices from Nordpool, for yesterday, today and tomorrow.
53
+ *
54
+ * @param aDate
55
+ * @param opts
56
+ */
57
+ this.fetchPrices = function (aDate, opts) { return __awaiter(_this, void 0, void 0, function () {
58
+ var yesterday, today, tomorrow, results, err_1;
59
+ return __generator(this, function (_a) {
60
+ switch (_a.label) {
61
+ case 0:
62
+ _a.trys.push([0, 2, , 3]);
63
+ yesterday = (0, moment_timezone_1.default)(aDate).subtract(1, 'day');
64
+ today = (0, moment_timezone_1.default)(aDate);
65
+ tomorrow = (0, moment_timezone_1.default)(aDate).add(1, 'day');
66
+ return [4 /*yield*/, Promise.all([
67
+ this.getSpotPricesForDay(yesterday, opts),
68
+ this.getSpotPricesForDay(today, opts),
69
+ this.getSpotPricesForDay(tomorrow, opts)
70
+ ])];
71
+ case 1:
72
+ results = _a.sent();
73
+ return [2 /*return*/, results.flat()];
74
+ case 2:
75
+ err_1 = _a.sent();
76
+ this.logger.error('Fetching prices failed: ', err_1);
77
+ return [2 /*return*/, []];
78
+ case 3: return [2 /*return*/];
79
+ }
80
+ });
81
+ }); };
82
+ /**
83
+ * Fetch prices from Nordpool for a single day.
84
+ *
85
+ * @param aDate
86
+ * @param opts
87
+ */
88
+ this.fetchPricesForDay = function (aDate, opts) { return __awaiter(_this, void 0, void 0, function () {
89
+ var err_2;
90
+ return __generator(this, function (_a) {
91
+ switch (_a.label) {
92
+ case 0:
93
+ _a.trys.push([0, 2, , 3]);
94
+ return [4 /*yield*/, this.getSpotPricesForDay((0, moment_timezone_1.default)(aDate), opts)];
95
+ case 1: return [2 /*return*/, _a.sent()];
96
+ case 2:
97
+ err_2 = _a.sent();
98
+ this.logger.error('Fetching prices failed: ', err_2);
99
+ return [3 /*break*/, 3];
100
+ case 3: return [2 /*return*/, undefined];
101
+ }
102
+ });
103
+ }); };
104
+ /**
105
+ * Fetch daily average prices for a month.
106
+ *
107
+ * @param aDate
108
+ * @param opts
109
+ */
110
+ this.fetchDailyPrices = function (aDate, opts) { return __awaiter(_this, void 0, void 0, function () {
111
+ return __generator(this, function (_a) {
112
+ try {
113
+ return [2 /*return*/, this.getDailyPrices((0, moment_timezone_1.default)(aDate), opts)];
114
+ }
115
+ catch (err) {
116
+ this.logger.error('Fetching daily average prices failed: ', err);
117
+ }
118
+ return [2 /*return*/, undefined];
119
+ });
120
+ }); };
121
+ this.getSpotPricesForDay = function (momnt, opts) { return __awaiter(_this, void 0, void 0, function () {
122
+ var url, resp, data, err_3;
123
+ return __generator(this, function (_a) {
124
+ switch (_a.label) {
125
+ case 0:
126
+ _a.trys.push([0, 2, , 3]);
127
+ url = new URL("".concat(this.API_URL, "/DayAheadPrices"));
128
+ url.searchParams.append('currency', opts.currency);
129
+ url.searchParams.append('market', 'DayAhead');
130
+ url.searchParams.append('deliveryArea', this.mapPriceArea(opts.priceArea));
131
+ url.searchParams.append('date', momnt.format('YYYY-MM-DD'));
132
+ return [4 /*yield*/, http.get({
133
+ uri: url.toString(),
134
+ headers: {
135
+ 'accept': 'application/json'
136
+ },
137
+ timeout: 30000
138
+ })];
139
+ case 1:
140
+ resp = _a.sent();
141
+ if (resp.response.statusCode === 204) {
142
+ return [2 /*return*/, []];
143
+ }
144
+ if (resp.response.statusCode !== 200) {
145
+ throw new Error("Invalid response from Nordpool API: ".concat(resp.response.statusCode, ", ").concat(resp.response.statusMessage));
146
+ }
147
+ data = JSON.parse(resp.data);
148
+ return [2 /*return*/, this.parseSpotResult(data, opts)];
149
+ case 2:
150
+ err_3 = _a.sent();
151
+ throw err_3;
152
+ case 3: return [2 /*return*/];
153
+ }
154
+ });
155
+ }); };
156
+ this.getDailyPrices = function (momnt, opts) { return __awaiter(_this, void 0, void 0, function () {
157
+ var startOfMonth, startOfNextMonth, url, resp, data, err_4;
158
+ return __generator(this, function (_a) {
159
+ switch (_a.label) {
160
+ case 0:
161
+ startOfMonth = momnt.startOf('month');
162
+ startOfNextMonth = (0, moment_timezone_1.default)(startOfMonth).add(1, 'month');
163
+ _a.label = 1;
164
+ case 1:
165
+ _a.trys.push([1, 3, , 4]);
166
+ url = new URL("".concat(this.API_URL, "/AggregatePrices"));
167
+ url.searchParams.append('currency', opts.currency);
168
+ url.searchParams.append('market', 'DayAhead');
169
+ url.searchParams.append('deliveryArea', this.mapPriceArea(opts.priceArea));
170
+ url.searchParams.append('year', startOfMonth.format('YYYY'));
171
+ return [4 /*yield*/, http.get({
172
+ uri: url.toString(),
173
+ headers: {
174
+ 'accept': 'application/json'
175
+ },
176
+ timeout: 30000
177
+ })];
178
+ case 2:
179
+ resp = _a.sent();
180
+ if (resp.response.statusCode === 204) {
181
+ return [2 /*return*/, []];
182
+ }
183
+ if (resp.response.statusCode !== 200) {
184
+ throw new Error("Invalid response from Nordpool API: ".concat(resp.response.statusCode, ", ").concat(resp.response.statusMessage));
185
+ }
186
+ data = JSON.parse(resp.data);
187
+ return [2 /*return*/, this.parseDailyResult(data, opts, startOfMonth, startOfNextMonth)];
188
+ case 3:
189
+ err_4 = _a.sent();
190
+ throw err_4;
191
+ case 4: return [2 /*return*/];
192
+ }
193
+ });
194
+ }); };
195
+ this.mapPriceArea = function (area) {
196
+ if (types_1.PRICE_AREA_MAP[area]) {
197
+ return types_1.PRICE_AREA_MAP[area];
198
+ }
199
+ return area;
200
+ };
201
+ this.logger = logger;
202
+ }
203
+ NordpoolApi.prototype.parseSpotResult = function (data, opts) {
204
+ var _a, _b;
205
+ if (data.currency !== opts.currency) {
206
+ throw new Error('Currency mismatch');
207
+ }
208
+ var result = [];
209
+ var areaId = this.mapPriceArea(opts.priceArea);
210
+ for (var _i = 0, _c = data.multiAreaEntries; _i < _c.length; _i++) {
211
+ var entry = _c[_i];
212
+ var startsAt = (0, moment_timezone_1.default)(entry.deliveryStart);
213
+ var deliveryEnd = entry.deliveryEnd ? (0, moment_timezone_1.default)(entry.deliveryEnd) : (0, moment_timezone_1.default)(startsAt).add(1, 'hour');
214
+ var durationMinutes = Math.max(deliveryEnd.diff(startsAt, 'minutes'), 1);
215
+ var perArea = entry.entryPerArea || {};
216
+ var rawPrice = perArea[areaId];
217
+ if (rawPrice === undefined) {
218
+ (_b = (_a = this.logger) === null || _a === void 0 ? void 0 : _a.warn) === null || _b === void 0 ? void 0 : _b.call(_a, "NordpoolApi: missing price for area ".concat(areaId, " at ").concat(startsAt.toISOString()));
219
+ continue;
220
+ }
221
+ var price = rawPrice / 1000;
222
+ result.push({
223
+ startsAt: startsAt,
224
+ endsAt: deliveryEnd,
225
+ time: startsAt.unix(),
226
+ durationMinutes: durationMinutes,
227
+ price: price
228
+ });
229
+ }
230
+ return result;
231
+ };
232
+ NordpoolApi.prototype.parseDailyResult = function (data, opts, startOfMonth, startOfNextMonth) {
233
+ var result = [];
234
+ for (var _i = 0, _a = data.multiAreaDailyAggregates; _i < _a.length; _i++) {
235
+ var entry = _a[_i];
236
+ var startsAt = (0, moment_timezone_1.default)(entry.deliveryStart);
237
+ if (startsAt.isSameOrAfter(startOfMonth) && startsAt.isBefore(startOfNextMonth)) {
238
+ var deliveryEnd = entry.deliveryEnd ? (0, moment_timezone_1.default)(entry.deliveryEnd) : (0, moment_timezone_1.default)(startsAt).add(1, 'day');
239
+ var durationMinutes = Math.max(deliveryEnd.diff(startsAt, 'minutes'), 1);
240
+ var price = entry.averagePerArea[this.mapPriceArea(opts.priceArea)] / 1000;
241
+ result.push({
242
+ startsAt: startsAt,
243
+ endsAt: deliveryEnd,
244
+ time: startsAt.unix(),
245
+ durationMinutes: durationMinutes,
246
+ price: price
247
+ });
248
+ }
249
+ }
250
+ return result;
251
+ };
252
+ return NordpoolApi;
253
+ }());
254
+ exports.NordpoolApi = NordpoolApi;
@@ -0,0 +1,61 @@
1
+ import moment, { MomentInput } from 'moment-timezone';
2
+ import { NordpoolPrice, NordpoolPrices } from "./types";
3
+ export declare class PriceApi {
4
+ private getSlotMinutes;
5
+ private hoursToSlotCount;
6
+ private alignToSlotStart;
7
+ private resolveEndsAt;
8
+ private isInSlot;
9
+ toHour: (aDate: MomentInput) => string;
10
+ currentPrice: (prices: NordpoolPrices, aDate: MomentInput) => NordpoolPrice | undefined;
11
+ pricesStarting: (prices: NordpoolPrices, aDate: MomentInput, startHour: number, num_hours: number) => NordpoolPrice[];
12
+ pricesSorted: (prices: NordpoolPrices, aDate: MomentInput) => NordpoolPrice[];
13
+ priceRatio: (prices: NordpoolPrices, aDate: MomentInput) => number;
14
+ priceLevels: {
15
+ code: string;
16
+ eval: string;
17
+ description: string;
18
+ }[];
19
+ priceLevel: (prices: NordpoolPrices, aDate: MomentInput) => {
20
+ code: string;
21
+ eval: string;
22
+ description: string;
23
+ } | undefined;
24
+ priceHighLow: (prices: NordpoolPrices, aDate: MomentInput) => {
25
+ high: NordpoolPrice | undefined;
26
+ low: NordpoolPrice | undefined;
27
+ diffPercentage: number;
28
+ diffAmount: number;
29
+ };
30
+ priceNextHours: (prices: NordpoolPrices, aDate: MomentInput, num_hours: number) => NordpoolPrice[];
31
+ averagePricesStarting: (prices: NordpoolPrices, aDate: MomentInput, startHour: number, num_hours: number) => number;
32
+ checkAveragePrice: (price: number, averagePrice: number, below: boolean, percentage: number) => boolean;
33
+ checkLowPrice: (prices: NordpoolPrices, low_hours: number, aDate: MomentInput) => NordpoolPrice[];
34
+ checkHighPrice: (prices: NordpoolPrices, high_hours: number, aDate: MomentInput) => NordpoolPrice[];
35
+ checkHighPrice2: (prices: NordpoolPrices, high_hours: number, aDate: MomentInput, state: any, filter?: boolean) => {
36
+ heating: import("./types").HeatingResult;
37
+ startsAt: moment.Moment;
38
+ endsAt: moment.Moment;
39
+ time: number;
40
+ durationMinutes: number;
41
+ price: number;
42
+ }[];
43
+ minOfHighestPrices: (prices: NordpoolPrices, num_hours: number) => NordpoolPrice | undefined;
44
+ maxOfLowestPrices: (prices: NordpoolPrices, num_hours: number) => NordpoolPrice | undefined;
45
+ pricesAmongLowest: (prices: NordpoolPrices, aDate: MomentInput, startHour: number, numHours: number, numLowestHours: number) => boolean;
46
+ pricesAmongHighest: (prices: NordpoolPrices, aDate: MomentInput, startHour: number, numHours: number, numHighestHours: number) => boolean;
47
+ daysPeriod: (aDate: MomentInput, start: number | string, end: number | string) => {
48
+ startTs: moment.Moment;
49
+ endTs: moment.Moment;
50
+ };
51
+ pricesLowestInPeriod: (prices: NordpoolPrices, aDate: MomentInput, startingAt: MomentInput, endingAt: MomentInput, numLowestHours: number) => boolean;
52
+ inPeriod: (aDate: MomentInput, startingAt: MomentInput, endingAt: MomentInput) => boolean;
53
+ pricesHighestInPeriod: (prices: NordpoolPrices, aDate: MomentInput, startingAt: MomentInput, endingAt: MomentInput, numHighestHours: number) => boolean;
54
+ checkSumPrices: (prices: NordpoolPrices, aDate: MomentInput, startingAt: MomentInput, endingAt: MomentInput, hours: number, low?: boolean) => false | {
55
+ startsAt: moment.Moment;
56
+ endsAt: moment.Moment;
57
+ price: number;
58
+ } | undefined;
59
+ currentPriceLowerThanNext: (prices: NordpoolPrices, aDate: MomentInput, numHours: number) => boolean;
60
+ currentPriceHigherThanNext: (prices: NordpoolPrices, aDate: MomentInput, numHours: number) => boolean;
61
+ }