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!: Remove configuring group members through configuration.yaml #24338

Merged
merged 8 commits into from
Oct 21, 2024
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
95 changes: 0 additions & 95 deletions lib/extension/groups.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,79 +45,6 @@ export default class Groups extends Extension {
override async start(): Promise<void> {
this.eventBus.onStateChange(this, this.onStateChange);
this.eventBus.onMQTTMessage(this, this.onMQTTMessage);
await this.syncGroupsWithSettings();
}

private async syncGroupsWithSettings(): Promise<void> {
const settingsGroups = settings.getGroups();

const addRemoveFromGroup = async (
action: 'add' | 'remove',
deviceName: string,
groupName: string | number,
endpoint: zh.Endpoint,
group: Group,
): Promise<void> => {
try {
logger.info(`${action === 'add' ? 'Adding' : 'Removing'} '${deviceName}' to group '${groupName}'`);

if (action === 'remove') {
await endpoint.removeFromGroup(group.zh);
} else {
await endpoint.addToGroup(group.zh);
}
} catch (error) {
logger.error(`Failed to ${action} '${deviceName}' from '${groupName}'`);
logger.debug((error as Error).stack!);
}
};

for (const settingGroup of settingsGroups) {
const groupID = settingGroup.ID;
const zigbeeGroup = this.zigbee.groupsIterator((g) => g.groupID === groupID).next().value || this.zigbee.createGroup(groupID);
const settingsEndpoints: zh.Endpoint[] = [];

for (const d of settingGroup.devices) {
const parsed = this.zigbee.resolveEntityAndEndpoint(d);
const device = parsed.entity as Device;

if (!device) {
logger.error(`Cannot find '${d}' of group '${settingGroup.friendly_name}'`);
}

if (!parsed.endpoint) {
if (parsed.endpointID) {
logger.error(`Cannot find endpoint '${parsed.endpointID}' of device '${parsed.ID}'`);
}

continue;
}

// In settings but not in zigbee
if (!zigbeeGroup.zh.hasMember(parsed.endpoint)) {
await addRemoveFromGroup('add', device?.name, settingGroup.friendly_name, parsed.endpoint, zigbeeGroup);
}

settingsEndpoints.push(parsed.endpoint);
}

// In zigbee but not in settings
for (const endpoint of zigbeeGroup.zh.members) {
if (!settingsEndpoints.includes(endpoint)) {
const deviceName = settings.getDevice(endpoint.getDevice().ieeeAddr)!.friendly_name;

await addRemoveFromGroup('remove', deviceName, settingGroup.friendly_name, endpoint, zigbeeGroup);
}
}
}

for (const zigbeeGroup of this.zigbee.groupsIterator((zg) => !settingsGroups.some((sg) => sg.ID === zg.groupID))) {
for (const endpoint of zigbeeGroup.zh.members) {
const deviceName = settings.getDevice(endpoint.getDevice().ieeeAddr)!.friendly_name;

await addRemoveFromGroup('remove', deviceName, zigbeeGroup.ID, endpoint, zigbeeGroup);
}
}
}

@bind async onStateChange(data: eventdata.StateChange): Promise<void> {
Expand Down Expand Up @@ -320,33 +247,15 @@ export default class Groups extends Extension {
if (!error) {
assert(resolvedEntityEndpoint, '`resolvedEntityEndpoint` is missing');
try {
const keys = [
`${resolvedEntityDevice.ieeeAddr}/${resolvedEntityEndpoint.ID}`,
`${resolvedEntityDevice.name}/${resolvedEntityEndpoint.ID}`,
];
const endpointNameLocal = resolvedEntityDevice.endpointName(resolvedEntityEndpoint);

if (endpointNameLocal) {
keys.push(`${resolvedEntityDevice.ieeeAddr}/${endpointNameLocal}`);
keys.push(`${resolvedEntityDevice.name}/${endpointNameLocal}`);
}

if (!endpointNameLocal) {
keys.push(resolvedEntityDevice.name);
keys.push(resolvedEntityDevice.ieeeAddr);
}

if (type === 'add') {
assert(resolvedEntityGroup, '`resolvedEntityGroup` is missing');
logger.info(`Adding '${resolvedEntityDevice.name}' to '${resolvedEntityGroup.name}'`);
await resolvedEntityEndpoint.addToGroup(resolvedEntityGroup.zh);
settings.addDeviceToGroup(resolvedEntityGroup.ID.toString(), keys);
Koenkk marked this conversation as resolved.
Show resolved Hide resolved
changedGroups.push(resolvedEntityGroup);
} 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);
} else {
// remove_all
Expand All @@ -357,10 +266,6 @@ export default class Groups extends Extension {
}

await resolvedEntityEndpoint.removeFromAllGroups();

for (const settingsGroup of settings.getGroups()) {
settings.removeDeviceFromGroup(settingsGroup.ID.toString(), keys);
}
}
} catch (e) {
error = `Failed to ${type} from group (${(e as Error).message})`;
Expand Down
3 changes: 1 addition & 2 deletions lib/types/types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,7 @@ declare global {
ssl_key?: string;
};
devices: {[s: string]: DeviceOptions};
groups: {[s: string]: OptionalProps<Omit<GroupOptions, 'ID'>, 'devices'>};
groups: {[s: string]: Omit<GroupOptions, 'ID'>};
device_options: KeyValue;
advanced: {
log_rotation: boolean;
Expand Down Expand Up @@ -238,7 +238,6 @@ declare global {
}

interface GroupOptions {
devices: string[];
ID: number;
optimistic?: boolean;
off_state?: 'all_members_off' | 'last_member_state';
Expand Down
6 changes: 0 additions & 6 deletions lib/util/settings.schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -905,12 +905,6 @@
"retain": {
"type": "boolean"
},
"devices": {
"type": "array",
"items": {
"type": "string"
}
},
"optimistic": {
"type": "boolean"
},
Expand Down
62 changes: 2 additions & 60 deletions lib/util/settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -527,26 +527,18 @@ export function getGroup(IDorName: string | number): GroupOptions | undefined {
const byID = settings.groups[IDorName];

if (byID) {
return {devices: [], ...byID, ID: Number(IDorName)};
return {...byID, ID: Number(IDorName)};
}

for (const [ID, group] of Object.entries(settings.groups)) {
if (group.friendly_name === IDorName) {
return {devices: [], ...group, ID: Number(ID)};
return {...group, ID: Number(ID)};
}
}

return undefined;
}

export function getGroups(): GroupOptions[] {
const settings = get();

return Object.entries(settings.groups).map(([ID, group]) => {
return {devices: [], ...group, ID: Number(ID)};
});
}

function getGroupThrowIfNotExists(IDorName: string): GroupOptions {
const group = getGroup(IDorName);

Expand Down Expand Up @@ -614,16 +606,6 @@ export function removeDevice(IDorName: string): void {
const device = getDeviceThrowIfNotExists(IDorName);
const settings = getInternalSettings();
delete settings.devices?.[device.ID];

// Remove device from groups
if (settings.groups) {
const regex = new RegExp(`^(${device.friendly_name}|${device.ID})(/[^/]+)?$`);

for (const group of Object.values(settings.groups).filter((g) => g.devices)) {
group.devices = group.devices?.filter((device) => !device.match(regex));
}
}

write();
}

Expand Down Expand Up @@ -661,46 +643,6 @@ export function addGroup(name: string, ID?: string): GroupOptions {
return getGroup(ID)!; // valid from creation above
}

function groupGetDevice(group: {devices?: string[]}, keys: string[]): string | undefined {
for (const device of group.devices ?? []) {
if (keys.includes(device)) {
return device;
}
}

return undefined;
}

export function addDeviceToGroup(IDorName: string, keys: string[]): void {
const groupID = getGroupThrowIfNotExists(IDorName).ID!;
const settings = getInternalSettings();

const group = settings.groups![groupID];

if (!groupGetDevice(group, keys)) {
if (!group.devices) group.devices = [];
group.devices.push(keys[0]);
write();
}
}

export function removeDeviceFromGroup(IDorName: string, keys: string[]): void {
const groupID = getGroupThrowIfNotExists(IDorName).ID!;
const settings = getInternalSettings();
const group = settings.groups![groupID];

if (!group.devices) {
return;
}

const key = groupGetDevice(group, keys);

if (key) {
group.devices = group.devices.filter((d) => d != key);
write();
}
}

export function removeGroup(IDorName: string | number): void {
const groupID = getGroupThrowIfNotExists(IDorName.toString()).ID!;
const settings = getInternalSettings();
Expand Down
Loading