Skip to content

Commit 059a209

Browse files
committed
Prefixed logging
1 parent 671d86a commit 059a209

12 files changed

Lines changed: 134 additions & 46 deletions

‎dist/Predbat-Table-Card-Next.js‎

Lines changed: 74 additions & 21 deletions
Large diffs are not rendered by default.

‎eslint.config.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,8 @@ export default defineConfig([
7575
"@stylistic/indent": ["error", 2],
7676
"@stylistic/object-curly-spacing": ["error", "always"],
7777
"@stylistic/comma-dangle": ["error", "never"],
78-
"@stylistic/space-before-blocks": ["error", "always"]
78+
"@stylistic/space-before-blocks": ["error", "always"],
79+
"no-console": "error"
7980
},
8081
},
8182
{

‎src/PredbatData.ts‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { ColumnKey } from './schemas/home-assistant';
33
import { PredbatRowData, RawData } from './schemas/predbat';
44
import { change } from './utils/entity-utils';
55
import { getColourFromScale } from './utils/general-utils';
6+
import { logger } from './utils/logger';
67

78
export class PredbatData {
89
private _plan: Map<string, PredbatRowData | null> | null = null;
@@ -77,7 +78,7 @@ export class PredbatData {
7778
keyToUse = roundedTemporal.toString();
7879

7980
if (newPlan.has(keyToUse)) {
80-
console.warn(`Skipping off-half-hour entry ${timeString} (collides with ${keyToUse})`);
81+
logger.warn(`Skipping off-half-hour entry ${timeString} (collides with ${keyToUse})`);
8182

8283
continue;
8384
}
@@ -96,13 +97,13 @@ export class PredbatData {
9697
while (Temporal.PlainDateTime.compare(fillTime, currentModifiedTime) < 0) {
9798
const fillKey = fillTime.toString();
9899

99-
console.warn(`Gap detected: ${diffMinutes} minutes between ${lastKey} and ${keyToUse} - Filling missing slot: ${fillKey} with null`);
100+
logger.warn(`Gap detected: ${diffMinutes} minutes between ${lastKey} and ${keyToUse} - Filling missing slot: ${fillKey} with null`);
100101
newPlan.set(fillKey, null);
101102
fillTime = fillTime.add({ minutes: 30 });
102103
}
103104
}
104105
else if (diffMinutes !== 30) {
105-
console.warn(`Skipping ${keyToUse}: not 30 minutes after ${lastKey} (${diffMinutes} minutes)`);
106+
logger.warn(`Skipping ${keyToUse}: not 30 minutes after ${lastKey} (${diffMinutes} minutes)`);
106107

107108
continue;
108109
}

‎src/predbat-card.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -241,7 +241,7 @@ class PredbatTableCard extends HTMLElement {
241241
this._weatherService.getWeatherData(this._configManager.dayLimit)
242242
);
243243
}
244-
244+
// TODO - change cost column to pounds
245245
private _getOverrideStateString(): string {
246246
const overrideEntities = this._haService.getOverrideEntities();
247247

‎src/schemas/home-assistant.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { z } from 'zod';
22
import { allColumns, htmlPlanEntity } from '../constants';
3+
import { logger } from '../utils/logger';
34

45
const HistoryStateSchema = z.object({
56
state: z.string(),
@@ -27,7 +28,7 @@ export const PredbatTableCardConfigSchema = z.object({
2728
columns.filter((column): column is ColumnKey => {
2829
if (validColumns.has(column)) return true;
2930

30-
console.warn(`Unknown column "${column}" — ignoring. Valid values: ${allColumns.join(', ')}`);
31+
logger.warn(`Unknown column "${column}" — ignoring. Valid values: ${allColumns.join(', ')}`);
3132

3233
return false;
3334
})

‎src/schemas/predbat.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import z from 'zod';
22
import { Temporal } from '@js-temporal/polyfill';
33
import { fixTimezoneOffset, dateStringHasTimezoneOffset as stringHasTimezoneOffset } from '../utils/general-utils';
44
import { dayStart } from '../constants';
5+
import { logger } from '../utils/logger';
56

67
const UTCDateSchema = z.preprocess(
78
(val) => {
@@ -62,7 +63,7 @@ const resultsToTemporalMap = (results: Record<string, number>): Map<Temporal.Pla
6263
}
6364
}
6465
catch (error) {
65-
console.error(error);
66+
logger.error(error);
6667
}
6768
}
6869

‎src/services/predbat-service.ts‎

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { PredbatData } from '../PredbatData';
22
import { RawData, PredbatRawDataSchema } from '../schemas/predbat';
3+
import { logger } from '../utils/logger';
34

45
export class PredbatRestApiService {
56
private _dataCallback: ((predbatData: PredbatData) => void) | null;
@@ -39,7 +40,7 @@ export class PredbatRestApiService {
3940
this._getPlanData(this._port)
4041
.then((planData) => {
4142
if (planData?.yesterday === undefined) {
42-
console.warn('No data received from Predbat API');
43+
logger.warn('No data received from Predbat API');
4344

4445
return;
4546
}
@@ -53,25 +54,25 @@ export class PredbatRestApiService {
5354
this._dataCallback(new PredbatData(validatedHistoricPlanData, validatedPlanData));
5455
}
5556
catch (error) {
56-
console.error(error);
57+
logger.error(error);
5758
}
5859

5960
if (!this._isAvailable) {
60-
console.info('Successfully fetched Predbat API data');
61+
logger.info('Successfully fetched Predbat API data');
6162

6263
this._isAvailable = true;
6364
this._scheduleHalfHourUpdate(5);
6465
}
6566
})
6667
.catch((error) => {
6768
if (this._isAvailable) {
68-
console.warn('Predbat API request failed, will retry...', error.message);
69+
logger.warn('Predbat API request failed, will retry...', error.message);
6970

7071
this._isAvailable = false;
7172
this._startPolling();
7273
}
7374
else {
74-
console.error('Predbat is unreachable');
75+
logger.error('Predbat is unreachable');
7576
}
7677
})
7778
.finally(() => {
@@ -115,19 +116,19 @@ export class PredbatRestApiService {
115116
return fetch(`http://${window.location.hostname}:${port}/api/plan_data`)
116117
.then(async (response) => {
117118
if (!response.ok) {
118-
console.info('Using HASS state for Predbat data (response error)');
119+
logger.info('Using HASS state for Predbat data (response error)');
119120

120121
return false;
121122
}
122123

123124
await response.json();
124125

125-
console.info('Using REST API for Predbat data');
126+
logger.info('Using REST API for Predbat data');
126127

127128
return true;
128129
})
129130
.catch(() => {
130-
console.info('Using HASS state for Predbat data (fetch error)');
131+
logger.info('Using HASS state for Predbat data (fetch error)');
131132

132133
return false;
133134
});

‎src/services/weather-service.ts‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { ForecastSubscriptionError } from '../utils/ForecastSubscriptionError';
44
import { maxWeatherSubscriptionRetries, weekdayMap, white } from '../constants';
55
import { getColourFromScale, invalidDay } from '../utils/general-utils';
66
import { WeatherAttributesSchema, WeatherForecastArray, WeatherForecastArraySchema, WeatherForecastItem } from '../schemas/weather';
7+
import { logger } from '../utils/logger';
78

89
export type WeatherRowData = {
910
'weather-column': { value: string, colour: string } | null;
@@ -56,7 +57,7 @@ export class WeatherService {
5657

5758
public async subscribe(weatherEntityId: string | undefined): Promise<void> {
5859
if (weatherEntityId === undefined) {
59-
console.info('No weather forecast entity configured');
60+
logger.info('No weather forecast entity configured');
6061
}
6162
else {
6263
// Prevent multiple subscription attempts
@@ -74,7 +75,7 @@ export class WeatherService {
7475
throw new Error('throw new Error(`Failed to subscribe to forecast - connection not available after ${maxWeatherSubscriptionRetries} attempts`);');
7576
}
7677

77-
console.info(`Waiting for hass connection... attempt ${attempts}/${maxWeatherSubscriptionRetries} (waiting ${delayMs}ms)`);
78+
logger.info(`Waiting for hass connection... attempt ${attempts}/${maxWeatherSubscriptionRetries} (waiting ${delayMs}ms)`);
7879

7980
await new Promise(resolve => setTimeout(resolve, delayMs));
8081
}
@@ -96,13 +97,13 @@ export class WeatherService {
9697
}
9798
);
9899

99-
console.info('Weather forecast subscription successful');
100+
logger.info('Weather forecast subscription successful');
100101
}
101102
catch (error) {
102103
const forecastSubscriptionError = error as ForecastSubscriptionError;
103104

104105
if (forecastSubscriptionError.code !== 'invalid_format') {
105-
console.error('Failed to subscribe to forecast:', forecastSubscriptionError);
106+
logger.error('Failed to subscribe to forecast:', forecastSubscriptionError);
106107
}
107108

108109
throw new Error('Failed to subscribe to forecast - Correct the entity value and refresh');

‎src/utils/config-manager.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { ColumnKey, PredbatTableCardConfigSchema } from '../schemas/home-assistant';
22
import { PredbatTableCardConfig } from '../types/home-assistant';
3+
import { logger } from './logger';
34

45
export class ConfigManager {
56
private _config: PredbatTableCardConfig | null;
@@ -14,8 +15,8 @@ export class ConfigManager {
1415

1516
this._config = validatedConfig;
1617
}
17-
catch(error) {
18-
console.error(error);
18+
catch (error) {
19+
logger.error(error);
1920
}
2021
}
2122

‎src/utils/general-utils.ts‎

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import isSemver from 'is-semver';
22
import { weekdayArray, weekdayMap } from '../constants';
33
import type { CellValue, WeekdayKey } from '../types/home-assistant';
4+
import { logger } from './logger';
45

56
export function invalidDay(labelDayStr: string): boolean {
67
if (!weekdayArray.includes(labelDayStr)) return true;
@@ -71,7 +72,7 @@ export function cleanAndValidateVersion(version: string | undefined): string | n
7172
const cleaned = trimmed.startsWith('v') ? trimmed.slice(1) : trimmed;
7273

7374
if (!isSemver(cleaned)) {
74-
console.warn(`Invalid version format: ${version}`);
75+
logger.warn(`Invalid version format: ${version}`);
7576

7677
return null;
7778
}
@@ -231,8 +232,6 @@ export function isWithinLastHalfHour(dateString: string): void {
231232
const dateToCheck = Temporal.PlainDateTime.from(dateString);
232233

233234
if (Temporal.PlainDateTime.compare(dateToCheck, thirtyMinutesAgo) < 0) {
234-
console.error(
235-
`Predbat has not returned full history data. Expected data from ${thirtyMinutesAgo.toString()}, but latest received is ${dateToCheck.toString()}`
236-
);
235+
logger.error(`Predbat has not returned full history data. Expected data from ${thirtyMinutesAgo.toString()}, but latest received is ${dateToCheck.toString()}`);
237236
}
238237
}

0 commit comments

Comments
 (0)