Skip to content
Open
Show file tree
Hide file tree
Changes from 2 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
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@ The main work (all changes without a GitHub username in brackets in the below li
- Fix: `ModeSelectServer` rejects a write of a `startUpMode` or `onMode` outside `supportedModes` with CONSTRAINT_ERROR, and an application write of such a `currentMode` with `UnsupportedModeError`
- Fix: Mode Select and the Mode Base derived servers replace a mode outside `supportedModes`, for example one stored before a firmware update, with a warning at startup instead of failing the node start
- Fix: A group invoke leaves the request object passed in unchanged
- Fix: `ColorControlServer` defaults `colorLoopDirection` to Decrement instead of Increment
- Fix: `ColorControlServer` starts MoveHue, EnhancedMoveHue and the color loop when the hue is at its minimum moving down or at its maximum moving up
- Fix: `ColorControlServer` continues a hue transition from the highest hue to the lowest and back without skipping a value

- @matter/protocol
- Feature: `Invoke()` and `Write()` accept `omitFalseFlags` to leave a false SuppressResponse and TimedRequest out of the request; use it only when all target nodes support Interaction Model revision 14 or later
Expand All @@ -31,6 +34,7 @@ The main work (all changes without a GitHub username in brackets in the below li
- Fix: The controller examples log only the discovery options when commissioning, not the passcode or network credentials

- @matter/general
- Fix: `addValueWithOverflow` includes both `min` and `max` in the range, so one above `max` is `min`
- Feature: `Logger.logPayloads`, also set by the `log.payloads` variable, leaves decrypted message payloads out of message logs when set to false
- Feature: `Logger.redactSecrets`, also set by the `log.redactSecrets` variable, turns off the replacement of secret values in log output when set to false
- Feature: `Network.interfacesChanged` reports interface and address changes, checked every 60 seconds while observed
Expand Down
12 changes: 4 additions & 8 deletions packages/general/src/util/Number.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,14 +56,10 @@ export function cropValueRange(value: number, min: number, max: number): number
}

/**
* Adds a value to another value and wraps around on the min and max values.
* Adds a value to another value in the cyclic range `min` to `max`, both included: one above `max` is `min` and one
* below `min` is `max`. A fractional result lies in the range `min` up to, but excluding, `max + 1`.
*/
export function addValueWithOverflow(value: number, add: number, min: number, max: number): number {
const newValue = value + add;
if (newValue < min) {
return newValue - min + max;
} else if (newValue > max) {
return newValue - max + min;
}
return newValue;
const span = max - min + 1;
return ((((value + add - min) % span) + span) % span) + min;
}
20 changes: 18 additions & 2 deletions packages/general/test/util/NumberTest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,11 +52,27 @@ describe("Number utilities", () => {

describe("addValueWithOverflow", () => {
it("wraps past the maximum", () => {
expect(addValueWithOverflow(8, 5, 0, 10)).equal(3);
expect(addValueWithOverflow(8, 5, 0, 10)).equal(2);
});

it("wraps below the minimum", () => {
expect(addValueWithOverflow(2, -5, 0, 10)).equal(7);
expect(addValueWithOverflow(2, -5, 0, 10)).equal(8);
});

it("continues from the minimum one above the maximum", () => {
expect(addValueWithOverflow(254, 1, 0, 254)).equal(0);
});

it("continues from the maximum one below the minimum", () => {
expect(addValueWithOverflow(0, -1, 0, 254)).equal(254);
});

it("wraps a range that does not start at zero", () => {
expect(addValueWithOverflow(9, 3, 5, 10)).equal(6);
});

it("wraps more than one full range", () => {
expect(addValueWithOverflow(3, -24, 0, 10)).equal(1);
});

it("stays in range without wrapping", () => {
Expand Down
27 changes: 13 additions & 14 deletions packages/node/src/behavior/Transitions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,8 @@ export class Transitions<B extends Behavior> {

/**
* Calculate the distance between two values in a cyclic range. This is the default implementation only caring
* about normal upwards and downwards transitions.
* about normal upwards and downwards transitions. The range includes `min` and `max`, and the value after `max` is
* `min`.
*/
protected calculateCyclicDistance(
currentValue: number,
Expand All @@ -102,16 +103,8 @@ export class Transitions<B extends Behavior> {
min: number,
max: number,
): number {
if (changePerS > 0) {
// We want to transition upwards to target value or to max and then from min to target value
if (currentValue > targetValue) {
return Math.abs(currentValue - max) + Math.abs(max - targetValue);
}
} else if (currentValue < targetValue) {
// We want to transition downwards to target value or to min and then from max to target value
return Math.abs(currentValue - min) + Math.abs(min - targetValue);
}
return Math.abs(currentValue - targetValue);
const change = changePerS > 0 ? targetValue - currentValue : currentValue - targetValue;
return addValueWithOverflow(change, 0, 0, max - min);
}

/**
Expand Down Expand Up @@ -162,7 +155,7 @@ export class Transitions<B extends Behavior> {
if (distanceLeft === 0) {
return;
}
} else if (min !== undefined && max !== undefined) {
} else if (!cyclic && min !== undefined && max !== undefined) {
if ((changePerS < 0 && currentValue === min) || (changePerS > 0 && currentValue === max)) {
return;
}
Expand Down Expand Up @@ -541,7 +534,11 @@ export class Transitions<B extends Behavior> {
for (const prop of this) {
const { name, currentValue } = prop;

const nextValue = Math.round(currentValue);
const { cyclic, min, max } = this.#config.properties[name] ?? {};
const nextValue =
cyclic && min !== undefined && max !== undefined
? addValueWithOverflow(Math.round(currentValue), 0, min, max)
Comment thread
Apollon77 marked this conversation as resolved.
Resolved
: Math.round(currentValue);
if (state[name] !== nextValue && (nextValue === null || typeof nextValue === "number")) {
//logger.debug(this.#logPrefix, "Stepping", Diagnostic.strong(name), "to", nextValue);
changes[name] = nextValue as unknown as Transitions.StateOf<B>[Transitions.PropertyOf<B>];
Expand Down Expand Up @@ -776,7 +773,7 @@ export namespace Transitions {
readonly max?: number | undefined;

/**
* Is the property transitioning ina cyclic manner? means it overflows to the min value when it reaches the max
* Whether the property is cyclic: the value after `max` is `min`, and the value before `min` is `max`.
*/
cyclic?: boolean;
}
Expand Down Expand Up @@ -832,6 +829,8 @@ export namespace Transitions {

/**
* Invoked every time the transitioning value changes before committing the mutating transaction.
*
* The value may be fractional. For a cyclic property it lies in the range `min` up to, but excluding, `max + 1`.
*/
onStep?: (this: B, value: number) => MaybePromise<void>;
}
Expand Down
24 changes: 8 additions & 16 deletions packages/node/src/behaviors/color-control/ColorControlServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -441,8 +441,6 @@ export class ColorControlBaseServer extends ColorControlBase {
owner: this,
changePerS: effectiveRate,
targetValue: targetHue,
calculateCyclicDistance: (current, target) =>
this.#getHueDistanceByDirection(current, target, direction, maxHue),
});
}

Expand Down Expand Up @@ -565,13 +563,6 @@ export class ColorControlBaseServer extends ColorControlBase {
owner: this,
changePerS: effectiveRate,
targetValue,
calculateCyclicDistance: (current, target) =>
this.#getHueDistanceByDirection(
current,
target,
stepMode === ColorControl.StepMode.Up ? ColorControl.Direction.Up : ColorControl.Direction.Down,
maxHue,
),
});
}

Expand Down Expand Up @@ -1610,26 +1601,27 @@ export class ColorControlBaseServer extends ColorControlBase {

/** Calculate the hue distance depending on the direction and the current and target hue. */
#getHueDistanceByDirection(currentHue: number, targetHue: number, direction: ColorControl.Direction, max: number) {
const distance = (targetHue > currentHue ? targetHue : max + targetHue + 1) - currentHue;
const span = max - MIN_HUE_VALUE + 1;
const distance = addValueWithOverflow(targetHue - currentHue, 0, 0, max - MIN_HUE_VALUE);
if (distance === 0) {
return 0;
}
if (direction === ColorControl.Direction.Up) {
return distance;
} else if (direction === ColorControl.Direction.Down) {
return -(max - distance);
return -(span - distance);
}
if (direction === ColorControl.Direction.Shortest) {
if (Math.abs(distance) > max / 2) {
return -(max - distance);
if (distance > span / 2) {
return -(span - distance);
}
return distance;
}
if (direction === ColorControl.Direction.Longest) {
if (Math.abs(distance) > max / 2) {
if (distance > span / 2) {
return distance;
}
return -(max - distance);
return -(span - distance);
}
throw new ImplementationError(`Unknown direction: ${direction}`);
}
Expand Down Expand Up @@ -1962,7 +1954,7 @@ export namespace ColorControlBaseServer {
override colorLoopTime = 25;
override colorLoopStartEnhancedHue = 8960;
override colorLoopActive = ColorControl.ColorLoopActive.Inactive;
override colorLoopDirection = ColorControl.ColorLoopDirection.Increment;
override colorLoopDirection = ColorControl.ColorLoopDirection.Decrement;

[Val.properties](endpoint: Endpoint) {
// An undefined value means the endpoint does not support the attribute
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ const SERVER_ONLY_DEFAULTS: Record<string, unknown[]> = {
"AdministratorCommissioningServer.windowStatus": [0],
"BasicInformationServer.maxPathsPerInvoke": [0],
"ColorControlServer.colorLoopActive": [0],
"ColorControlServer.colorLoopDirection": [1],
"ColorControlServer.colorLoopDirection": [0],
"ColorControlServer.enhancedColorMode": [1],
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,12 @@ const ColorLightDeviceWithoutColorLoop = ExtendedColorLightDevice.with(
);

describe("ColorControlServer", () => {
it("defaults colorLoopDirection to Decrement", () => {
expect(ColorControlServer.with("HueSaturation", "EnhancedHue", "ColorLoop").defaults.colorLoopDirection).equals(
ColorControl.ColorLoopDirection.Decrement,
);
});

it("transitions cyclic hue downwards with correct events", async () => {
const { node, endpoint, events, complete } = await setup();

Expand Down Expand Up @@ -47,7 +53,7 @@ describe("ColorControlServer", () => {

await node.close();

// 253 in 6s aka 42/s
// 254 in 6s aka 42/s
expect(events).deep.equals([
// Startup
{ kind: "hue", value: 128, ms: 0 },
Expand All @@ -57,16 +63,92 @@ describe("ColorControlServer", () => {

// Transitioning
{ kind: "hue", value: 86, ms: 1000 },
{ kind: "hue", value: 44, ms: 1000 },
{ kind: "hue", value: 43, ms: 1000 },
{ kind: "hue", value: 1, ms: 1000 },
{ kind: "hue", value: 213, ms: 1000 },
{ kind: "hue", value: 214, ms: 1000 },
{ kind: "hue", value: 171, ms: 1000 },

// Transition complete
{ kind: "hue", value: 129, ms: 920 },
{ kind: "time", value: 0, ms: 0 },
]);
});

async function hueValuesOfMoveToHue(
currentHue: number,
hue: number,
direction: ColorControl.Direction,
transitionTime: number,
) {
const { node, endpoint, events, complete } = await setup();

await endpoint.set({ colorControl: { currentHue } });

await node.online({ command: true }, async agent => {
const endpointAgent = endpoint.agentFor(agent.context);
await agent.context.transaction.addResources(endpointAgent.colorControl);
await endpointAgent.colorControl.moveToHue({
hue,
direction,
transitionTime,
optionsMask: {},
optionsOverride: {},
});
});

await MockTime.resolve(complete, { stepMs: 10 });
await node.close();

return events.filter(({ kind }) => kind === "hue").map(({ value, ms }) => [value, ms]);
}

it("takes the shortest way across the hue minimum", async () => {
expect(await hueValuesOfMoveToHue(1, 253, ColorControl.Direction.Shortest, 30)).deep.equals([
[1, 0],
[0, 1000],
[254, 1000],
[253, 400],
]);
});

it("takes the longest way across the hue minimum", async () => {
expect(await hueValuesOfMoveToHue(128, 129, ColorControl.Direction.Longest, 60)).deep.equals([
[128, 0],
[86, 1000],
[43, 1000],
[1, 1000],
[214, 1000],
[171, 1000],
[129, 920],
]);
});
});

describe("ColorControl hue move", () => {
before(MockTime.enable);

async function hueAfterMove(currentHue: number, moveMode: ColorControl.MoveMode) {
const { node, endpoint, invoke } = await setup();

await endpoint.set({ colorControl: { currentHue } });

await invoke(agent => agent.colorControl.moveHue({ moveMode, rate: 10, optionsMask: {}, optionsOverride: {} }));

await MockTime.advance(Millis(1000));
await MockTime.yield();

const hue = endpoint.state.colorControl.currentHue;
await node.close();
return hue;
}

it("moves hue downwards past the minimum", async () => {
expect(await hueAfterMove(0, ColorControl.MoveMode.Down)).greaterThan(200);
});

it("moves hue upwards past the maximum", async () => {
expect(await hueAfterMove(254, ColorControl.MoveMode.Up)).lessThan(50);
});
});

describe("ColorControl primaries", () => {
Expand Down
Loading