Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix floating point validation on Characteristic Set #956

Merged
merged 2 commits into from
May 29, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions src/lib/Characteristic.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1094,6 +1094,35 @@ describe("Characteristic", () => {
expect(mock).toBeCalledTimes(0);
});

it("should validate Formats.FLOAT with precision with minimum steps", () => {
const steps = (100 / 6);
const characteristic = createCharacteristicWithProps({
format: Formats.FLOAT,
perms: [Perms.PAIRED_READ, Perms.PAIRED_WRITE],
minValue: 0,
maxValue: 100,
minStep: steps,
});

characteristic.setValue(steps);
expect(characteristic.value).toEqual(steps);

characteristic.setValue(steps * 2);
expect(characteristic.value).toEqual(steps * 2);

characteristic.setValue(steps * 3);
expect(characteristic.value).toEqual(steps * 3);

characteristic.setValue(steps * 4);
expect(characteristic.value).toEqual(steps * 4);

characteristic.setValue(steps * 5);
expect(characteristic.value).toEqual(steps * 5);

characteristic.setValue(steps * 6);
expect(characteristic.value).toEqual(steps * 6);
});

it("should allow negative floats in range for Formats.FLOAT", () => {
const characteristic = createCharacteristicWithProps({
format: Formats.FLOAT,
Expand Down
3 changes: 2 additions & 1 deletion src/lib/Characteristic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2071,8 +2071,9 @@ export class Characteristic extends EventEmitter {
if (stepValue === 1) {
value = Math.round(value);
} else if (stepValue > 1) {
const eps = 1; // stable constant for floating point precision
value = Math.round(value);
value = value - (value % stepValue);
value = value - ((value + eps) % stepValue) + eps;
} // for stepValue < 1 rounding is done only when formatting the response. We can't store the "perfect" .step anyways
}

Expand Down