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

Availability code optimization/formatting #23065

Merged
merged 3 commits into from
Jun 16, 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
94 changes: 54 additions & 40 deletions lib/extension/availability.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,23 +27,21 @@ export default class Availability extends Extension {

const key = this.isActiveDevice(device) ? 'active' : 'passive';
let value = settings.get().availability?.[key]?.timeout;
if (value == null) value = key == 'active' ? 10 : 1500;

if (value == null) {
value = key == 'active' ? 10 : 1500;
}

return utils.minutes(value);
}

private isActiveDevice(device: Device): boolean {
return (device.zh.type === 'Router' && device.zh.powerSource !== 'Battery') ||
device.zh.powerSource === 'Mains (single phase)';
return (device.zh.type === 'Router' && device.zh.powerSource !== 'Battery') || device.zh.powerSource === 'Mains (single phase)';
}

private isAvailable(entity: Device | Group): boolean {
if (entity.isDevice()) {
const ago = Date.now() - entity.zh.lastSeen;
return ago < this.getTimeout(entity);
} else {
return entity.membersDevices().length === 0 ||
entity.membersDevices().map((d) => this.availabilityCache[d.ieeeAddr]).includes(true);
}
return entity.isDevice() ? (Date.now() - entity.zh.lastSeen) < this.getTimeout(entity) :
entity.membersDevices().length === 0 || entity.membersDevices().some((d) => this.availabilityCache[d.ieeeAddr]);
}

private resetTimer(device: Device): void {
Expand All @@ -52,11 +50,9 @@ export default class Availability extends Extension {
// If the timer triggers, the device is not available anymore otherwise resetTimer already have been called
if (this.isActiveDevice(device)) {
// If device did not check in, ping it, if that fails it will be marked as offline
this.timers[device.ieeeAddr] = setTimeout(
() => this.addToPingQueue(device), this.getTimeout(device) + utils.seconds(1));
this.timers[device.ieeeAddr] = setTimeout(() => this.addToPingQueue(device), this.getTimeout(device) + utils.seconds(1));
} else {
this.timers[device.ieeeAddr] = setTimeout(
() => this.publishAvailability(device, true), this.getTimeout(device) + utils.seconds(1));
this.timers[device.ieeeAddr] = setTimeout(() => this.publishAvailability(device, true), this.getTimeout(device) + utils.seconds(1));
}
}

Expand All @@ -71,26 +67,32 @@ export default class Availability extends Extension {
}

private async pingQueueExecuteNext(): Promise<void> {
if (this.pingQueue.length === 0 || this.pingQueueExecuting) return;
this.pingQueueExecuting = true;
if (this.pingQueue.length === 0 || this.pingQueueExecuting) {
return;
}

this.pingQueueExecuting = true;
const device = this.pingQueue[0];
let pingedSuccessfully = false;
const available = this.availabilityCache[device.ieeeAddr] || this.isAvailable(device);
const attempts = available ? 2 : 1;
for (let i = 0; i < attempts; i++) {

for (let i = 1; i <= attempts; i++) {
try {
// Enable recovery if device is marked as available and first ping fails.
const disableRecovery = !(i == 1 && available);
await device.zh.ping(disableRecovery);
await device.zh.ping(!available || (i !== 2));

pingedSuccessfully = true;
logger.debug(`Successfully pinged '${device.name}' (attempt ${i + 1}/${attempts})`);

logger.debug(`Successfully pinged '${device.name}' (attempt ${i}/${attempts})`);
break;
} catch (error) {
logger.warning(`Failed to ping '${device.name}' (attempt ${i + 1}/${attempts}, ${error.message})`);
logger.warning(`Failed to ping '${device.name}' (attempt ${i}/${attempts}, ${error.message})`);

// Try again in 3 seconds.
const lastAttempt = i - 1 === attempts;
!lastAttempt && await utils.sleep(3);
if (i !== attempts) {
await utils.sleep(3);
}
}
}

Expand All @@ -105,7 +107,9 @@ export default class Availability extends Extension {

// Sleep 2 seconds before executing next ping
await utils.sleep(2);

this.pingQueueExecuting = false;

await this.pingQueueExecuteNext();
}

Expand Down Expand Up @@ -148,26 +152,23 @@ export default class Availability extends Extension {
}
}

private async publishAvailability(entity: Device | Group, logLastSeen: boolean,
forcePublish=false, skipGroups=false): Promise<void> {
private async publishAvailability(entity: Device | Group, logLastSeen: boolean, forcePublish=false, skipGroups=false): Promise<void> {
if (logLastSeen && entity.isDevice()) {
const ago = Date.now() - entity.zh.lastSeen;
if (this.isActiveDevice(entity)) {
logger.debug(`Active device '${entity.name}' was last seen ` +
`'${(ago / utils.minutes(1)).toFixed(2)}' minutes ago.`);
logger.debug(`Active device '${entity.name}' was last seen '${(ago / utils.minutes(1)).toFixed(2)}' minutes ago.`);
} else {
logger.debug(
`Passive device '${entity.name}' was last seen '${(ago / utils.hours(1)).toFixed(2)}' hours ago.`);
logger.debug(`Passive device '${entity.name}' was last seen '${(ago / utils.hours(1)).toFixed(2)}' hours ago.`);
}
}

const available = this.isAvailable(entity);

if (!forcePublish && this.availabilityCache[entity.ID] == available) {
return;
}

if (entity.isDevice() && entity.ieeeAddr in this.availabilityCache && available &&
this.availabilityCache[entity.ieeeAddr] === false) {
if (entity.isDevice() && entity.ieeeAddr in this.availabilityCache && available && this.availabilityCache[entity.ieeeAddr] === false) {
logger.debug(`Device '${entity.name}' reconnected`);
this.retrieveState(entity);
}
Expand All @@ -178,9 +179,11 @@ export default class Availability extends Extension {
await this.mqtt.publish(topic, payload, {retain: true, qos: 1});

if (!skipGroups && entity.isDevice()) {
this.zigbee.groups().filter((g) => g.hasMember(entity))
.filter((g) => utils.isAvailabilityEnabledForEntity(g, settings.get()))
.forEach((g) => this.publishAvailability(g, false, forcePublish));
for (const group of this.zigbee.groups()) {
if (group.hasMember(entity) && utils.isAvailabilityEnabledForEntity(group, settings.get())) {
await this.publishAvailability(group, false, forcePublish);
}
}
}
}

Expand All @@ -196,7 +199,11 @@ export default class Availability extends Extension {
override async stop(): Promise<void> {
this.stopped = true;
this.pingQueue = [];
Object.values(this.timers).forEach((t) => clearTimeout(t));

for (const t of Object.values(this.timers)) {
clearTimeout(t);
}

await super.stop();
}

Expand All @@ -208,20 +215,27 @@ export default class Availability extends Extension {
if (device.definition && !device.zh.interviewing && !this.retrieveStateDebouncers[device.ieeeAddr]) {
this.retrieveStateDebouncers[device.ieeeAddr] = debounce(async () => {
logger.debug(`Retrieving state of '${device.name}' after reconnect`);

// Color and color temperature converters do both, only needs to be called once.
for (const item of retrieveOnReconnect) {
if (item.condition && this.state.get(device) && !item.condition(this.state.get(device))) continue;
if (item.condition && this.state.get(device) && !item.condition(this.state.get(device))) {
continue;
}

const converter = device.definition.toZigbee.find((c) => c.key.find((k) => item.keys.includes(k)));
const options: KeyValue = device.options;
const state = this.state.get(device);
const meta: zhc.Tz.Meta = {
message: this.state.get(device), mapped: device.definition, endpoint_name: null,
options, state, device: device.zh,
};
await converter?.convertGet?.(device.endpoint(), item.keys[0], meta)
.catch((e) => {
logger.error(`Failed to read state of '${device.name}' after reconnect (${e.message})`);
});

try {
await converter?.convertGet?.(device.endpoint(), item.keys[0], meta);
} catch (error) {
logger.error(`Failed to read state of '${device.name}' after reconnect (${error.message})`);
}

await utils.sleep(500);
}
}, utils.seconds(2));
Expand Down
23 changes: 16 additions & 7 deletions lib/util/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -269,27 +269,36 @@ function sanitizeImageParameter(parameter: string): string {
}

function isAvailabilityEnabledForEntity(entity: Device | Group, settings: Settings): boolean {
if (entity.isDevice() && entity.options.disabled) {
return false;
}

if (entity.isGroup()) {
return !entity.membersDevices().map((d) => isAvailabilityEnabledForEntity(d, settings)).includes(false);
return !entity.membersDevices().some((d) => !isAvailabilityEnabledForEntity(d, settings));
}

if (entity.options.hasOwnProperty('availability')) {
if (entity.options.availability != null) {
return !!entity.options.availability;
}

// availability_timeout = deprecated
const enabledGlobal = settings.advanced.availability_timeout || settings.availability;
if (!enabledGlobal) return false;

if (entity.isDevice() && entity.options.disabled) return false;
if (!(settings.advanced.availability_timeout || settings.availability)) {
return false;
}

const passlist = settings.advanced.availability_passlist.concat(settings.advanced.availability_whitelist);

if (passlist.length > 0) {
return passlist.includes(entity.name) || passlist.includes(entity.ieeeAddr);
}

const blocklist = settings.advanced.availability_blacklist.concat(settings.advanced.availability_blocklist);
return !blocklist.includes(entity.name) && !blocklist.includes(entity.ieeeAddr);

if (blocklist.length > 0) {
return !blocklist.includes(entity.name) && !blocklist.includes(entity.ieeeAddr);
}

return true;
}

function isEndpoint(obj: unknown): obj is zh.Endpoint {
Expand Down
Loading