homebridge-bomgovau-v2 0.2.4 → 0.2.6

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.hap);
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 = 1013;
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,50 @@ 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
- }
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;
191
180
  }
192
181
 
193
182
  /**
194
- * Fetches the station URL while rejecting redirects outside BOM and limiting response size.
183
+ * Returns the last valid HomeKit value, or a valid initial fallback.
195
184
  *
196
- * @returns {Promise<Object>}
185
+ * @param {Service} service - Sensor service
186
+ * @param {Characteristic} characteristic - Sensor characteristic
187
+ * @param {number} min - Inclusive minimum
188
+ * @param {number} max - Inclusive maximum
189
+ * @param {number} fallback - Valid value to use before a reading is available
190
+ * @returns {number}
197
191
  * @private
198
192
  */
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");
193
+ _getCharacteristicFallback(service, characteristic, min, max, fallback) {
194
+ const value = service.getCharacteristic(characteristic).value;
195
+ return typeof value === "number" && Number.isFinite(value) && value >= min && value <= max
196
+ ? value
197
+ : fallback;
257
198
  }
258
199
 
259
200
  /**
260
201
  * Sets up HomeKit services based on enabled sensors.
261
202
  *
262
- * Creates TemperatureSensor, HumiditySensor services and adds
263
- * pressure characteristic to temperature service.
203
+ * Creates TemperatureSensor and HumiditySensor services.
264
204
  * Initializes FakeGato history on first enabled sensor.
265
205
  *
266
206
  * @private
267
207
  */
268
208
  setupServices() {
209
+ const { Service, Characteristic } = this.hap;
210
+
269
211
  // Temperature Service
270
212
  if (this.sensors.temperature) {
271
213
  /** @type {Service} */
@@ -274,18 +216,11 @@ class BOMgovauAccessory {
274
216
  .setProps({ minValue: -100, maxValue: 100 })
275
217
  .onGet(this.getStateTemperature.bind(this));
276
218
 
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
219
  // Service status
283
220
  this.temperatureService.addCharacteristic(Characteristic.StatusFault);
284
221
  this.temperatureService.addCharacteristic(Characteristic.StatusActive);
285
222
  this.temperatureService.setCharacteristic(Characteristic.StatusActive, false);
286
223
 
287
- // Initialize FakeGato history (will be created on first enabled sensor)
288
- this._initHistory();
289
224
  }
290
225
 
291
226
  // Apparent Temperature Service
@@ -301,8 +236,6 @@ class BOMgovauAccessory {
301
236
  this.apparentTempService.addCharacteristic(Characteristic.StatusActive);
302
237
  this.apparentTempService.setCharacteristic(Characteristic.StatusActive, false);
303
238
 
304
- // Initialize FakeGato history if not already created
305
- this._initHistory();
306
239
  }
307
240
 
308
241
  // Humidity Service
@@ -317,39 +250,55 @@ class BOMgovauAccessory {
317
250
  this.humidityService.setCharacteristic(Characteristic.StatusActive, false);
318
251
  this.humidityService.setCharacteristic(Characteristic.SerialNumber, "Station:" + this.name);
319
252
 
320
- // Initialize FakeGato history if not already created
321
- this._initHistory();
322
253
  }
254
+
255
+ if (this.sensors.pressure) {
256
+ this.airPressureService = new this.AirPressureService(this.name + " Air Pressure", "airPressure");
257
+ this.airPressureService.getCharacteristic(this.AirPressureCharacteristic)
258
+ .onGet(this.getStatePressure.bind(this));
259
+ this.airPressureService.setCharacteristic(Characteristic.StatusFault, true);
260
+ this.airPressureService.setCharacteristic(Characteristic.StatusActive, false);
261
+ }
262
+
263
+ this._initHistory();
323
264
  }
324
265
 
325
266
  /**
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.
267
+ * Initializes FakeGato weather history using the enabled sensor services.
268
+ *
269
+ * Weather history entries contain temperature, humidity, and pressure.
270
+ * Missing readings are recorded as zero to preserve the expected entry format.
330
271
  *
331
272
  * @private
332
273
  */
333
274
  _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
- }
275
+ const sensorServices = [
276
+ this.temperatureService,
277
+ this.humidityService,
278
+ this.airPressureService
279
+ ].filter(Boolean);
280
+
281
+ if (!this.history && sensorServices.length) {
282
+ const historyAccessory = {
283
+ displayName: this.name,
284
+ log: this.log,
285
+ services: sensorServices
286
+ };
287
+ this.history = new this.FakeGatoHistoryService("weather", historyAccessory, {
288
+ storage: "fs"
289
+ });
290
+ this.log("[BOM gov au] Initialized FakeGato history");
343
291
  }
344
292
  }
345
293
 
346
294
  /**
347
295
  * Returns all HomeKit services for this accessory.
348
- *
296
+ *
349
297
  * @returns {Service[]} Array of HomeKit services
350
298
  */
351
299
  getServices() {
352
- /** @type {Service[]} */
300
+ const { Service, Characteristic } = this.hap;
301
+
353
302
  const services = [
354
303
  new Service.AccessoryInformation()
355
304
  .setCharacteristic(Characteristic.Manufacturer, "PCoombe")
@@ -367,13 +316,19 @@ class BOMgovauAccessory {
367
316
  if (this.sensors.humidity && this.humidityService) {
368
317
  services.push(this.humidityService);
369
318
  }
319
+ if (this.sensors.pressure && this.airPressureService) {
320
+ services.push(this.airPressureService);
321
+ }
322
+ if (this.history) {
323
+ services.push(this.history);
324
+ }
370
325
 
371
326
  return services;
372
327
  }
373
328
 
374
329
  /**
375
330
  * Shutdown method for cleanup.
376
- *
331
+ *
377
332
  * Called by Homebridge when accessory is removed.
378
333
  * Clears the periodic update interval.
379
334
  */
@@ -387,194 +342,224 @@ class BOMgovauAccessory {
387
342
 
388
343
  /**
389
344
  * 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
- *
345
+ *
346
+ * Concurrent callers share the same in-flight request.
347
+ *
395
348
  * @async
396
349
  * @returns {Promise<void>}
397
350
  */
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;
351
+ updateObservations() {
352
+ if (!this._updatePromise) {
353
+ this._updatePromise = this._performObservationUpdate()
354
+ .finally(() => {
355
+ this._updatePromise = null;
356
+ });
403
357
  }
358
+ return this._updatePromise;
359
+ }
360
+
361
+ /**
362
+ * Fetches observations, updates sensor availability, and records history.
363
+ *
364
+ * @returns {Promise<void>}
365
+ * @private
366
+ */
367
+ async _performObservationUpdate() {
368
+ const { Characteristic } = this.hap;
404
369
 
405
370
  /** @type {number} */
406
371
  const now = Date.now();
407
372
 
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);
373
+ if (now < this.BOMdataExpires) {
374
+ this.log.debug("[BOM gov au] BOM data will expire at " + new Date(this.BOMdataExpires).toLocaleString() + " which is in " +
375
+ ((this.BOMdataExpires - now) / 1000 / 60).toFixed(1) + "min");
376
+ return;
377
+ }
378
+
379
+ this.log("[BOM gov au] Current Time is " + new Date(now).toLocaleString() +
380
+ ", BOM data expires at " + (this.BOMdataExpires > 0
381
+ ? new Date(this.BOMdataExpires).toLocaleString()
382
+ : "not set"));
383
+ this.log("[BOM gov au] Updating observations from BOM.");
384
+
385
+ try {
386
+ const { observation, header, fetchedAt, expiresAt } = await this.bomClient.fetchObservations();
387
+ this.obs = observation;
388
+ this.header = header;
389
+ this.log("[BOM gov au] Observations retrieved for " + this.header.name + ", " + this.header.state);
390
+
391
+ this.BOMdataExpires = expiresAt;
392
+ this.log.debug("[BOM gov au] BOM data will expire at " + new Date(this.BOMdataExpires).toLocaleString() + " which is in " +
393
+ ((this.BOMdataExpires - fetchedAt) / 1000 / 60).toFixed(1) + "min");
394
+
395
+ const temperature = this._getObservationValue("air_temp", -100, 100);
396
+ const apparentTemp = this._getObservationValue("apparent_t", -100, 100);
397
+ const humidity = this._getObservationValue("rel_hum", 0, 100);
398
+ const pressure = this._getObservationValue("press", 700, 1100);
399
+ const readings = [];
400
+
401
+ if (this.sensors.temperature) {
402
+ readings.push("temperature: " + (temperature === undefined ? "unavailable" : temperature + " °C"));
403
+ }
404
+ if (this.sensors.apparentTemp) {
405
+ readings.push("apparent temperature: " +
406
+ (apparentTemp === undefined ? "unavailable" : apparentTemp + " °C"));
407
+ }
408
+ if (this.sensors.humidity) {
409
+ readings.push("humidity: " + (humidity === undefined ? "unavailable" : humidity + "%"));
410
+ }
411
+ if (this.sensors.pressure) {
412
+ readings.push("pressure: " + (pressure === undefined ? "unavailable" : pressure + " hPa"));
413
+ }
414
+ if (readings.length) {
415
+ this.log("[BOM gov au] Current readings: " + readings.join(", "));
416
+ }
417
+
418
+ if (this.sensors.temperature && this.temperatureService) {
419
+ this.temperatureService.setCharacteristic(Characteristic.StatusActive, temperature !== undefined);
420
+ this.temperatureService.setCharacteristic(Characteristic.StatusFault, temperature === undefined);
421
+ if (temperature !== undefined) {
422
+ this.temperatureService.updateCharacteristic(Characteristic.CurrentTemperature, temperature);
458
423
  }
424
+ }
459
425
 
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);
426
+ if (this.sensors.apparentTemp && this.apparentTempService) {
427
+ this.apparentTempService.setCharacteristic(Characteristic.StatusActive, apparentTemp !== undefined);
428
+ this.apparentTempService.setCharacteristic(Characteristic.StatusFault, apparentTemp === undefined);
429
+ if (apparentTemp !== undefined) {
430
+ this.apparentTempService.updateCharacteristic(Characteristic.CurrentTemperature, apparentTemp);
465
431
  }
432
+ }
466
433
 
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);
434
+ if (this.sensors.humidity && this.humidityService) {
435
+ this.humidityService.setCharacteristic(Characteristic.StatusActive, humidity !== undefined);
436
+ this.humidityService.setCharacteristic(Characteristic.StatusFault, humidity === undefined);
437
+ if (humidity !== undefined) {
438
+ this.humidityService.updateCharacteristic(Characteristic.CurrentRelativeHumidity, humidity);
472
439
  }
440
+ }
473
441
 
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");
442
+ if (this.sensors.pressure && this.airPressureService) {
443
+ this.airPressureService.setCharacteristic(Characteristic.StatusActive, pressure !== undefined);
444
+ this.airPressureService.setCharacteristic(Characteristic.StatusFault, pressure === undefined);
445
+ if (pressure !== undefined) {
446
+ this.airPressureService.updateCharacteristic(this.AirPressureCharacteristic, pressure);
483
447
  }
448
+ }
484
449
 
485
- } catch (error) {
486
- this.log.error("[BOM gov au] Failed to fetch BOM data:", error.message);
450
+ if (this.history) {
451
+ this.history.addEntry({
452
+ time: Math.floor(fetchedAt / 1000),
453
+ temp: temperature ?? 0,
454
+ humidity: humidity ?? 0,
455
+ pressure: pressure ?? 0
456
+ });
457
+ this.log("[BOM gov au] Added FakeGato history entry");
458
+ }
459
+ } catch (error) {
460
+ this.log.error("[BOM gov au] Failed to fetch BOM data:", error.message);
487
461
 
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;
462
+ if (this.sensors.temperature && this.temperatureService) {
463
+ this.temperatureService.setCharacteristic(Characteristic.StatusActive, false);
464
+ this.temperatureService.setCharacteristic(Characteristic.StatusFault, true);
465
+ }
466
+ if (this.sensors.apparentTemp && this.apparentTempService) {
467
+ this.apparentTempService.setCharacteristic(Characteristic.StatusActive, false);
468
+ this.apparentTempService.setCharacteristic(Characteristic.StatusFault, true);
469
+ }
470
+ if (this.sensors.humidity && this.humidityService) {
471
+ this.humidityService.setCharacteristic(Characteristic.StatusActive, false);
472
+ this.humidityService.setCharacteristic(Characteristic.StatusFault, true);
473
+ }
474
+ if (this.sensors.pressure && this.airPressureService) {
475
+ this.airPressureService.setCharacteristic(Characteristic.StatusActive, false);
476
+ this.airPressureService.setCharacteristic(Characteristic.StatusFault, true);
499
477
  }
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
478
  }
504
479
  }
505
480
 
506
481
  /**
507
- * Gets current temperature state.
508
- *
509
- * @async
510
- * @returns {Promise<number>} Temperature in Celsius, 0 if unavailable
482
+ * Gets the current air temperature.
483
+ *
484
+ * Returns the last valid characteristic value while the sensor is offline.
485
+ *
486
+ * @returns {Promise<number>} Temperature in Celsius
511
487
  */
512
488
  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
519
- }
489
+ await this.updateObservations();
490
+ return this._getObservationValue("air_temp", -100, 100) ??
491
+ this._getCharacteristicFallback(
492
+ this.temperatureService,
493
+ this.hap.Characteristic.CurrentTemperature,
494
+ -100,
495
+ 100,
496
+ 0
497
+ );
520
498
  }
521
499
 
522
500
  /**
523
- * Gets current atmospheric pressure state.
524
- *
525
- * @async
526
- * @returns {Promise<number>} Pressure in hPa, 0 if unavailable
501
+ * Gets the current air pressure.
502
+ *
503
+ * Returns the last valid characteristic value while the sensor is offline.
504
+ *
505
+ * @returns {Promise<number>} Pressure in hPa
527
506
  */
528
507
  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
535
- }
508
+ await this.updateObservations();
509
+ return this._getObservationValue("press", 700, 1100) ??
510
+ this._getCharacteristicFallback(
511
+ this.airPressureService,
512
+ this.AirPressureCharacteristic,
513
+ 700,
514
+ 1100,
515
+ 1013
516
+ );
536
517
  }
537
518
 
538
519
  /**
539
- * Gets current apparent temperature state.
540
- *
541
- * @async
542
- * @returns {Promise<number>} Apparent temperature in Celsius, 0 if unavailable
520
+ * Gets the current apparent temperature.
521
+ *
522
+ * Returns the last valid characteristic value while the sensor is offline.
523
+ *
524
+ * @returns {Promise<number>} Apparent temperature in Celsius
543
525
  */
544
526
  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
551
- }
527
+ await this.updateObservations();
528
+ return this._getObservationValue("apparent_t", -100, 100) ??
529
+ this._getCharacteristicFallback(
530
+ this.apparentTempService,
531
+ this.hap.Characteristic.CurrentTemperature,
532
+ -100,
533
+ 100,
534
+ 0
535
+ );
552
536
  }
553
537
 
554
538
  /**
555
- * Gets current humidity state.
556
- *
557
- * @async
558
- * @returns {Promise<number>} Relative humidity percentage, 0 if unavailable
539
+ * Gets the current relative humidity.
540
+ *
541
+ * Returns the last valid characteristic value while the sensor is offline.
542
+ *
543
+ * @returns {Promise<number>} Relative humidity percentage
559
544
  */
560
545
  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
567
- }
546
+ await this.updateObservations();
547
+ return this._getObservationValue("rel_hum", 0, 100) ??
548
+ this._getCharacteristicFallback(
549
+ this.humidityService,
550
+ this.hap.Characteristic.CurrentRelativeHumidity,
551
+ 0,
552
+ 100,
553
+ 0
554
+ );
568
555
  }
569
556
  }
570
557
 
571
558
  /**
572
559
  * Homebridge plugin entry point.
573
- *
574
- * Registers the BOMgovau accessory with Homebridge.
575
- *
560
+ *
576
561
  * @param {HomebridgeAPI} api - Homebridge API instance
577
562
  */
578
- module.exports = (api) => {
563
+ module.exports = api => {
579
564
  api.registerAccessory(PLUGIN_NAME, "BOMgovau", BOMgovauAccessory);
580
565
  };