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: Use BuffaloZdo in ZStackAdapter #1133

Merged
merged 26 commits into from
Sep 14, 2024
Merged
Show file tree
Hide file tree
Changes from 4 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
114 changes: 58 additions & 56 deletions src/adapter/z-stack/adapter/zStackAdapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@
import {logger} from '../../../utils/logger';
import {BroadcastAddress} from '../../../zspec/enums';
import * as Zcl from '../../../zspec/zcl';
import {Status as ZdoStatus} from '../../../zspec/zdo';

Check failure on line 9 in src/adapter/z-stack/adapter/zStackAdapter.ts

View workflow job for this annotation

GitHub Actions / ci

'ZdoStatus' is defined but never used
import {BuffaloZdo} from '../../../zspec/zdo/buffaloZdo';
import {SimpleDescriptorResponse, ActiveEndpointsResponse} from '../../../zspec/zdo/definition/tstypes';
import Adapter from '../../adapter';
import * as Events from '../../events';
import {
Expand All @@ -28,6 +31,7 @@
import * as Constants from '../constants';
import {Constants as UnpiConstants} from '../unpi';
import {Znp, ZpiObject} from '../znp';
import {MtCmdZdo, ZpiObjectPayload} from '../znp/tstype';
import {ZnpAdapterManager} from './manager';
import {ZnpVersion} from './tstype';

Expand Down Expand Up @@ -174,26 +178,24 @@
public async getCoordinator(): Promise<Coordinator> {
return this.queue.execute<Coordinator>(async () => {
this.checkInterpanLock();
const activeEpRsp = this.znp.waitFor(UnpiConstants.Type.AREQ, Subsystem.ZDO, 'activeEpRsp');
const activeEpRsp = this.waitForAreqZdo<ActiveEndpointsResponse>('activeEpRsp');
await this.znp.request(Subsystem.ZDO, 'activeEpReq', {dstaddr: 0, nwkaddrofinterest: 0}, activeEpRsp.ID);
const activeEp = await activeEpRsp.start().promise;
const activeEp = await activeEpRsp.start();

const deviceInfo = await this.znp.request(Subsystem.UTIL, 'getDeviceInfo', {});

const endpoints = [];
for (const endpoint of activeEp.payload.activeeplist) {
const simpleDescRsp = this.znp.waitFor(UnpiConstants.Type.AREQ, Subsystem.ZDO, 'simpleDescRsp', {endpoint});

for (const endpoint of activeEp.endpointList) {
const simpleDescRsp = this.waitForAreqZdo<SimpleDescriptorResponse>('simpleDescRsp', {endpoint});
await this.znp.request(Subsystem.ZDO, 'simpleDescReq', {dstaddr: 0, nwkaddrofinterest: 0, endpoint}, simpleDescRsp.ID);

const simpleDesc = await simpleDescRsp.start().promise;
const simpleDesc = await simpleDescRsp.start();

endpoints.push({
ID: simpleDesc.payload.endpoint,
profileID: simpleDesc.payload.profileid,
deviceID: simpleDesc.payload.deviceid,
inputClusters: simpleDesc.payload.inclusterlist,
outputClusters: simpleDesc.payload.outclusterlist,
ID: simpleDesc.endpoint,
profileID: simpleDesc.profileId,
deviceID: simpleDesc.deviceId,
inputClusters: simpleDesc.inClusterList,
outputClusters: simpleDesc.outClusterList,
});
}

Expand Down Expand Up @@ -267,9 +269,9 @@
* this is currently not handled, the first nwkAddrRsp is taken.
*/
logger.debug(`Request network address of '${ieeeAddr}'`, NS);
const response = this.znp.waitFor(UnpiConstants.Type.AREQ, Subsystem.ZDO, 'nwkAddrRsp', {ieeeaddr: ieeeAddr});
const response = this.waitForAreqZdo('nwkAddrRsp', {ieeeaddr: ieeeAddr});
await this.znp.request(Subsystem.ZDO, 'nwkAddrReq', {ieeeaddr: ieeeAddr, reqtype: 0, startindex: 0});
const result = await response.start().promise;
const result = await response.start();
return result.payload.nwkaddr;
}

Expand Down Expand Up @@ -309,10 +311,10 @@
}

private async nodeDescriptorInternal(networkAddress: number): Promise<NodeDescriptor> {
const response = this.znp.waitFor(Type.AREQ, Subsystem.ZDO, 'nodeDescRsp', {nwkaddr: networkAddress});
const response = this.waitForAreqZdo('nodeDescRsp', {nwkaddr: networkAddress});
const payload = {dstaddr: networkAddress, nwkaddrofinterest: networkAddress};
await this.znp.request(Subsystem.ZDO, 'nodeDescReq', payload, response.ID);
const descriptor = await response.start().promise;
const descriptor = await response.start();

let type: DeviceType = 'Unknown';
const logicalType = descriptor.payload.logicaltype_cmplxdescavai_userdescavai & 0x07;
Expand All @@ -331,10 +333,10 @@
public async activeEndpoints(networkAddress: number): Promise<ActiveEndpoints> {
return this.queue.execute<ActiveEndpoints>(async () => {
this.checkInterpanLock();
const response = this.znp.waitFor(Type.AREQ, Subsystem.ZDO, 'activeEpRsp', {nwkaddr: networkAddress});
const response = this.waitForAreqZdo('activeEpRsp', {nwkaddr: networkAddress});
const payload = {dstaddr: networkAddress, nwkaddrofinterest: networkAddress};
await this.znp.request(Subsystem.ZDO, 'activeEpReq', payload, response.ID);
const activeEp = await response.start().promise;
const activeEp = await response.start();
return {endpoints: activeEp.payload.activeeplist};
}, networkAddress);
}
Expand All @@ -343,10 +345,10 @@
return this.queue.execute<SimpleDescriptor>(async () => {
this.checkInterpanLock();
const responsePayload = {nwkaddr: networkAddress, endpoint: endpointID};
const response = this.znp.waitFor(Type.AREQ, Subsystem.ZDO, 'simpleDescRsp', responsePayload);
const response = this.waitForAreqZdo('simpleDescRsp', responsePayload);
const payload = {dstaddr: networkAddress, nwkaddrofinterest: networkAddress, endpoint: endpointID};
await this.znp.request(Subsystem.ZDO, 'simpleDescReq', payload, response.ID);
const descriptor = await response.start().promise;
const descriptor = await response.start();
return {
profileID: descriptor.payload.profileid,
endpointID: descriptor.payload.endpoint,
Expand Down Expand Up @@ -694,15 +696,9 @@

// eslint-disable-next-line @typescript-eslint/no-explicit-any
const request = async (startIndex: number): Promise<any> => {
const response = this.znp.waitFor(Type.AREQ, Subsystem.ZDO, 'mgmtLqiRsp', {srcaddr: networkAddress});
const response = this.waitForAreqZdo('mgmtLqiRsp', {srcaddr: networkAddress});
await this.znp.request(Subsystem.ZDO, 'mgmtLqiReq', {dstaddr: networkAddress, startindex: startIndex}, response.ID);
const result = await response.start().promise;
if (result.payload.status !== ZnpCommandStatus.SUCCESS) {
throw new Error(
`LQI for '${networkAddress}' failed with error: '${ZnpCommandStatus[result.payload.status]}' (${result.payload.status})`,
);
}

const result = await response.start();
return result;
};

Expand Down Expand Up @@ -741,17 +737,9 @@

// eslint-disable-next-line @typescript-eslint/no-explicit-any
const request = async (startIndex: number): Promise<any> => {
const response = this.znp.waitFor(Type.AREQ, Subsystem.ZDO, 'mgmtRtgRsp', {srcaddr: networkAddress});
const response = this.waitForAreqZdo('mgmtRtgRsp', {srcaddr: networkAddress});
await this.znp.request(Subsystem.ZDO, 'mgmtRtgReq', {dstaddr: networkAddress, startindex: startIndex}, response.ID);
const result = await response.start().promise;
if (result.payload.status !== ZnpCommandStatus.SUCCESS) {
throw new Error(
`Routing table for '${networkAddress}' failed with error: '${
ZnpCommandStatus[result.payload.status]
}' (${result.payload.status})`,
);
}

const result = await response.start();
return result;
};

Expand Down Expand Up @@ -841,7 +829,7 @@
): Promise<void> {
return this.queue.execute<void>(async () => {
this.checkInterpanLock();
const response = this.znp.waitFor(Type.AREQ, Subsystem.ZDO, `${bindType}Rsp`, {srcaddr: destinationNetworkAddress});
const response = this.waitForAreqZdo<void>(`${bindType}Rsp`, {srcaddr: destinationNetworkAddress});

const payload = {
dstaddr: destinationNetworkAddress,
Expand All @@ -854,21 +842,14 @@
};

await this.znp.request(Subsystem.ZDO, `${bindType}Req`, payload, response.ID);
const result = await response.start().promise;
if (result.payload.status !== 0) {
// Z-Stack only returns status 0 or 1, so not the actual error code
throw new Error(
`Failed to ${bindType} '${clusterID}' from '${destinationAddressOrGroup}/${destinationEndpoint}' ` +
`to '${sourceIeeeAddress}/${sourceEndpoint}' (${result.payload.status})`,
);
}
await response.start();
}, destinationNetworkAddress);
}

public removeDevice(networkAddress: number, ieeeAddr: string): Promise<void> {
return this.queue.execute<void>(async () => {
this.checkInterpanLock();
const response = this.znp.waitFor(UnpiConstants.Type.AREQ, Subsystem.ZDO, 'mgmtLeaveRsp', {srcaddr: networkAddress});
const response = this.waitForAreqZdo('mgmtLeaveRsp', {srcaddr: networkAddress});

const payload = {
dstaddr: networkAddress,
Expand All @@ -877,7 +858,7 @@
};

await this.znp.request(Subsystem.ZDO, 'mgmtLeaveReq', payload, response.ID);
await response.start().promise;
await response.start();
}, networkAddress);
}

Expand All @@ -891,19 +872,19 @@
}

public onZnpRecieved(object: ZpiObject): void {
if (object.type !== UnpiConstants.Type.AREQ) {
if (object.command.type !== UnpiConstants.Type.AREQ) {
return;
}

if (object.subsystem === Subsystem.ZDO) {
if (object.command === 'tcDeviceInd') {
if (object.command.name === 'tcDeviceInd') {
const payload: Events.DeviceJoinedPayload = {
networkAddress: object.payload.nwkaddr,
ieeeAddr: object.payload.extaddr,
};

this.emit(Events.Events.deviceJoined, payload);
} else if (object.command === 'endDeviceAnnceInd') {
} else if (object.command.name === 'endDeviceAnnceInd') {
const payload: Events.DeviceAnnouncePayload = {
networkAddress: object.payload.nwkaddr,
ieeeAddr: object.payload.ieeeaddr,
Expand Down Expand Up @@ -933,14 +914,14 @@
}

this.emit(Events.Events.deviceAnnounce, payload);
} else if (object.command === 'nwkAddrRsp') {
} else if (object.command.name === 'nwkAddrRsp') {
const payload: Events.NetworkAddressPayload = {
networkAddress: object.payload.nwkaddr,
ieeeAddr: object.payload.ieeeaddr,
};

this.emit(Events.Events.networkAddress, payload);
} else if (object.command === 'concentratorIndCb') {
} else if (object.command.name === 'concentratorIndCb') {
// Some routers may change short addresses and the announcement
// is missed by the coordinator. This can happen when there are
// power outages or other interruptions in service. They may
Expand All @@ -959,7 +940,7 @@
this.emit(Events.Events.networkAddress, payload);
} else {
/* istanbul ignore else */
if (object.command === 'leaveInd') {
if (object.command.name === 'leaveInd') {
if (object.payload.rejoin) {
logger.debug(`Device leave: Got leave indication with rejoin=true, nothing to do`, NS);
} else {
Expand All @@ -976,7 +957,7 @@
/* istanbul ignore else */
if (object.subsystem === Subsystem.AF) {
/* istanbul ignore else */
if (object.command === 'incomingMsg' || object.command === 'incomingMsgExt') {
if (object.command.name === 'incomingMsg' || object.command.name === 'incomingMsgExt') {
const payload: Events.ZclPayload = {
clusterID: object.payload.clusterid,
data: object.payload.data,
Expand Down Expand Up @@ -1117,6 +1098,27 @@
});
}

private waitForAreqZdo<T>(command: string, payload?: ZpiObjectPayload): {start: () => Promise<T>; ID: number} {
const result = this.znp.waitFor(UnpiConstants.Type.AREQ, Subsystem.ZDO, command, payload);
const start = (): Promise<T> => {
const startResult = result.start();
return new Promise<T>((resolve, reject) => {
startResult.promise
.then((response) => {
const cmd: MtCmdZdo = response.command;
try {
const zdoResponse = BuffaloZdo.readResponse(cmd.zdo.cluterId, response.unpiFrame.data.subarray(cmd.zdo.skip)) as T;
Koenkk marked this conversation as resolved.
Show resolved Hide resolved
resolve(zdoResponse);
} catch (error) {
reject(error);
}
})
.catch(reject);
});
};
return {start, ID: result.ID};
}

private waitForInternal(
networkAddress: number,
endpoint: number,
Expand Down
6 changes: 4 additions & 2 deletions src/adapter/z-stack/znp/definition.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import {ClusterId as ZdoClusterId} from '../../../zspec/zdo';
import {Subsystem, Type as CommandType} from '../unpi/constants';
import ParameterType from './parameterType';
import {MtCmd} from './tstype';
import {MtCmd, MtCmdZdo} from './tstype';

const Definition: {
[s: number]: MtCmd[];
[s: number]: (MtCmd | MtCmdZdo)[];
} = {
[Subsystem.SYS]: [
{
Expand Down Expand Up @@ -1538,6 +1539,7 @@ const Definition: {
name: 'unbindRsp',
ID: 162,
type: CommandType.AREQ,
zdo: {cluterId: ZdoClusterId.BIND_RESPONSE, skip: 2},
request: [
{name: 'srcaddr', parameterType: ParameterType.UINT16},
{name: 'status', parameterType: ParameterType.UINT8},
Expand Down
7 changes: 6 additions & 1 deletion src/adapter/z-stack/znp/tstype.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import {ClusterId as ZdoClusterId} from '../../../zspec/zdo';
import ParameterType from './parameterType';

type MtType = number | number[] | string | Buffer | {[s: string]: number | string}[];
Expand All @@ -15,6 +16,10 @@ interface MtCmd {
response?: MtParameter[];
}

interface MtCmdZdo extends MtCmd {
zdo: {cluterId: ZdoClusterId; skip: number};
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any
type ZpiObjectPayload = any;

Expand All @@ -23,4 +28,4 @@ interface BuffaloZnpOptions {
startIndex?: number;
}

export {ZpiObjectPayload, MtParameter, MtCmd, MtType, BuffaloZnpOptions};
export {ZpiObjectPayload, MtParameter, MtCmd, MtType, BuffaloZnpOptions, MtCmdZdo};
31 changes: 15 additions & 16 deletions src/adapter/z-stack/znp/znp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,8 +86,8 @@ class Znp extends events.EventEmitter {
private onUnpiParsed(frame: UnpiFrame): void {
try {
const object = ZpiObject.fromUnpiFrame(frame);
const message = `<-- ${Subsystem[object.subsystem]} - ${object.command} - ${JSON.stringify(object.payload)}`;
this.log(object.type, message);
const message = `<-- ${Subsystem[object.subsystem]} - ${object.command.name} - ${JSON.stringify(object.payload)}`;
this.log(object.command.type, message);
this.waitress.resolve(object);
this.emit('received', object);
} catch (error) {
Expand Down Expand Up @@ -286,17 +286,15 @@ class Znp extends events.EventEmitter {
}

const object = ZpiObject.createRequest(subsystem, command, payload);
const message = `--> ${Subsystem[object.subsystem]} - ${object.command} - ${JSON.stringify(payload)}`;
const message = `--> ${Subsystem[object.subsystem]} - ${object.command.name} - ${JSON.stringify(payload)}`;

return this.queue.execute<ZpiObject>(async (): Promise<ZpiObject> => {
this.log(object.type, message);
this.log(object.command.type, message);

const frame = object.toUnpiFrame();

if (object.type === Type.SREQ) {
const t = object.command === 'bdbStartCommissioning' || object.command === 'startupFromApp' ? 40000 : timeouts.SREQ;
const waiter = this.waitress.waitFor({type: Type.SRSP, subsystem: object.subsystem, command: object.command}, timeout || t);
this.unpiWriter.writeFrame(frame);
if (object.command.type === Type.SREQ) {
const t = object.command.name === 'bdbStartCommissioning' || object.command.name === 'startupFromApp' ? 40000 : timeouts.SREQ;
const waiter = this.waitress.waitFor({type: Type.SRSP, subsystem: object.subsystem, command: object.command.name}, timeout || t);
this.unpiWriter.writeFrame(object.unpiFrame);
const result = await waiter.start().promise;
if (result && result.payload.hasOwnProperty('status') && !expectedStatuses.includes(result.payload.status)) {
if (typeof waiterID === 'number') {
Expand All @@ -311,18 +309,18 @@ class Znp extends events.EventEmitter {
} else {
return result;
}
} else if (object.type === Type.AREQ && object.isResetCommand()) {
} else if (object.command.type === Type.AREQ && object.isResetCommand()) {
const waiter = this.waitress.waitFor({type: Type.AREQ, subsystem: Subsystem.SYS, command: 'resetInd'}, timeout || timeouts.reset);
this.queue.clear();
this.unpiWriter.writeFrame(frame);
this.unpiWriter.writeFrame(object.unpiFrame);
return waiter.start().promise;
} else {
/* istanbul ignore else */
if (object.type === Type.AREQ) {
this.unpiWriter.writeFrame(frame);
if (object.command.type === Type.AREQ) {
this.unpiWriter.writeFrame(object.unpiFrame);
return undefined;
} else {
throw new Error(`Unknown type '${object.type}'`);
throw new Error(`Unknown type '${object.command.type}'`);
}
}
});
Expand All @@ -343,7 +341,8 @@ class Znp extends events.EventEmitter {
}

private waitressValidator(zpiObject: ZpiObject, matcher: WaitressMatcher): boolean {
const requiredMatch = matcher.type === zpiObject.type && matcher.subsystem == zpiObject.subsystem && matcher.command === zpiObject.command;
const requiredMatch =
matcher.type === zpiObject.command.type && matcher.subsystem == zpiObject.subsystem && matcher.command === zpiObject.command.name;
let payloadMatch = true;

if (matcher.payload) {
Expand Down
Loading
Loading