From 63bc58973cb0e8351b9bba73c9ed138d77ce6eef Mon Sep 17 00:00:00 2001 From: Andi Date: Mon, 19 Sep 2022 20:12:23 +0900 Subject: [PATCH] Fixed a regression where floats were rounded incorrectly when no minValue was provided (fixes #971) (#972) --- src/lib/Characteristic.spec.ts | 16 ++++++++++++++++ src/lib/Characteristic.ts | 10 +++++----- 2 files changed, 21 insertions(+), 5 deletions(-) diff --git a/src/lib/Characteristic.spec.ts b/src/lib/Characteristic.spec.ts index e8888dc8e..ee8a55f8f 100644 --- a/src/lib/Characteristic.spec.ts +++ b/src/lib/Characteristic.spec.ts @@ -1063,6 +1063,22 @@ describe("Characteristic", () => { expect(characteristic.value).toEqual(0.1); }); + it("should accept Formats.FLOAT with non-defined min/max value", () => { + const characteristic = createCharacteristicWithProps({ + format: Formats.FLOAT, + minStep: 0.01, + perms: [Perms.PAIRED_READ, Perms.NOTIFY], + }, uuid.generate("051")); + + // @ts-expect-error - spying on private property + const mock = jest.spyOn(characteristic, "characteristicWarning"); + + mock.mockReset(); + characteristic.updateValue(0.09); + expect(characteristic.value).toEqual(0.09); + expect(mock).toBeCalledTimes(0); + }); + it("should validate Formats.FLOAT with precision", () => { const characteristic = new Characteristic.CurrentAmbientLightLevel(); diff --git a/src/lib/Characteristic.ts b/src/lib/Characteristic.ts index c3890e643..dbc9fec71 100644 --- a/src/lib/Characteristic.ts +++ b/src/lib/Characteristic.ts @@ -602,9 +602,9 @@ function extractHAPStatusFromError(error: Error) { } function maxWithUndefined(a?: number, b?: number): number | undefined { - if (a === undefined) { + if (a == null) { return b; - } else if (b === undefined) { + } else if (b == null) { return a; } else { return Math.max(a, b); @@ -612,9 +612,9 @@ function maxWithUndefined(a?: number, b?: number): number | undefined { } function minWithUndefined(a?: number, b?: number): number | undefined { - if (a === undefined) { + if (a == null) { return b; - } else if (b === undefined) { + } else if (b == null) { return a; } else { return Math.min(a, b); @@ -2042,7 +2042,7 @@ export class Characteristic extends EventEmitter { } if (stepValue != null && stepValue > 0) { - const minValue = numericMin != null ? numericMin : 0; + const minValue = this.props.minValue != null ? this.props.minValue : 0; value = stepValue * Math.round((value - minValue) / stepValue) + minValue; }