Skip to content

Commit

Permalink
Remove legacy_api logic from non-legacy extensions.
Browse files Browse the repository at this point in the history
  • Loading branch information
Nerivec committed Oct 4, 2024
1 parent fe7d913 commit a2237ed
Show file tree
Hide file tree
Showing 13 changed files with 94 additions and 1,222 deletions.
2 changes: 1 addition & 1 deletion lib/controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -349,7 +349,7 @@ export class Controller {
// Filter mqtt message attributes
utils.filterProperties(entity.options.filtered_attributes, message);

if (Object.entries(message).length) {
if (!utils.objectIsEmpty(message)) {
const output = settings.get().advanced.output;
if (output === 'attribute_and_json' || output === 'json') {
await this.mqtt.publish(entity.name, stringify(message), options);
Expand Down
38 changes: 3 additions & 35 deletions lib/extension/bind.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,6 @@ import * as settings from '../util/settings';
import utils from '../util/utils';
import Extension from './extension';

const LEGACY_API = settings.get().advanced.legacy_api;
const LEGACY_TOPIC_REGEX = new RegExp(`^${settings.get().mqtt.base_topic}/bridge/(bind|unbind)/.+$`);
const TOPIC_REGEX = new RegExp(`^${settings.get().mqtt.base_topic}/bridge/request/device/(bind|unbind)`);
const ALL_CLUSTER_CANDIDATES: readonly ClusterName[] = [
'genScenes',
Expand Down Expand Up @@ -226,12 +224,7 @@ export default class Bind extends Extension {
let clusters: ParsedMQTTMessage['clusters'] | undefined;
let skipDisableReporting: ParsedMQTTMessage['skipDisableReporting'] = false;

if (LEGACY_API && data.topic.match(LEGACY_TOPIC_REGEX)) {
const topic = data.topic.replace(`${settings.get().mqtt.base_topic}/bridge/`, '');
type = topic.split('/')[0] as ParsedMQTTMessage['type'];
sourceKey = topic.replace(`${type}/`, '');
targetKey = data.message;
} else if (data.topic.match(TOPIC_REGEX)) {
if (data.topic.match(TOPIC_REGEX)) {
type = data.topic.endsWith('unbind') ? 'unbind' : 'bind';
const message: DataMessage = JSON.parse(data.message);
sourceKey = message.from;
Expand Down Expand Up @@ -312,37 +305,16 @@ export default class Bind extends Extension {
logger.info(
`Successfully ${type === 'bind' ? 'bound' : 'unbound'} cluster '${cluster}' from '${source.name}' to '${target.name}'`,
);

/* istanbul ignore else */
if (settings.get().advanced.legacy_api) {
await this.mqtt.publish(
'bridge/log',
stringify({type: `device_${type}`, message: {from: source.name, to: target.name, cluster}}),
);
}
} catch (error) {
failedClusters.push(cluster);
logger.error(`Failed to ${type} cluster '${cluster}' from '${source.name}' to '${target.name}' (${error})`);

/* istanbul ignore else */
if (settings.get().advanced.legacy_api) {
await this.mqtt.publish(
'bridge/log',
stringify({type: `device_${type}_failed`, message: {from: source.name, to: target.name, cluster}}),
);
}
}
}
}

if (attemptedClusters.length === 0) {
logger.error(`Nothing to ${type} from '${source.name}' to '${target.name}'`);
error = `Nothing to ${type}`;

/* istanbul ignore else */
if (settings.get().advanced.legacy_api) {
await this.mqtt.publish('bridge/log', stringify({type: `device_${type}_failed`, message: {from: source.name, to: target.name}}));
}
} else if (failedClusters.length === attemptedClusters.length) {
error = `Failed to ${type}`;
}
Expand All @@ -359,13 +331,9 @@ export default class Bind extends Extension {
}
}

const triggeredViaLegacyApi = data.topic.match(LEGACY_TOPIC_REGEX);
const response = utils.getResponse(message, responseData, error);

if (!triggeredViaLegacyApi) {
const response = utils.getResponse(message, responseData, error);

await this.mqtt.publish(`bridge/response/device/${type}`, stringify(response));
}
await this.mqtt.publish(`bridge/response/device/${type}`, stringify(response));

if (error) {
logger.error(error);
Expand Down
101 changes: 8 additions & 93 deletions lib/extension/groups.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,6 @@ import utils, {isLightExpose} from '../util/utils';
import Extension from './extension';

const TOPIC_REGEX = new RegExp(`^${settings.get().mqtt.base_topic}/bridge/request/group/members/(remove|add|remove_all)$`);
const LEGACY_TOPIC_REGEX = new RegExp(`^${settings.get().mqtt.base_topic}/bridge/group/(.+)/(remove|add|remove_all)$`);
const LEGACY_TOPIC_REGEX_REMOVE_ALL = new RegExp(`^${settings.get().mqtt.base_topic}/bridge/group/remove_all$`);

const STATE_PROPERTIES: Readonly<Record<string, (value: string, exposes: zhc.Expose[]) => boolean>> = {
state: () => true,
Expand All @@ -37,13 +35,11 @@ interface ParsedMQTTMessage {
error?: string;
groupKey?: string;
deviceKey?: string;
triggeredViaLegacyApi: boolean;
skipDisableReporting: boolean;
resolvedEntityEndpoint?: zh.Endpoint;
}

export default class Groups extends Extension {
private legacyApi = settings.get().advanced.legacy_api;
private lastOptimisticState: {[s: string]: KeyValue} = {};

override async start(): Promise<void> {
Expand Down Expand Up @@ -255,60 +251,12 @@ export default class Groups extends Extension {
let error: ParsedMQTTMessage['error'] | undefined;
let groupKey: ParsedMQTTMessage['groupKey'] | undefined;
let deviceKey: ParsedMQTTMessage['deviceKey'] | undefined;
let triggeredViaLegacyApi: ParsedMQTTMessage['triggeredViaLegacyApi'] = false;
let skipDisableReporting: ParsedMQTTMessage['skipDisableReporting'] = false;

/* istanbul ignore else */
const topicRegexMatch = data.topic.match(TOPIC_REGEX);
const legacyTopicRegexRemoveAllMatch = data.topic.match(LEGACY_TOPIC_REGEX_REMOVE_ALL);
const legacyTopicRegexMatch = data.topic.match(LEGACY_TOPIC_REGEX);

if (this.legacyApi && (legacyTopicRegexMatch || legacyTopicRegexRemoveAllMatch)) {
triggeredViaLegacyApi = true;

if (legacyTopicRegexMatch) {
resolvedEntityGroup = this.zigbee.resolveEntity(legacyTopicRegexMatch[1]) as Group;
type = legacyTopicRegexMatch[2] as ParsedMQTTMessage['type'];

if (!resolvedEntityGroup || !(resolvedEntityGroup instanceof Group)) {
logger.error(`Group '${legacyTopicRegexMatch[1]}' does not exist`);

/* istanbul ignore else */
if (settings.get().advanced.legacy_api) {
const message = {friendly_name: data.message, group: legacyTopicRegexMatch[1], error: `group doesn't exists`};

await this.mqtt.publish('bridge/log', stringify({type: `device_group_${type}_failed`, message}));
}

return undefined;
}
} else {
type = 'remove_all';
}

const parsedEntity = this.zigbee.resolveEntityAndEndpoint(data.message);
resolvedEntityDevice = parsedEntity.entity as Device;

if (!resolvedEntityDevice || !(resolvedEntityDevice instanceof Device)) {
logger.error(`Device '${data.message}' does not exist`);

/* istanbul ignore else */
if (settings.get().advanced.legacy_api) {
const message = {friendly_name: data.message, group: legacyTopicRegexMatch![1], error: "entity doesn't exists"};

await this.mqtt.publish('bridge/log', stringify({type: `device_group_${type}_failed`, message}));
}

return undefined;
}

resolvedEntityEndpoint = parsedEntity.endpoint;

if (parsedEntity.endpointID && !resolvedEntityEndpoint) {
logger.error(`Device '${parsedEntity.ID}' does not have endpoint '${parsedEntity.endpointID}'`);
return undefined;
}
} else if (topicRegexMatch) {
if (topicRegexMatch) {
type = topicRegexMatch[1] as 'remove' | 'add' | 'remove_all';
const message = JSON.parse(data.message);
deviceKey = message.device;
Expand Down Expand Up @@ -348,7 +296,6 @@ export default class Groups extends Extension {
error,
groupKey,
deviceKey,
triggeredViaLegacyApi,
skipDisableReporting,
resolvedEntityEndpoint,
};
Expand All @@ -361,16 +308,7 @@ export default class Groups extends Extension {
return;
}

const {
resolvedEntityGroup,
resolvedEntityDevice,
type,
triggeredViaLegacyApi,
groupKey,
deviceKey,
skipDisableReporting,
resolvedEntityEndpoint,
} = parsed;
const {resolvedEntityGroup, resolvedEntityDevice, type, groupKey, deviceKey, skipDisableReporting, resolvedEntityEndpoint} = parsed;
let error = parsed.error;
const changedGroups: Group[] = [];

Expand Down Expand Up @@ -399,26 +337,12 @@ export default class Groups extends Extension {
await resolvedEntityEndpoint.addToGroup(resolvedEntityGroup.zh);
settings.addDeviceToGroup(resolvedEntityGroup.ID.toString(), keys);
changedGroups.push(resolvedEntityGroup);

/* istanbul ignore else */
if (settings.get().advanced.legacy_api) {
const message = {friendly_name: resolvedEntityDevice.name, group: resolvedEntityGroup.name};

await this.mqtt.publish('bridge/log', stringify({type: `device_group_add`, message}));
}
} else if (type === 'remove') {
assert(resolvedEntityGroup, '`resolvedEntityGroup` is missing');
logger.info(`Removing '${resolvedEntityDevice.name}' from '${resolvedEntityGroup.name}'`);
await resolvedEntityEndpoint.removeFromGroup(resolvedEntityGroup.zh);
settings.removeDeviceFromGroup(resolvedEntityGroup.ID.toString(), keys);
changedGroups.push(resolvedEntityGroup);

/* istanbul ignore else */
if (settings.get().advanced.legacy_api) {
const message = {friendly_name: resolvedEntityDevice.name, group: resolvedEntityGroup.name};

await this.mqtt.publish('bridge/log', stringify({type: `device_group_remove`, message}));
}
} else {
// remove_all
logger.info(`Removing '${resolvedEntityDevice.name}' from all groups`);
Expand All @@ -431,13 +355,6 @@ export default class Groups extends Extension {

for (const settingsGroup of settings.getGroups()) {
settings.removeDeviceFromGroup(settingsGroup.ID.toString(), keys);

/* istanbul ignore else */
if (settings.get().advanced.legacy_api) {
const message = {friendly_name: resolvedEntityDevice.name};

await this.mqtt.publish('bridge/log', stringify({type: `device_group_remove_all`, message}));
}
}
}
} catch (e) {
Expand All @@ -446,17 +363,15 @@ export default class Groups extends Extension {
}
}

if (!triggeredViaLegacyApi) {
const message = utils.parseJSON(data.message, data.message);
const responseData: KeyValue = {device: deviceKey};
const message = utils.parseJSON(data.message, data.message);
const responseData: KeyValue = {device: deviceKey};

if (groupKey) {
responseData.group = groupKey;
}

await this.mqtt.publish(`bridge/response/group/members/${type}`, stringify(utils.getResponse(message, responseData, error)));
if (groupKey) {
responseData.group = groupKey;
}

await this.mqtt.publish(`bridge/response/group/members/${type}`, stringify(utils.getResponse(message, responseData, error)));

if (error) {
logger.error(error);
} else {
Expand Down
14 changes: 0 additions & 14 deletions lib/extension/networkMap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,6 @@ interface Topology {
* This extension creates a network map
*/
export default class NetworkMap extends Extension {
private legacyApi = settings.get().advanced.legacy_api;
private legacyTopic = `${settings.get().mqtt.base_topic}/bridge/networkmap`;
private legacyTopicRoutes = `${settings.get().mqtt.base_topic}/bridge/networkmap/routes`;
private topic = `${settings.get().mqtt.base_topic}/bridge/request/networkmap`;
private supportedFormats: {[s: string]: (topology: Topology) => KeyValue | string} = {
raw: this.raw,
Expand All @@ -53,17 +50,6 @@ export default class NetworkMap extends Extension {
}

@bind async onMQTTMessage(data: eventdata.MQTTMessage): Promise<void> {
/* istanbul ignore else */
if (this.legacyApi) {
if ((data.topic === this.legacyTopic || data.topic === this.legacyTopicRoutes) && this.supportedFormats[data.message] !== undefined) {
const includeRoutes = data.topic === this.legacyTopicRoutes;
const topology = await this.networkScan(includeRoutes);
let converted = this.supportedFormats[data.message](topology);
converted = data.message === 'raw' ? stringify(converted) : converted;
await this.mqtt.publish(`bridge/networkmap/${data.message}`, converted as string, {});
}
}

if (data.topic === this.topic) {
const message = utils.parseJSON(data.message, data.message);
try {
Expand Down
Loading

0 comments on commit a2237ed

Please sign in to comment.