Skip to content
Open
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
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ 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
- Fix: A transition that matter.js runs with its own timer takes the requested transition time and reports its end after the final value, instead of ending one step early or as soon as the rounded value equals the target

- @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 +35,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
85 changes: 60 additions & 25 deletions packages/node/src/behavior/Transitions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,8 @@ const logger = Logger.get("Transition");
* 4. You can also allow matter.js to operate a transition timer but apply value updates directly to hardware by
* overriding {@link applyUpdates} (and use `determineUpdates()` if needed) or {@link step}. This is useful if your
* device does not support transitions natively, but you want to ensure that matter.js does not report values that
* do not reflect hardware state.
* do not reflect hardware state. An override of {@link step} that does not call the default implementation ends
* a transition when the state reaches the target value, or when you invoke {@link finish}.
*
* Whichever approach you take, matter.js attempts to implement the Matter protocol as accurately as possible with the
* information available.
Expand All @@ -69,6 +70,8 @@ export class Transitions<B extends Behavior> {
#staticRemainingTime = 0;
#prevPublishedRemainingTime = 0;
#propertyStates = {} as Record<string, Transitions.PropertyState<B>>;
#publishedValues = new Map<string, number>();
#reachedTargets = new Array<Transitions.PropertyState<B>>();
#observers?: ObserverGroup;
#instrumentedProperties?: Set<string>;

Expand All @@ -93,7 +96,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 +106,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 +158,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 All @@ -175,7 +171,7 @@ export class Transitions<B extends Behavior> {
configuration: transition,
currentValue,
changePerMs: changePerS / 1000,
prevStepAt: Timestamp(Time.nowMs - (this.#config.stepInterval ?? Transitions.DEFAULT_STEP_INTERVAL)),
prevStepAt: Time.nowMs,
distanceLeft,
};

Expand Down Expand Up @@ -263,12 +259,14 @@ export class Transitions<B extends Behavior> {
stop(name?: Transitions.PropertyOf<B>) {
if (name === undefined) {
this.#propertyStates = {} as Record<any, any>;
this.#publishedValues.clear();
} else {
if (!(name in this.#propertyStates)) {
return;
}

delete this.#propertyStates[name];
this.#publishedValues.delete(name);

if (Object.keys(this.#propertyStates).length) {
// Other transitions are ongoing
Expand Down Expand Up @@ -480,13 +478,17 @@ export class Transitions<B extends Behavior> {

const { targetValue, targetDescription } = this.#determineTargetValue(prop);

// Steps add up rounding errors, so less than half a millisecond of change left counts as the target
const reachTolerance = Math.abs(changePerMs) / 2;
let reached = false;

if (cyclic) {
let distanceLeft = this.#determineDistanceLeft(prop);
if (distanceLeft !== undefined && targetValue !== undefined) {
distanceLeft -= Math.abs(changeSinceLastStep);
if (distanceLeft <= 0) {
// We reached the target value
if (distanceLeft <= reachTolerance) {
nextValue = targetValue;
reached = true;
prop.distanceLeft = 0;
} else {
prop.distanceLeft = distanceLeft;
Expand All @@ -495,12 +497,14 @@ export class Transitions<B extends Behavior> {
} else {
// Clamp nextValue to valid range
if (prop.changePerMs < 0) {
if (targetValue !== undefined && nextValue < targetValue) {
if (targetValue !== undefined && nextValue <= targetValue + reachTolerance) {
nextValue = targetValue;
reached = true;
}
} else if (prop.changePerMs > 0) {
if (targetValue !== undefined && nextValue > targetValue) {
if (targetValue !== undefined && nextValue >= targetValue - reachTolerance) {
nextValue = targetValue;
reached = true;
}
} else {
// This shouldn't happen
Expand All @@ -517,6 +521,9 @@ export class Transitions<B extends Behavior> {
}

prop.currentValue = nextValue;
if (reached) {
this.#reachedTargets.push(prop);
}

// Invoke step callback, if any
const callbackPromise = prop.configuration.onStep?.call(behavior, nextValue);
Expand All @@ -527,7 +534,14 @@ export class Transitions<B extends Behavior> {
prop.prevStepAt = now;
}

const applyPromise = this.applyUpdates(behavior, this.determineUpdates(behavior));
const updates = this.determineUpdates(behavior);
for (const [name, value] of Object.entries(updates)) {
if (typeof value === "number") {
this.#publishedValues.set(name, value);
}
}

const applyPromise = this.applyUpdates(behavior, updates);
if (MaybePromise.is(applyPromise)) {
await applyPromise;
}
Expand All @@ -541,7 +555,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 @@ -589,14 +607,27 @@ export class Transitions<B extends Behavior> {
await this.step(behavior);
};

// A transition ends once its last value is committed, so the end is never reported before that value
const finishReachedTargets = () => {
const reached = this.#reachedTargets;
this.#reachedTargets = [];
for (const state of reached) {
if (this.#propertyStates[state.name] === state) {
this.finish(state.name);
}
Comment on lines +615 to +617
}
};

// Create a behavior to perform actual stepping
const promise = (this.#outstandingTick = Promise.resolve(this.#endpoint.act("transition", executeStep))
.then(finishReachedTargets)
.catch(error => {
logger.error(
this.#logPrefix,
"Aborting transition due to unhandled error during step management:",
error,
);
this.#reachedTargets = [];
this.stop();
})
.finally(() => {
Expand Down Expand Up @@ -651,10 +682,11 @@ export class Transitions<B extends Behavior> {
}

/**
* We add event handlers for any property we transition. If the property reaches the target value we end the
* transition.
* We add event handlers for any property we transition. If the property reaches the target value through a value
* the timer did not publish, we end the transition.
*
* This allows us to detect "end of transition" independent of the means of transition.
* This detects the end of a transition that hardware or another writer performs. The timer step ends the
* transitions it performs itself once their final value is committed.
*/
#instrumentProperty(name: Transitions.PropertyOf<B>) {
if (this.#instrumentedProperties === undefined) {
Expand Down Expand Up @@ -686,7 +718,8 @@ export class Transitions<B extends Behavior> {

const { targetValue } = this.#determineTargetValue(state);

if (newValue === targetValue) {
// A value the timer published is rounded, so only the timer step ends its own transition
if (newValue === targetValue && newValue !== this.#publishedValues.get(name)) {
return this.finish(name);
}
});
Expand Down Expand Up @@ -776,7 +809,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 +865,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
Loading
Loading