homebridge-bomgovau-v2 0.2.2 → 0.2.5

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.
package/index.js CHANGED
@@ -9,10 +9,8 @@
9
9
 
10
10
  "use strict";
11
11
 
12
- const { Service, Characteristic } = require("hap-nodejs");
13
12
  const pjson = require("./package.json");
14
- const dns = require("node:dns").promises;
15
- const { BlockList } = require("node:net");
13
+ const BomClient = require("./lib/bom-client");
16
14
 
17
15
  /** @const {string} Plugin name from package.json */
18
16
  const PLUGIN_NAME = pjson.name;
@@ -21,27 +19,8 @@ const PLUGIN_VERSION = pjson.version;
21
19
  const DEFAULT_UPDATE_FREQUENCY = 30 * 60 * 1000;
22
20
  const MIN_UPDATE_FREQUENCY = 60 * 1000;
23
21
  const MAX_UPDATE_FREQUENCY = 24 * 60 * 60 * 1000;
24
- const FETCH_TIMEOUT_MS = 10 * 1000;
25
- const MAX_RESPONSE_BYTES = 1024 * 1024;
26
- const MAX_REDIRECTS = 3;
27
- const nonPublicAddresses = new BlockList();
28
- [
29
- ["0.0.0.0", 8, "ipv4"],
30
- ["10.0.0.0", 8, "ipv4"],
31
- ["100.64.0.0", 10, "ipv4"],
32
- ["127.0.0.0", 8, "ipv4"],
33
- ["169.254.0.0", 16, "ipv4"],
34
- ["172.16.0.0", 12, "ipv4"],
35
- ["192.168.0.0", 16, "ipv4"],
36
- ["224.0.0.0", 4, "ipv4"],
37
- ["::", 128, "ipv6"],
38
- ["::1", 128, "ipv6"],
39
- ["fc00::", 7, "ipv6"],
40
- ["fe80::", 10, "ipv6"],
41
- ["ff00::", 8, "ipv6"]
42
- ].forEach(([address, prefix, family]) => {
43
- nonPublicAddresses.addSubnet(address, prefix, family);
44
- });
22
+ const EVE_AIR_PRESSURE_SERVICE_UUID = "E863F00A-079E-48FF-8F27-9C2605A29F52";
23
+ const EVE_AIR_PRESSURE_CHAR_UUID = "E863F10F-079E-48FF-8F27-9C2605A29F52";
45
24
 
46
25
  /**
47
26
  * BOMgovauAccessory - Homebridge accessory for BOM weather station data
@@ -56,9 +35,9 @@ class BOMgovauAccessory {
56
35
  /**
57
36
  * Creates an instance of BOMgovauAccessory.
58
37
  *
59
- * @param {HomebridgeAPI} api - Homebridge API instance
60
38
  * @param {HomebridgeLogger} logger - Homebridge logger instance
61
39
  * @param {Object} config - Accessory configuration
40
+ * @param {HomebridgeAPI} api - Homebridge API instance
62
41
  * @param {string} [config.name="BOM Weather Station"] - Display name for the accessory
63
42
  * @param {string} [config.stationURL] - BOM JSON observation URL (defaults to Canberra Airport)
64
43
  * @param {number} [config.updateFrequency=1800000] - Update interval in milliseconds (default 30 min)
@@ -66,22 +45,51 @@ class BOMgovauAccessory {
66
45
  * @param {boolean} [config.sensors.temperature=true] - Enable temperature sensor
67
46
  * @param {boolean} [config.sensors.humidity=true] - Enable humidity sensor
68
47
  * @param {boolean} [config.sensors.apparentTemp=true] - Enable apparent temperature sensor
48
+ * @param {boolean} [config.sensors.pressure=true] - Enable air pressure sensor
69
49
  */
70
- constructor(api, logger, config) {
50
+ constructor(logger, config, api) {
51
+ const { Characteristic, Service, Formats, Perms } = api.hap;
52
+ this.hap = api.hap;
53
+
71
54
  /** @type {HomebridgeLogger} */
72
55
  this.log = logger;
73
56
  /** @type {string} */
74
57
  this.name = config.name || "BOM Weather Station";
75
58
 
76
- // Load community types and FakeGato - instance local, not global
77
- /** @type {Object} */
78
- this.CommunityTypes = require("hap-nodejs-community-types")(api);
59
+ class AirPressureCharacteristic extends Characteristic {
60
+ constructor() {
61
+ super("Air Pressure", EVE_AIR_PRESSURE_CHAR_UUID, {
62
+ format: Formats.UINT16,
63
+ unit: "hPa",
64
+ minValue: 700,
65
+ maxValue: 1100,
66
+ minStep: 1,
67
+ perms: [Perms.PAIRED_READ, Perms.NOTIFY]
68
+ });
69
+ this.value = this.getDefaultValue();
70
+ }
71
+ }
72
+
73
+ class AirPressureService extends Service {
74
+ constructor(displayName, subtype) {
75
+ super(displayName, EVE_AIR_PRESSURE_SERVICE_UUID, subtype);
76
+ this.addCharacteristic(AirPressureCharacteristic);
77
+ this.addOptionalCharacteristic(Characteristic.Name);
78
+ this.addCharacteristic(Characteristic.StatusFault);
79
+ this.addCharacteristic(Characteristic.StatusActive);
80
+ }
81
+ }
82
+
83
+ /** @type {Function} */
84
+ this.AirPressureCharacteristic = AirPressureCharacteristic;
85
+ /** @type {typeof Service} */
86
+ this.AirPressureService = AirPressureService;
87
+ /** @type {Service|null} */
88
+ this.airPressureService = null;
79
89
  /** @type {Function} */
80
90
  this.FakeGatoHistoryService = require("fakegato-history")(api);
81
91
 
82
92
  // Station configuration
83
- /** @type {string} */
84
- this.stationURL = config.stationURL || "http://reg.bom.gov.au/fwo/IDN60903/IDN60903.94926.json";
85
93
  /** @type {number} */
86
94
  this.updateFrequency = Number.isSafeInteger(config.updateFrequency) &&
87
95
  config.updateFrequency >= MIN_UPDATE_FREQUENCY &&
@@ -95,18 +103,22 @@ class BOMgovauAccessory {
95
103
  ". Using " + this.updateFrequency + " ms.");
96
104
  }
97
105
 
98
- // Validate stationURL
99
- if (!this._isValidUrl(this.stationURL)) {
100
- this.log.error("[BOM gov au] Invalid stationURL: " + this.stationURL + ". Using default.");
101
- this.stationURL = "http://reg.bom.gov.au/fwo/IDN60903/IDN60903.94926.json";
102
- }
106
+ this.bomClient = new BomClient({
107
+ stationURL: config.stationURL,
108
+ name: this.name,
109
+ updateFrequency: this.updateFrequency,
110
+ log: this.log
111
+ });
112
+ /** @type {string} */
113
+ this.stationURL = this.bomClient.stationURL;
103
114
 
104
115
  // Sensor configuration
105
116
  /** @type {Object.<string, boolean>} */
106
117
  this.sensors = {
107
118
  temperature: true,
108
119
  humidity: true,
109
- apparentTemp: true
120
+ apparentTemp: true,
121
+ pressure: true
110
122
  };
111
123
 
112
124
  if (config.sensors) {
@@ -128,17 +140,17 @@ class BOMgovauAccessory {
128
140
  // Current observations
129
141
  /** @type {Object} */
130
142
  this.obs = {
131
- air_temp: 0,
132
- press: 0,
133
- rel_hum: 0,
134
- apparent_t: 0
143
+ air_temp: undefined,
144
+ press: undefined,
145
+ rel_hum: undefined,
146
+ apparent_t: undefined
135
147
  };
136
148
  /** @type {number} */
137
149
  this.BOMdataExpires = 0;
138
150
  /** @type {Object|null} */
139
151
  this.history = null;
140
- /** @type {boolean} */
141
- this._updateLock = false; // Mutex for race condition prevention
152
+ /** @type {Promise<void>|null} */
153
+ this._updatePromise = null;
142
154
 
143
155
  // Setup services
144
156
  this.setupServices();
@@ -152,120 +164,32 @@ class BOMgovauAccessory {
152
164
  }
153
165
 
154
166
  /**
155
- * Validates a URL string.
156
- *
157
- * @param {string} string - URL to validate
158
- * @returns {boolean} True if valid URL
159
- * @private
160
- */
161
- _isValidUrl(string) {
162
- try {
163
- const url = new URL(string);
164
- if (url.protocol !== "http:" && url.protocol !== "https:") {
165
- return false;
166
- }
167
- if (url.username || url.password) {
168
- return false;
169
- }
170
- const hostname = url.hostname.toLowerCase();
171
- return hostname === "bom.gov.au" || hostname.endsWith(".bom.gov.au");
172
- } catch {
173
- return false;
174
- }
175
- }
176
-
177
- /**
178
- * Resolves a station host and prevents DNS resolution to private networks.
167
+ * Returns a finite observation value within the sensor's supported range.
179
168
  *
180
- * @param {string} stationURL - BOM station URL
181
- * @returns {Promise<void>}
169
+ * @param {string} field - BOM observation field
170
+ * @param {number} min - Inclusive minimum
171
+ * @param {number} max - Inclusive maximum
172
+ * @returns {number|undefined}
182
173
  * @private
183
174
  */
184
- async _validateStationHost(stationURL) {
185
- const url = new URL(stationURL);
186
- const addresses = await dns.lookup(url.hostname, { all: true, verbatim: true });
187
- if (!addresses.length || addresses.some(({ address, family }) =>
188
- nonPublicAddresses.check(address, family === 6 ? "ipv6" : "ipv4"))) {
189
- throw new Error("Station host resolves to a non-public IP address");
190
- }
191
- }
192
-
193
- /**
194
- * Fetches the station URL while rejecting redirects outside BOM and limiting response size.
195
- *
196
- * @returns {Promise<Object>}
197
- * @private
198
- */
199
- async _fetchStationJson() {
200
- let currentURL = this.stationURL;
201
-
202
- for (let redirectCount = 0; redirectCount <= MAX_REDIRECTS; redirectCount++) {
203
- if (!this._isValidUrl(currentURL)) {
204
- throw new Error("Station URL is not an approved BOM host");
205
- }
206
- await this._validateStationHost(currentURL);
207
-
208
- const controller = new AbortController();
209
- const timeout = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
210
-
211
- try {
212
- const response = await fetch(currentURL, {
213
- headers: { "User-Agent": PLUGIN_NAME + "/" + PLUGIN_VERSION + " (" + this.name + ")" },
214
- redirect: "manual",
215
- signal: controller.signal
216
- });
217
-
218
- if (response.status >= 300 && response.status < 400) {
219
- const location = response.headers.get("location");
220
- if (!location) {
221
- throw new Error("Redirect response missing Location header");
222
- }
223
- currentURL = new URL(location, currentURL).toString();
224
- continue;
225
- }
226
-
227
- if (!response.ok) {
228
- throw new Error("HTTP error " + response.status);
229
- }
230
-
231
- const contentLength = Number(response.headers.get("content-length"));
232
- if (Number.isFinite(contentLength) && contentLength > MAX_RESPONSE_BYTES) {
233
- throw new Error("BOM response exceeds maximum allowed size");
234
- }
235
-
236
- if (!response.body) {
237
- throw new Error("BOM response has no body");
238
- }
239
-
240
- let receivedBytes = 0;
241
- const chunks = [];
242
- for await (const chunk of response.body) {
243
- receivedBytes += chunk.length;
244
- if (receivedBytes > MAX_RESPONSE_BYTES) {
245
- throw new Error("BOM response exceeds maximum allowed size");
246
- }
247
- chunks.push(Buffer.from(chunk));
248
- }
249
-
250
- return JSON.parse(Buffer.concat(chunks).toString("utf8"));
251
- } finally {
252
- clearTimeout(timeout);
253
- }
254
- }
255
-
256
- throw new Error("Too many redirects");
175
+ _getObservationValue(field, min, max) {
176
+ const value = this.obs[field];
177
+ return typeof value === "number" && Number.isFinite(value) && value >= min && value <= max
178
+ ? value
179
+ : undefined;
257
180
  }
258
181
 
259
182
  /**
260
183
  * Sets up HomeKit services based on enabled sensors.
261
184
  *
262
- * Creates TemperatureSensor, HumiditySensor services and adds
263
- * pressure characteristic to temperature service.
185
+ * Creates TemperatureSensor and HumiditySensor services.
264
186
  * Initializes FakeGato history on first enabled sensor.
265
187
  *
266
188
  * @private
267
189
  */
268
190
  setupServices() {
191
+ const { Service, Characteristic } = this.hap;
192
+
269
193
  // Temperature Service
270
194
  if (this.sensors.temperature) {
271
195
  /** @type {Service} */
@@ -274,18 +198,11 @@ class BOMgovauAccessory {
274
198
  .setProps({ minValue: -100, maxValue: 100 })
275
199
  .onGet(this.getStateTemperature.bind(this));
276
200
 
277
- // Add pressure characteristic (non-standard, added to temperature service)
278
- this.temperatureService.addCharacteristic(this.CommunityTypes.AtmosphericPressureLevel)
279
- .setProps({ format: Characteristic.Formats.UINT16, minValue: 800, maxValue: 1200 })
280
- .onGet(this.getStatePressure.bind(this));
281
-
282
201
  // Service status
283
202
  this.temperatureService.addCharacteristic(Characteristic.StatusFault);
284
203
  this.temperatureService.addCharacteristic(Characteristic.StatusActive);
285
204
  this.temperatureService.setCharacteristic(Characteristic.StatusActive, false);
286
205
 
287
- // Initialize FakeGato history (will be created on first enabled sensor)
288
- this._initHistory();
289
206
  }
290
207
 
291
208
  // Apparent Temperature Service
@@ -301,8 +218,6 @@ class BOMgovauAccessory {
301
218
  this.apparentTempService.addCharacteristic(Characteristic.StatusActive);
302
219
  this.apparentTempService.setCharacteristic(Characteristic.StatusActive, false);
303
220
 
304
- // Initialize FakeGato history if not already created
305
- this._initHistory();
306
221
  }
307
222
 
308
223
  // Humidity Service
@@ -317,39 +232,55 @@ class BOMgovauAccessory {
317
232
  this.humidityService.setCharacteristic(Characteristic.StatusActive, false);
318
233
  this.humidityService.setCharacteristic(Characteristic.SerialNumber, "Station:" + this.name);
319
234
 
320
- // Initialize FakeGato history if not already created
321
- this._initHistory();
322
235
  }
236
+
237
+ if (this.sensors.pressure) {
238
+ this.airPressureService = new this.AirPressureService(this.name + " Air Pressure", "airPressure");
239
+ this.airPressureService.getCharacteristic(this.AirPressureCharacteristic)
240
+ .onGet(this.getStatePressure.bind(this));
241
+ this.airPressureService.setCharacteristic(Characteristic.StatusFault, true);
242
+ this.airPressureService.setCharacteristic(Characteristic.StatusActive, false);
243
+ }
244
+
245
+ this._initHistory();
323
246
  }
324
247
 
325
248
  /**
326
- * Initializes FakeGato history on the first enabled sensor.
327
- *
328
- * Creates history on temperature service if available, otherwise humidity.
329
- * Only creates once per accessory instance.
249
+ * Initializes FakeGato weather history using the enabled sensor services.
250
+ *
251
+ * Weather history entries contain temperature, humidity, and pressure.
252
+ * Missing readings are recorded as zero to preserve the expected entry format.
330
253
  *
331
254
  * @private
332
255
  */
333
256
  _initHistory() {
334
- // Create FakeGato history on the first enabled sensor that supports it
335
- if (!this.history && (this.sensors.temperature || this.sensors.humidity)) {
336
- /** @type {Service|null} */
337
- const primaryService = this.temperatureService || this.humidityService;
338
- if (primaryService) {
339
- primaryService.setCharacteristic(Characteristic.SerialNumber, "Station:" + this.name);
340
- this.history = new this.FakeGatoHistoryService("weather", primaryService, { storage: "fs" });
341
- this.log("[BOM gov au] Initialized FakeGato history on " + primaryService.displayName);
342
- }
257
+ const sensorServices = [
258
+ this.temperatureService,
259
+ this.humidityService,
260
+ this.airPressureService
261
+ ].filter(Boolean);
262
+
263
+ if (!this.history && sensorServices.length) {
264
+ const historyAccessory = {
265
+ displayName: this.name,
266
+ log: this.log,
267
+ services: sensorServices
268
+ };
269
+ this.history = new this.FakeGatoHistoryService("weather", historyAccessory, {
270
+ storage: "fs"
271
+ });
272
+ this.log("[BOM gov au] Initialized FakeGato history");
343
273
  }
344
274
  }
345
275
 
346
276
  /**
347
277
  * Returns all HomeKit services for this accessory.
348
- *
278
+ *
349
279
  * @returns {Service[]} Array of HomeKit services
350
280
  */
351
281
  getServices() {
352
- /** @type {Service[]} */
282
+ const { Service, Characteristic } = this.hap;
283
+
353
284
  const services = [
354
285
  new Service.AccessoryInformation()
355
286
  .setCharacteristic(Characteristic.Manufacturer, "PCoombe")
@@ -367,13 +298,19 @@ class BOMgovauAccessory {
367
298
  if (this.sensors.humidity && this.humidityService) {
368
299
  services.push(this.humidityService);
369
300
  }
301
+ if (this.sensors.pressure && this.airPressureService) {
302
+ services.push(this.airPressureService);
303
+ }
304
+ if (this.history) {
305
+ services.push(this.history);
306
+ }
370
307
 
371
308
  return services;
372
309
  }
373
310
 
374
311
  /**
375
312
  * Shutdown method for cleanup.
376
- *
313
+ *
377
314
  * Called by Homebridge when accessory is removed.
378
315
  * Clears the periodic update interval.
379
316
  */
@@ -387,194 +324,187 @@ class BOMgovauAccessory {
387
324
 
388
325
  /**
389
326
  * Fetches and updates weather observations from BOM.
390
- *
391
- * Uses mutex lock to prevent concurrent fetches (race condition protection).
392
- * Parses BOM timestamp and sets data expiry based on update frequency.
393
- * Updates all enabled sensor characteristics and logs to FakeGato history.
394
- *
327
+ *
328
+ * Concurrent callers share the same in-flight request.
329
+ *
395
330
  * @async
396
331
  * @returns {Promise<void>}
397
332
  */
398
- async updateObservations() {
399
- // Mutex to prevent concurrent fetches (race condition fix)
400
- if (this._updateLock) {
401
- this.log("[BOM gov au] Update already in progress, skipping");
402
- return;
333
+ updateObservations() {
334
+ if (!this._updatePromise) {
335
+ this._updatePromise = this._performObservationUpdate()
336
+ .finally(() => {
337
+ this._updatePromise = null;
338
+ });
403
339
  }
340
+ return this._updatePromise;
341
+ }
342
+
343
+ /**
344
+ * Fetches observations, updates sensor availability, and records history.
345
+ *
346
+ * @returns {Promise<void>}
347
+ * @private
348
+ */
349
+ async _performObservationUpdate() {
350
+ const { Characteristic } = this.hap;
404
351
 
405
352
  /** @type {number} */
406
353
  const now = Date.now();
407
354
 
408
- if (now >= this.BOMdataExpires) {
409
- this._updateLock = true;
410
- this.log("[BOM gov au] Current Time is " + now + ", BOM data expires at " + this.BOMdataExpires);
411
- this.log("[BOM gov au] Updating observations from BOM.");
412
-
413
- try {
414
- /** @type {Object} */
415
- const json = await this._fetchStationJson();
416
-
417
- this.obs = json.observations.data[0];
418
- this.header = json.observations.header[0];
419
-
420
- this.log("[BOM gov au] Observations retrieved for " + this.header.name + ", " + this.header.state);
421
-
422
- const fetchedAt = Date.now();
423
- // Parse BOM timestamp (format: YYYYMMDDHHMMSS)
424
- const timestamp = this.obs.aifstime_utc;
425
- const validTimestamp = typeof timestamp === "string" && /^\d{14}$/.test(timestamp);
426
- /** @type {number} */
427
- const BOMyear = validTimestamp ? parseInt(timestamp.substr(0, 4)) : NaN;
428
- /** @type {number} */
429
- const BOMmonth = validTimestamp ? parseInt(timestamp.substr(4, 2)) - 1 : NaN;
430
- /** @type {number} */
431
- const BOMday = validTimestamp ? parseInt(timestamp.substr(6, 2)) : NaN;
432
- /** @type {number} */
433
- const BOMhour = validTimestamp ? parseInt(timestamp.substr(8, 2)) : NaN;
434
- /** @type {number} */
435
- const BOMmin = validTimestamp ? parseInt(timestamp.substr(10, 2)) : NaN;
436
- /** @type {number} */
437
- const BOMsec = validTimestamp ? parseInt(timestamp.substr(12, 2)) : NaN;
438
- const observationTime = validTimestamp
439
- ? Date.UTC(BOMyear, BOMmonth, BOMday, BOMhour, BOMmin, BOMsec)
440
- : NaN;
441
- const observationExpiry = observationTime + this.updateFrequency;
442
-
443
- // Use the observation expiry if it is still ahead; otherwise wait a full interval after fetch.
444
- this.BOMdataExpires = Number.isFinite(observationExpiry) && observationExpiry > fetchedAt
445
- ? observationExpiry
446
- : fetchedAt + this.updateFrequency;
447
- this.log("[BOM gov au] BOM data will expire at " + new Date(this.BOMdataExpires).toLocaleString() + " which is in " +
448
- ((this.BOMdataExpires - fetchedAt) / 1000 / 60).toFixed(1) + "min");
449
-
450
- // Update characteristics
451
- if (this.sensors.temperature && this.temperatureService) {
452
- this.temperatureService.setCharacteristic(Characteristic.StatusActive, true);
453
- this.temperatureService.setCharacteristic(Characteristic.StatusFault, false);
454
- this.temperatureService.updateCharacteristic(Characteristic.CurrentTemperature,
455
- isNaN(this.obs.air_temp) ? 0 : this.obs.air_temp);
456
- this.temperatureService.updateCharacteristic(this.CommunityTypes.AtmosphericPressureLevel,
457
- isNaN(this.obs.press) ? 0 : this.obs.press);
355
+ if (now < this.BOMdataExpires) {
356
+ this.log("[BOM gov au] BOM data will expire at " + new Date(this.BOMdataExpires).toLocaleString() + " which is in " +
357
+ ((this.BOMdataExpires - now) / 1000 / 60).toFixed(1) + "min");
358
+ return;
359
+ }
360
+
361
+ this.log("[BOM gov au] Current Time is " + now + ", BOM data expires at " + this.BOMdataExpires);
362
+ this.log("[BOM gov au] Updating observations from BOM.");
363
+
364
+ try {
365
+ const { observation, header, fetchedAt, expiresAt } = await this.bomClient.fetchObservations();
366
+ this.obs = observation;
367
+ this.header = header;
368
+ this.log("[BOM gov au] Observations retrieved for " + this.header.name + ", " + this.header.state);
369
+
370
+ this.BOMdataExpires = expiresAt;
371
+ this.log("[BOM gov au] BOM data will expire at " + new Date(this.BOMdataExpires).toLocaleString() + " which is in " +
372
+ ((this.BOMdataExpires - fetchedAt) / 1000 / 60).toFixed(1) + "min");
373
+
374
+ const temperature = this._getObservationValue("air_temp", -100, 100);
375
+ const apparentTemp = this._getObservationValue("apparent_t", -100, 100);
376
+ const humidity = this._getObservationValue("rel_hum", 0, 100);
377
+ const pressure = this._getObservationValue("press", 700, 1100);
378
+
379
+ if (this.sensors.temperature && this.temperatureService) {
380
+ this.temperatureService.setCharacteristic(Characteristic.StatusActive, temperature !== undefined);
381
+ this.temperatureService.setCharacteristic(Characteristic.StatusFault, temperature === undefined);
382
+ if (temperature !== undefined) {
383
+ this.temperatureService.updateCharacteristic(Characteristic.CurrentTemperature, temperature);
458
384
  }
385
+ }
459
386
 
460
- if (this.sensors.apparentTemp && this.apparentTempService) {
461
- this.apparentTempService.setCharacteristic(Characteristic.StatusActive, true);
462
- this.apparentTempService.setCharacteristic(Characteristic.StatusFault, false);
463
- this.apparentTempService.updateCharacteristic(Characteristic.CurrentTemperature,
464
- isNaN(this.obs.apparent_t) ? 0 : this.obs.apparent_t);
387
+ if (this.sensors.apparentTemp && this.apparentTempService) {
388
+ this.apparentTempService.setCharacteristic(Characteristic.StatusActive, apparentTemp !== undefined);
389
+ this.apparentTempService.setCharacteristic(Characteristic.StatusFault, apparentTemp === undefined);
390
+ if (apparentTemp !== undefined) {
391
+ this.apparentTempService.updateCharacteristic(Characteristic.CurrentTemperature, apparentTemp);
465
392
  }
393
+ }
466
394
 
467
- if (this.sensors.humidity && this.humidityService) {
468
- this.humidityService.setCharacteristic(Characteristic.StatusActive, true);
469
- this.humidityService.setCharacteristic(Characteristic.StatusFault, false);
470
- this.humidityService.updateCharacteristic(Characteristic.CurrentRelativeHumidity,
471
- isNaN(this.obs.rel_hum) ? 0 : this.obs.rel_hum);
395
+ if (this.sensors.humidity && this.humidityService) {
396
+ this.humidityService.setCharacteristic(Characteristic.StatusActive, humidity !== undefined);
397
+ this.humidityService.setCharacteristic(Characteristic.StatusFault, humidity === undefined);
398
+ if (humidity !== undefined) {
399
+ this.humidityService.updateCharacteristic(Characteristic.CurrentRelativeHumidity, humidity);
472
400
  }
401
+ }
473
402
 
474
- // FakeGato logging
475
- if (this.history) {
476
- this.history.addEntry({
477
- time: Math.floor(now / 1000),
478
- temp: this.obs.air_temp,
479
- pressure: this.obs.press,
480
- humidity: this.obs.rel_hum
481
- });
482
- this.log("[BOM gov au] Added FakeGato history entry");
403
+ if (this.sensors.pressure && this.airPressureService) {
404
+ this.airPressureService.setCharacteristic(Characteristic.StatusActive, pressure !== undefined);
405
+ this.airPressureService.setCharacteristic(Characteristic.StatusFault, pressure === undefined);
406
+ if (pressure !== undefined) {
407
+ this.airPressureService.updateCharacteristic(this.AirPressureCharacteristic, pressure);
483
408
  }
409
+ }
484
410
 
485
- } catch (error) {
486
- this.log.error("[BOM gov au] Failed to fetch BOM data:", error.message);
411
+ if (this.history) {
412
+ this.history.addEntry({
413
+ time: Math.floor(fetchedAt / 1000),
414
+ temp: temperature ?? 0,
415
+ humidity: humidity ?? 0,
416
+ pressure: pressure ?? 0
417
+ });
418
+ this.log("[BOM gov au] Added FakeGato history entry");
419
+ }
420
+ } catch (error) {
421
+ this.log.error("[BOM gov au] Failed to fetch BOM data:", error.message);
487
422
 
488
- if (this.sensors.temperature && this.temperatureService) {
489
- this.temperatureService.setCharacteristic(Characteristic.StatusFault, true);
490
- }
491
- if (this.sensors.apparentTemp && this.apparentTempService) {
492
- this.apparentTempService.setCharacteristic(Characteristic.StatusFault, true);
493
- }
494
- if (this.sensors.humidity && this.humidityService) {
495
- this.humidityService.setCharacteristic(Characteristic.StatusFault, true);
496
- }
497
- } finally {
498
- this._updateLock = false;
423
+ if (this.sensors.temperature && this.temperatureService) {
424
+ this.temperatureService.setCharacteristic(Characteristic.StatusActive, false);
425
+ this.temperatureService.setCharacteristic(Characteristic.StatusFault, true);
426
+ }
427
+ if (this.sensors.apparentTemp && this.apparentTempService) {
428
+ this.apparentTempService.setCharacteristic(Characteristic.StatusActive, false);
429
+ this.apparentTempService.setCharacteristic(Characteristic.StatusFault, true);
430
+ }
431
+ if (this.sensors.humidity && this.humidityService) {
432
+ this.humidityService.setCharacteristic(Characteristic.StatusActive, false);
433
+ this.humidityService.setCharacteristic(Characteristic.StatusFault, true);
434
+ }
435
+ if (this.sensors.pressure && this.airPressureService) {
436
+ this.airPressureService.setCharacteristic(Characteristic.StatusActive, false);
437
+ this.airPressureService.setCharacteristic(Characteristic.StatusFault, true);
499
438
  }
500
- } else {
501
- this.log("[BOM gov au] BOM data will expire at " + new Date(this.BOMdataExpires).toLocaleString() + " which is in " +
502
- ((this.BOMdataExpires - now) / 1000 / 60).toFixed(1) + "min");
503
439
  }
504
440
  }
505
441
 
506
442
  /**
507
- * Gets current temperature state.
508
- *
509
- * @async
510
- * @returns {Promise<number>} Temperature in Celsius, 0 if unavailable
443
+ * Gets the current air temperature.
444
+ *
445
+ * @returns {Promise<number>} Temperature in Celsius
446
+ * @throws {Error} If temperature is unavailable or outside the supported range
511
447
  */
512
448
  async getStateTemperature() {
513
- try {
514
- await this.updateObservations();
515
- return isNaN(this.obs.air_temp) ? 0 : this.obs.air_temp;
516
- } catch (error) {
517
- this.log.error("[BOM gov au] getStateTemperature error:", error.message);
518
- return 0; // Safe default
449
+ await this.updateObservations();
450
+ const value = this._getObservationValue("air_temp", -100, 100);
451
+ if (value === undefined) {
452
+ throw new Error("BOM temperature is unavailable or outside the supported range");
519
453
  }
454
+ return value;
520
455
  }
521
456
 
522
457
  /**
523
- * Gets current atmospheric pressure state.
524
- *
525
- * @async
526
- * @returns {Promise<number>} Pressure in hPa, 0 if unavailable
458
+ * Gets the current air pressure.
459
+ *
460
+ * @returns {Promise<number>} Pressure in hPa
461
+ * @throws {Error} If pressure is unavailable or outside the supported range
527
462
  */
528
463
  async getStatePressure() {
529
- try {
530
- await this.updateObservations();
531
- return isNaN(this.obs.press) ? 0 : this.obs.press;
532
- } catch (error) {
533
- this.log.error("[BOM gov au] getStatePressure error:", error.message);
534
- return 0; // Safe default
464
+ await this.updateObservations();
465
+ const value = this._getObservationValue("press", 700, 1100);
466
+ if (value === undefined) {
467
+ throw new Error("BOM pressure is unavailable or outside the supported range");
535
468
  }
469
+ return value;
536
470
  }
537
471
 
538
472
  /**
539
- * Gets current apparent temperature state.
540
- *
541
- * @async
542
- * @returns {Promise<number>} Apparent temperature in Celsius, 0 if unavailable
473
+ * Gets the current apparent temperature.
474
+ *
475
+ * @returns {Promise<number>} Apparent temperature in Celsius
476
+ * @throws {Error} If apparent temperature is unavailable or outside the supported range
543
477
  */
544
478
  async getStateApparentTemperature() {
545
- try {
546
- await this.updateObservations();
547
- return isNaN(this.obs.apparent_t) ? 0 : this.obs.apparent_t;
548
- } catch (error) {
549
- this.log.error("[BOM gov au] getStateApparentTemperature error:", error.message);
550
- return 0; // Safe default
479
+ await this.updateObservations();
480
+ const value = this._getObservationValue("apparent_t", -100, 100);
481
+ if (value === undefined) {
482
+ throw new Error("BOM apparent temperature is unavailable or outside the supported range");
551
483
  }
484
+ return value;
552
485
  }
553
486
 
554
487
  /**
555
- * Gets current humidity state.
556
- *
557
- * @async
558
- * @returns {Promise<number>} Relative humidity percentage, 0 if unavailable
488
+ * Gets the current relative humidity.
489
+ *
490
+ * @returns {Promise<number>} Relative humidity percentage
491
+ * @throws {Error} If humidity is unavailable or outside the supported range
559
492
  */
560
493
  async getStateHumidity() {
561
- try {
562
- await this.updateObservations();
563
- return isNaN(this.obs.rel_hum) ? 0 : this.obs.rel_hum;
564
- } catch (error) {
565
- this.log.error("[BOM gov au] getStateHumidity error:", error.message);
566
- return 0; // Safe default
494
+ await this.updateObservations();
495
+ const value = this._getObservationValue("rel_hum", 0, 100);
496
+ if (value === undefined) {
497
+ throw new Error("BOM humidity is unavailable or outside the supported range");
567
498
  }
499
+ return value;
568
500
  }
569
501
  }
570
502
 
571
503
  /**
572
504
  * Homebridge plugin entry point.
573
- *
574
- * Registers the BOMgovau accessory with Homebridge.
575
- *
505
+ *
576
506
  * @param {HomebridgeAPI} api - Homebridge API instance
577
507
  */
578
- module.exports = (api) => {
508
+ module.exports = api => {
579
509
  api.registerAccessory(PLUGIN_NAME, "BOMgovau", BOMgovauAccessory);
580
510
  };
@@ -0,0 +1,204 @@
1
+ "use strict";
2
+
3
+ const pjson = require("../package.json");
4
+ const dns = require("node:dns").promises;
5
+ const { BlockList } = require("node:net");
6
+
7
+ const PLUGIN_NAME = pjson.name;
8
+ const PLUGIN_VERSION = pjson.version;
9
+ const DEFAULT_STATION_URL = "http://reg.bom.gov.au/fwo/IDN60903/IDN60903.94926.json";
10
+ const FETCH_TIMEOUT_MS = 10 * 1000;
11
+ const MAX_RESPONSE_BYTES = 1024 * 1024;
12
+ const MAX_REDIRECTS = 3;
13
+ const nonPublicAddresses = new BlockList();
14
+ [
15
+ ["0.0.0.0", 8, "ipv4"],
16
+ ["10.0.0.0", 8, "ipv4"],
17
+ ["100.64.0.0", 10, "ipv4"],
18
+ ["127.0.0.0", 8, "ipv4"],
19
+ ["169.254.0.0", 16, "ipv4"],
20
+ ["172.16.0.0", 12, "ipv4"],
21
+ ["192.168.0.0", 16, "ipv4"],
22
+ ["224.0.0.0", 4, "ipv4"],
23
+ ["::", 128, "ipv6"],
24
+ ["::1", 128, "ipv6"],
25
+ ["fc00::", 7, "ipv6"],
26
+ ["fe80::", 10, "ipv6"],
27
+ ["ff00::", 8, "ipv6"]
28
+ ].forEach(([address, prefix, family]) => {
29
+ nonPublicAddresses.addSubnet(address, prefix, family);
30
+ });
31
+
32
+ /**
33
+ * Fetches and parses weather observations from an approved BOM station URL.
34
+ */
35
+ class BomClient {
36
+ /**
37
+ * @param {Object} options
38
+ * @param {string} [options.stationURL] - BOM JSON observation URL
39
+ * @param {string} options.name - Accessory name for the request User-Agent
40
+ * @param {number} options.updateFrequency - Observation cache duration in milliseconds
41
+ * @param {HomebridgeLogger} options.log - Homebridge logger
42
+ */
43
+ constructor({ stationURL, name, updateFrequency, log }) {
44
+ this.name = name;
45
+ this.updateFrequency = updateFrequency;
46
+ this.log = log;
47
+ this.stationURL = stationURL || DEFAULT_STATION_URL;
48
+
49
+ if (!this._isValidUrl(this.stationURL)) {
50
+ this.log.error("[BOM gov au] Invalid stationURL: " + this.stationURL + ". Using default.");
51
+ this.stationURL = DEFAULT_STATION_URL;
52
+ }
53
+ }
54
+
55
+ /**
56
+ * Fetches the latest station observation and computes its cache expiry.
57
+ *
58
+ * @returns {Promise<{observation: Object, header: Object, fetchedAt: number, expiresAt: number}>}
59
+ */
60
+ async fetchObservations() {
61
+ const json = await this._fetchStationJson();
62
+ const observation = json?.observations?.data?.[0];
63
+ const header = json?.observations?.header?.[0];
64
+ if (!observation || typeof observation !== "object" || !header || typeof header !== "object") {
65
+ throw new Error("BOM response is missing observation data or station header");
66
+ }
67
+
68
+ const fetchedAt = Date.now();
69
+ const timestamp = observation.aifstime_utc;
70
+ const validTimestamp = typeof timestamp === "string" && /^\d{14}$/.test(timestamp);
71
+ /** @type {number} */
72
+ const BOMyear = validTimestamp ? parseInt(timestamp.slice(0, 4), 10) : NaN;
73
+ /** @type {number} */
74
+ const BOMmonth = validTimestamp ? parseInt(timestamp.slice(4, 6), 10) - 1 : NaN;
75
+ /** @type {number} */
76
+ const BOMday = validTimestamp ? parseInt(timestamp.slice(6, 8), 10) : NaN;
77
+ /** @type {number} */
78
+ const BOMhour = validTimestamp ? parseInt(timestamp.slice(8, 10), 10) : NaN;
79
+ /** @type {number} */
80
+ const BOMmin = validTimestamp ? parseInt(timestamp.slice(10, 12), 10) : NaN;
81
+ /** @type {number} */
82
+ const BOMsec = validTimestamp ? parseInt(timestamp.slice(12, 14), 10) : NaN;
83
+ /** @type {Date|null} */
84
+ const observationDate = validTimestamp ? new Date(0) : null;
85
+ observationDate?.setUTCFullYear(BOMyear, BOMmonth, BOMday);
86
+ observationDate?.setUTCHours(BOMhour, BOMmin, BOMsec, 0);
87
+ /** @type {number} */
88
+ const observationTime = observationDate?.getTime() ?? NaN;
89
+ const observationExpiry = observationTime + this.updateFrequency;
90
+ const expiresAt = Number.isFinite(observationExpiry) && observationExpiry > fetchedAt
91
+ ? observationExpiry
92
+ : fetchedAt + this.updateFrequency;
93
+
94
+ return { observation, header, fetchedAt, expiresAt };
95
+ }
96
+
97
+ /**
98
+ * Validates a URL string.
99
+ *
100
+ * @param {string} value - URL to validate
101
+ * @returns {boolean} True if valid URL
102
+ * @private
103
+ */
104
+ _isValidUrl(value) {
105
+ try {
106
+ const url = new URL(value);
107
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
108
+ return false;
109
+ }
110
+ if (url.username || url.password) {
111
+ return false;
112
+ }
113
+ const hostname = url.hostname.toLowerCase();
114
+ return hostname === "bom.gov.au" || hostname.endsWith(".bom.gov.au");
115
+ } catch {
116
+ return false;
117
+ }
118
+ }
119
+
120
+ /**
121
+ * Resolves the station host and rejects private network addresses.
122
+ *
123
+ * @param {string} stationURL - BOM station URL
124
+ * @returns {Promise<void>}
125
+ * @private
126
+ */
127
+ async _validateStationHost(stationURL) {
128
+ const url = new URL(stationURL);
129
+ const addresses = await dns.lookup(url.hostname, { all: true, verbatim: true });
130
+ if (!addresses.length || addresses.some(({ address, family }) =>
131
+ nonPublicAddresses.check(address, family === 6 ? "ipv6" : "ipv4"))) {
132
+ throw new Error("Station host resolves to a non-public IP address");
133
+ }
134
+ }
135
+
136
+ /**
137
+ * Fetches station JSON while restricting redirects and response size.
138
+ *
139
+ * @returns {Promise<Object>}
140
+ * @private
141
+ */
142
+ async _fetchStationJson() {
143
+ let currentURL = this.stationURL;
144
+
145
+ for (let redirectCount = 0; redirectCount <= MAX_REDIRECTS; redirectCount++) {
146
+ if (!this._isValidUrl(currentURL)) {
147
+ throw new Error("Station URL is not an approved BOM host");
148
+ }
149
+ await this._validateStationHost(currentURL);
150
+
151
+ const controller = new AbortController();
152
+ const timeout = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
153
+
154
+ try {
155
+ const response = await fetch(currentURL, {
156
+ headers: { "User-Agent": PLUGIN_NAME + "/" + PLUGIN_VERSION + " (" + this.name + ")" },
157
+ redirect: "manual",
158
+ signal: controller.signal
159
+ });
160
+
161
+ if (response.status >= 300 && response.status < 400) {
162
+ const location = response.headers.get("location");
163
+ if (!location) {
164
+ throw new Error("Redirect response missing Location header");
165
+ }
166
+ await response.body?.cancel();
167
+ currentURL = new URL(location, currentURL).toString();
168
+ continue;
169
+ }
170
+
171
+ if (!response.ok) {
172
+ throw new Error("HTTP error " + response.status);
173
+ }
174
+
175
+ const contentLength = Number(response.headers.get("content-length"));
176
+ if (Number.isFinite(contentLength) && contentLength > MAX_RESPONSE_BYTES) {
177
+ throw new Error("BOM response exceeds maximum allowed size");
178
+ }
179
+
180
+ if (!response.body) {
181
+ throw new Error("BOM response has no body");
182
+ }
183
+
184
+ let receivedBytes = 0;
185
+ const chunks = [];
186
+ for await (const chunk of response.body) {
187
+ receivedBytes += chunk.length;
188
+ if (receivedBytes > MAX_RESPONSE_BYTES) {
189
+ throw new Error("BOM response exceeds maximum allowed size");
190
+ }
191
+ chunks.push(Buffer.from(chunk));
192
+ }
193
+
194
+ return JSON.parse(Buffer.concat(chunks).toString("utf8"));
195
+ } finally {
196
+ clearTimeout(timeout);
197
+ }
198
+ }
199
+
200
+ throw new Error("Too many redirects");
201
+ }
202
+ }
203
+
204
+ module.exports = BomClient;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "homebridge-bomgovau-v2",
3
- "version": "0.2.2",
3
+ "version": "0.2.5",
4
4
  "description": "Makes BOM.gov.au data available in your Homebridge(Homekit) setup",
5
5
  "homepage": "https://github.com/pcoombe/homebridge-BOMgovau",
6
6
  "license": "Apache-2",
@@ -33,17 +33,13 @@
33
33
  },
34
34
  "main": "index.js",
35
35
  "scripts": {
36
- "lint": "eslint index.js scripts/test-bom-feed.js",
37
- "parse": "node --check index.js && node --check scripts/test-bom-feed.js",
36
+ "lint": "eslint index.js lib/bom-client.js scripts/test-bom-feed.js",
37
+ "parse": "node --check index.js && node --check lib/bom-client.js && node --check scripts/test-bom-feed.js",
38
38
  "test:bom-feed": "node scripts/test-bom-feed.js"
39
39
  },
40
40
  "dependencies": {
41
- "fakegato-history": "^0.6.2",
42
- "hap-nodejs-community-types": "^0.3.1"
43
- },
44
- "peerDependencies": {
45
- "hap-nodejs": "^0.13.0"
46
- },
41
+ "fakegato-history": "^0.6.2"
42
+ },
47
43
  "devDependencies": {
48
44
  "eslint": "^10.15.0"
49
45
  }
package/readme.md CHANGED
@@ -75,7 +75,7 @@ The test needs network access to BOM. It exits with an error if loading or updat
75
75
  3. At the bottom of the station page, locate the **JSON data feed** link
76
76
  4. Copy the URL (format: `http://reg.bom.gov.au/fwo/IDX60XXX/IDX60XXX.XXXXX.json`)
77
77
 
78
- ### Config.json (Legacy)
78
+ ### Homebridge accessory configuration
79
79
 
80
80
  ```json
81
81
  {
@@ -88,34 +88,17 @@ The test needs network access to BOM. It exits with an error if loading or updat
88
88
  "sensors": {
89
89
  "temperature": true,
90
90
  "humidity": true,
91
- "apparentTemp": true
91
+ "apparentTemp": true,
92
+ "pressure": true
92
93
  }
93
94
  }
94
95
  ]
95
96
  }
96
97
  ```
97
98
 
98
- ### Homebridge UI (Config.json for Homebridge 2.x)
99
-
100
- ```json
101
- {
102
- "platforms": [
103
- {
104
- "platform": "BOMgovau",
105
- "name": "Canberra Airport",
106
- "stationURL": "http://reg.bom.gov.au/fwo/IDN60903/IDN60903.94926.json",
107
- "updateFrequency": 1800000,
108
- "sensors": {
109
- "temperature": true,
110
- "humidity": true,
111
- "apparentTemp": true
112
- }
113
- }
114
- ]
115
- }
116
- ```
117
-
118
- > **Note**: The accessory can be configured either as an accessory (`accessories` array) or platform (`platforms` array). Both work with Homebridge 2.x.
99
+ > This plugin registers a Homebridge accessory, not a dynamic platform. Configure it under the `accessories` array; a `platforms` entry is not supported.
100
+ >
101
+ > Pressure is exposed as a separate Eve-compatible Air Pressure service. Sensors with unavailable or invalid readings are marked inactive and faulted, so compatible HomeKit apps can show them as offline; the plugin does not fabricate readings.
119
102
 
120
103
  ---
121
104
 
@@ -123,13 +106,14 @@ The test needs network access to BOM. It exits with an error if loading or updat
123
106
 
124
107
  | Option | Type | Required | Default | Description |
125
108
  |--------|------|----------|---------|-------------|
126
- | `accessory` / `platform` | string | Yes | `"BOMgovau"` | Must be `BOMgovau` |
109
+ | `accessory` | string | Yes | `"BOMgovau"` | Must be `BOMgovau` |
127
110
  | `name` | string | Yes | - | Display name in HomeKit |
128
111
  | `stationURL` | string | No | Canberra Airport | BOM JSON observation URL |
129
112
  | `updateFrequency` | number | No | `1800000` (30 min) | Update interval in milliseconds |
130
113
  | `sensors.temperature` | boolean | No | `true` | Enable temperature sensor |
131
114
  | `sensors.humidity` | boolean | No | `true` | Enable humidity sensor |
132
115
  | `sensors.apparentTemp` | boolean | No | `true` | Enable apparent temperature sensor |
116
+ | `sensors.pressure` | boolean | No | `true` | Enable separate Eve-compatible air-pressure service |
133
117
 
134
118
  ### Example: Disable Humidity
135
119
 
@@ -180,8 +164,8 @@ Any BOM station with a JSON observation feed. Common examples:
180
164
 
181
165
  The plugin supports [FakeGato History](https://github.com/simont77/fakegato-history) for viewing historical charts in the **Eve app** or **Home+**.
182
166
 
183
- - Automatically enabled when temperature or humidity sensor is active
184
- - Logs temperature, humidity, and pressure every 30 minutes
167
+ - Automatically enabled when a temperature, humidity, or pressure sensor is active
168
+ - Uses FakeGato's standard `weather` format with temperature, humidity, and pressure in every entry; missing or invalid history values are recorded as `0` (live sensors still show offline)
185
169
  - Data persists across Homebridge restarts
186
170
 
187
171
  ---
@@ -9,6 +9,12 @@ const stationURL = process.argv[2] ||
9
9
  "http://www.bom.gov.au/fwo/IDN60901/IDN60901.94763.json";
10
10
 
11
11
  class CharacteristicMock {
12
+ constructor(displayName, UUID, props) {
13
+ this.displayName = displayName;
14
+ this.UUID = UUID;
15
+ this.props = props;
16
+ }
17
+
12
18
  setProps(props) {
13
19
  this.props = props;
14
20
  return this;
@@ -18,17 +24,26 @@ class CharacteristicMock {
18
24
  this.getter = handler;
19
25
  return this;
20
26
  }
27
+
28
+ getDefaultValue() {
29
+ return 0;
30
+ }
21
31
  }
22
32
 
23
33
  class ServiceMock {
24
- constructor(displayName) {
34
+ constructor(displayName, UUID, subtype) {
25
35
  this.displayName = displayName;
36
+ this.UUID = UUID;
37
+ this.subtype = subtype;
26
38
  this.characteristics = new Map();
27
39
  }
28
40
 
29
41
  getCharacteristic(type) {
30
42
  if (!this.characteristics.has(type)) {
31
- this.characteristics.set(type, new CharacteristicMock());
43
+ const characteristic = typeof type === "function"
44
+ ? new type()
45
+ : new CharacteristicMock();
46
+ this.characteristics.set(type, characteristic);
32
47
  }
33
48
  return this.characteristics.get(type);
34
49
  }
@@ -37,6 +52,10 @@ class ServiceMock {
37
52
  return this.getCharacteristic(type);
38
53
  }
39
54
 
55
+ addOptionalCharacteristic(type) {
56
+ return this.getCharacteristic(type);
57
+ }
58
+
40
59
  setCharacteristic(type, value) {
41
60
  this.getCharacteristic(type).value = value;
42
61
  return this;
@@ -48,29 +67,43 @@ class ServiceMock {
48
67
  }
49
68
  }
50
69
 
51
- const Service = {
52
- AccessoryInformation: class extends ServiceMock {},
53
- TemperatureSensor: class extends ServiceMock {},
54
- HumiditySensor: class extends ServiceMock {}
55
- };
56
- const Characteristic = new Proxy(
57
- { Formats: { UINT16: "uint16" } },
58
- { get: (target, key) => key in target ? target[key] : String(key) }
59
- );
60
- const historyService = class {
61
- addEntry() {}
70
+ const Service = class extends ServiceMock {};
71
+ Service.AccessoryInformation = class extends Service {};
72
+ Service.TemperatureSensor = class extends Service {};
73
+ Service.HumiditySensor = class extends Service {};
74
+ CharacteristicMock.Formats = { UINT16: "uint16" };
75
+ CharacteristicMock.Perms = {
76
+ READ: "pr",
77
+ WRITE: "pw",
78
+ PAIRED_READ: "pr",
79
+ NOTIFY: "ev"
62
80
  };
81
+ CharacteristicMock.Units = { PRESSURE: "hPa" };
82
+ const Characteristic = new Proxy(CharacteristicMock, {
83
+ get: (target, key, receiver) =>
84
+ key in target ? Reflect.get(target, key, receiver) : String(key)
85
+ });
86
+ let fakegatoApi;
87
+ let historyConfig;
88
+ const historyEntries = [];
63
89
 
64
90
  const originalLoad = Module._load;
65
91
  Module._load = function(request, parent, isMain) {
66
- if (request === "hap-nodejs") {
67
- return { Service, Characteristic };
68
- }
69
- if (request === "hap-nodejs-community-types") {
70
- return () => ({ AtmosphericPressureLevel: "AtmosphericPressureLevel" });
71
- }
72
92
  if (request === "fakegato-history") {
73
- return () => historyService;
93
+ return api => {
94
+ fakegatoApi = api;
95
+ return class {
96
+ constructor(type, accessory, options) {
97
+ historyConfig = { type, accessory, options };
98
+ this.displayName = `${accessory.displayName} History`;
99
+ this.characteristics = new Map();
100
+ }
101
+
102
+ addEntry(entry) {
103
+ historyEntries.push(entry);
104
+ }
105
+ };
106
+ };
74
107
  }
75
108
  return originalLoad.call(this, request, parent, isMain);
76
109
  };
@@ -81,6 +114,13 @@ function characteristicValue(service, type) {
81
114
 
82
115
  async function main() {
83
116
  const api = {
117
+ hap: {
118
+ Service,
119
+ Characteristic,
120
+ uuid: () => "mock-uuid",
121
+ Formats: Characteristic.Formats,
122
+ Perms: Characteristic.Perms
123
+ },
84
124
  registerAccessory(pluginName, accessoryName, accessoryClass) {
85
125
  this.accessoryClass = accessoryClass;
86
126
  this.accessoryName = accessoryName;
@@ -97,24 +137,81 @@ async function main() {
97
137
  assert.ok(api.accessoryClass, "Plugin did not register its accessory");
98
138
  assert.equal(api.accessoryName, "BOMgovau");
99
139
 
100
- accessory = new api.accessoryClass(api, logger, {
140
+ accessory = new api.accessoryClass(logger, {
101
141
  name: "BOM feed test",
102
142
  stationURL,
103
143
  sensors: {
104
144
  temperature: true,
105
145
  humidity: true,
106
- apparentTemp: true
146
+ apparentTemp: true,
147
+ pressure: true
107
148
  }
108
- });
149
+ }, api);
109
150
 
110
151
  clearInterval(accessory.updateInterval);
111
- await accessory.updateObservations();
152
+ assert.equal(fakegatoApi, api, "FakeGato did not receive the Homebridge API");
153
+ assert.equal(historyConfig.type, "weather", "FakeGato should use its standard weather format");
154
+ assert.ok(accessory.getServices().includes(accessory.history),
155
+ "FakeGato history service was not exposed");
156
+ assert.ok(accessory.getServices().includes(accessory.airPressureService),
157
+ "Pressure should be exposed as its own service");
158
+ assert.equal(accessory.airPressureService.UUID, "E863F00A-079E-48FF-8F27-9C2605A29F52");
159
+ const pressure = accessory.airPressureService.characteristics.get(
160
+ accessory.AirPressureCharacteristic
161
+ );
162
+ assert.ok(pressure, "Eve Air Pressure characteristic was not created");
163
+ assert.equal(pressure.UUID, "E863F10F-079E-48FF-8F27-9C2605A29F52");
164
+ assert.equal(pressure.props.unit, "hPa");
165
+ assert.equal(pressure.props.minValue, 700);
166
+ assert.equal(pressure.props.maxValue, 1100);
167
+ const fetchObservations = accessory.bomClient.fetchObservations.bind(accessory.bomClient);
168
+ accessory.bomClient.fetchObservations = async () => {
169
+ throw new Error("Simulated initial BOM request failure");
170
+ };
171
+ await assert.rejects(accessory.getStateTemperature(), /temperature is unavailable/,
172
+ "Initial temperature should be unavailable when the first BOM request fails");
173
+ await assert.rejects(accessory.getStateHumidity(), /humidity is unavailable/,
174
+ "Initial humidity should be unavailable when the first BOM request fails");
175
+ await assert.rejects(accessory.getStateApparentTemperature(), /apparent temperature is unavailable/,
176
+ "Initial apparent temperature should be unavailable when the first BOM request fails");
177
+ assert.equal(accessory.obs.air_temp, undefined,
178
+ "Temperature should not start with a plausible zero reading");
179
+ assert.equal(accessory.obs.rel_hum, undefined,
180
+ "Humidity should not start with a plausible zero reading");
181
+ assert.equal(accessory.obs.apparent_t, undefined,
182
+ "Apparent temperature should not start with a plausible zero reading");
183
+ assert.equal(characteristicValue(accessory.temperatureService, "StatusActive"), false);
184
+ assert.equal(characteristicValue(accessory.temperatureService, "StatusFault"), true);
185
+ assert.equal(characteristicValue(accessory.humidityService, "StatusActive"), false);
186
+ assert.equal(characteristicValue(accessory.humidityService, "StatusFault"), true);
187
+ assert.equal(characteristicValue(accessory.apparentTempService, "StatusActive"), false);
188
+ assert.equal(characteristicValue(accessory.apparentTempService, "StatusFault"), true);
189
+ logErrors.length = 0;
190
+
191
+ let fetchCount = 0;
192
+ accessory.bomClient.fetchObservations = async () => {
193
+ fetchCount++;
194
+ return fetchObservations();
195
+ };
196
+ const [temperatureReading, humidityReading] = await Promise.all([
197
+ accessory.getStateTemperature(),
198
+ accessory.getStateHumidity()
199
+ ]);
200
+ assert.equal(fetchCount, 1, "Concurrent sensor reads should share one feed request");
201
+ assert.equal(temperatureReading, accessory.obs.air_temp);
202
+ assert.equal(humidityReading, accessory.obs.rel_hum);
112
203
  await new Promise(resolve => setImmediate(resolve));
113
204
 
114
205
  assert.equal(logErrors.length, 0, `Plugin logged errors:\n${logErrors.join("\n")}`);
115
206
  assert.ok(accessory.header?.name, "BOM station name was not loaded");
116
207
  assert.ok(accessory.header?.state, "BOM station state was not loaded");
117
208
  assert.ok(/^\d{14}$/.test(accessory.obs?.aifstime_utc), "Observation timestamp is invalid");
209
+ const originalTemperature = accessory.obs.air_temp;
210
+ assert.equal(accessory._getObservationValue("air_temp", -100, 100), originalTemperature);
211
+ accessory.obs.air_temp = null;
212
+ assert.equal(accessory._getObservationValue("air_temp", -100, 100), undefined,
213
+ "Null temperature must be treated as unavailable");
214
+ accessory.obs.air_temp = originalTemperature;
118
215
 
119
216
  const checks = [
120
217
  ["temperature", accessory.temperatureService, "CurrentTemperature", accessory.obs.air_temp],
@@ -131,10 +228,51 @@ async function main() {
131
228
  `${label} characteristic was not updated from BOM data`
132
229
  );
133
230
  assert.equal(characteristicValue(service, "StatusFault"), false, `${label} service has a fault`);
231
+ assert.equal(characteristicValue(service, "StatusActive"), true, `${label} service is offline`);
232
+ }
233
+
234
+ if (typeof accessory.obs.press === "number" &&
235
+ Number.isFinite(accessory.obs.press) &&
236
+ accessory.obs.press >= 700 &&
237
+ accessory.obs.press <= 1100) {
238
+ assert.equal(
239
+ characteristicValue(accessory.airPressureService, accessory.AirPressureCharacteristic),
240
+ accessory.obs.press,
241
+ "Pressure characteristic was not updated from BOM data"
242
+ );
243
+ assert.equal(characteristicValue(accessory.airPressureService, "StatusFault"), false);
244
+ assert.equal(characteristicValue(accessory.airPressureService, "StatusActive"), true,
245
+ "Pressure service is offline despite a valid reading");
246
+ } else {
247
+ assert.equal(characteristicValue(accessory.airPressureService, "StatusFault"), true,
248
+ "Pressure service should be faulted when the feed omits pressure");
249
+ assert.equal(characteristicValue(accessory.airPressureService, "StatusActive"), false,
250
+ "Pressure service should be offline when the feed omits pressure");
251
+ await assert.rejects(accessory.getStatePressure(), /pressure is unavailable/);
134
252
  }
135
253
 
254
+ assert.equal(historyEntries.length, 1, "A complete weather history entry should be recorded");
255
+ assert.equal(historyEntries[0].temp, accessory.obs.air_temp);
256
+ assert.equal(historyEntries[0].humidity, accessory.obs.rel_hum);
257
+ assert.equal(historyEntries[0].pressure, 0,
258
+ "Missing pressure should be recorded as zero in the weather history entry");
259
+
136
260
  assert.ok(accessory.BOMdataExpires > Date.now(), "Observation cache expiry is not in the future");
137
261
 
262
+ const cachedTemperature = accessory.obs.air_temp;
263
+ const cachedExpiry = accessory.BOMdataExpires;
264
+ accessory.BOMdataExpires = 0;
265
+ accessory.bomClient.fetchObservations = async () => {
266
+ throw new Error("Simulated refresh failure");
267
+ };
268
+ assert.equal(await accessory.getStateTemperature(), cachedTemperature,
269
+ "A failed refresh should preserve the last successful temperature");
270
+ assert.equal(characteristicValue(accessory.temperatureService, "StatusActive"), false,
271
+ "A failed refresh should mark the temperature service offline");
272
+ assert.equal(characteristicValue(accessory.temperatureService, "StatusFault"), true,
273
+ "A failed refresh should mark the temperature service faulted");
274
+ accessory.BOMdataExpires = cachedExpiry;
275
+
138
276
  console.log("BOM plugin data test passed");
139
277
  console.log(`Station: ${accessory.header.name}, ${accessory.header.state}`);
140
278
  console.log(`Observed at: ${accessory.obs.aifstime_utc}`);