Skip to content
This repository has been archived by the owner on Nov 7, 2024. It is now read-only.

Commit

Permalink
feat(climate): enable basic support for climate devices (#47)
Browse files Browse the repository at this point in the history
  • Loading branch information
t0bst4r committed Aug 16, 2024
1 parent 4e889d7 commit 6ffebb3
Show file tree
Hide file tree
Showing 11 changed files with 336 additions and 23 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ export class OnOffAspect extends AspectBase {

private turnOff = async (): Promise<void> => {
const cluster = this.device.getClusterServer(OnOffCluster)!;
this.log.debug('FROM MATTER: %s changed on off state to OFF', this.entityId);
this.log.debug('FROM MATTER: changed on off state to OFF');
cluster!.setOnOffAttribute(false);
const [domain, service] = this.config?.turnOff?.service?.split('.') ?? ['homeassistant', 'turn_off'];
await this.homeAssistantClient.callService(domain, service, this.config?.turnOn?.data?.(false), {
Expand All @@ -75,7 +75,7 @@ export class OnOffAspect extends AspectBase {
const cluster = this.device.getClusterServer(OnOffCluster)!;
const isOn = this.isOn(state);
if (cluster.getOnOffAttribute() !== isOn) {
this.log.debug('FROM HA: %s changed on-off state to %s', state.entity_id, state.state);
this.log.debug('FROM HA: changed on-off state to %s', state.state);
cluster.setOnOffAttribute(isOn);
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,193 @@
import { Thermostat, ThermostatCluster } from '@project-chip/matter.js/cluster';

import { AspectBase } from '@/aspects/aspect-base.js';
import {
ThermostatHandlers,
thermostatWithCooling,
thermostatWithHeating,
thermostatWithHeatingAndCooling,
} from '@/aspects/utils/thermostat-cluster.js';
import { MatterDevice } from '@/devices/index.js';
import { HomeAssistantClient } from '@/home-assistant-client/index.js';
import { HomeAssistantMatterEntity } from '@/models/index.js';

export interface ThermostatAspectConfig {
supportsCooling: boolean;
supportsHeating: boolean;
}

export interface ThermostatState {
systemMode: Thermostat.SystemMode;
minTemperature: number | undefined;
maxTemperature: number | undefined;
targetTemperature: number;
currentTemperature: number | null;
}

export class ThermostatAspect extends AspectBase {
private currentState: ThermostatState;

constructor(
private readonly homeAssistant: HomeAssistantClient,
private readonly device: MatterDevice,
entity: HomeAssistantMatterEntity,
private readonly config: ThermostatAspectConfig,
) {
super('ThermostatAspect', entity);
this.currentState = this.getState(entity);

if (config.supportsCooling && config.supportsHeating) {
this.log.debug('Cooling and Heating supported');
device.addClusterServer(thermostatWithHeatingAndCooling(device, this.currentState));
} else if (config.supportsCooling) {
this.log.debug('Cooling supported');
device.addClusterServer(thermostatWithCooling(device, this.currentState));
} else if (config.supportsHeating) {
this.log.debug('Heating supported');
device.addClusterServer(thermostatWithHeating(device, this.currentState));
}
device.addCommandHandler('setpointRaiseLower', this.setpointRaiseLower.bind(this));
device.addCommandHandler('systemMode', this.systemModeChanged.bind(this));
device.addCommandHandler('occupiedHeatingSetpoint', this.targetTemperatureChanged.bind(this));
device.addCommandHandler('occupiedCoolingSetpoint', this.targetTemperatureChanged.bind(this));
}

async update(state: HomeAssistantMatterEntity): Promise<void> {
const { systemMode, minTemperature, maxTemperature, currentTemperature, targetTemperature } = (this.currentState =
this.getState(state));
const cluster = this.device.getClusterServer(
ThermostatCluster.with(Thermostat.Feature.Cooling, Thermostat.Feature.Heating),
)!;
if (currentTemperature != null && currentTemperature != cluster.getLocalTemperatureAttribute()) {
cluster.setLocalTemperatureAttribute(currentTemperature);
}

if (this.config.supportsCooling) {
if (targetTemperature != null && targetTemperature !== cluster.getOccupiedCoolingSetpointAttribute()) {
cluster.setOccupiedCoolingSetpointAttribute(targetTemperature);
}
if (
minTemperature != null &&
cluster.getMinCoolSetpointLimitAttribute != null &&
minTemperature !== cluster.getMinCoolSetpointLimitAttribute()
) {
cluster.setMinCoolSetpointLimitAttribute(minTemperature);
}
if (
maxTemperature != null &&
cluster.getMaxCoolSetpointLimitAttribute != null &&
maxTemperature !== cluster.getMaxCoolSetpointLimitAttribute()
) {
cluster.setMaxCoolSetpointLimitAttribute(maxTemperature);
}
}
if (this.config.supportsHeating) {
if (targetTemperature != null && targetTemperature !== cluster.getOccupiedHeatingSetpointAttribute()) {
cluster.setOccupiedHeatingSetpointAttribute(targetTemperature);
}
if (
minTemperature != null &&
cluster.getMinHeatSetpointLimitAttribute != null &&
minTemperature !== cluster.getMinHeatSetpointLimitAttribute()
) {
cluster.setMinHeatSetpointLimitAttribute(minTemperature);
}
if (
maxTemperature != null &&
cluster.getMaxHeatSetpointLimitAttribute != null &&
maxTemperature !== cluster.getMaxHeatSetpointLimitAttribute()
) {
cluster.setMaxHeatSetpointLimitAttribute(maxTemperature);
}
}

if (systemMode != cluster.getSystemModeAttribute()) {
cluster.setSystemModeAttribute(systemMode);
}
}

private setpointRaiseLower: ThermostatHandlers['setpointRaiseLower'] = async ({ request }) => {
this.log.debug('FROM MATTER: SetpointRaise Lower: Mode: %s, Amount: %s', request.mode, request.amount);
const targetTemperature = this.currentState.targetTemperature / 100 + request.amount / 10;
await this.homeAssistant.callService(
'climate',
'set_temperature',
{
temperature: targetTemperature,
},
{
entity_id: [this.entityId],
},
);
};

private targetTemperatureChanged = async (newValue: number, oldValue: number) => {
if (newValue === this.currentState.targetTemperature) {
return;
}
this.log.debug('FROM MATTER: changed occupiedHeatingSetpoint from %s to %s', oldValue, newValue);
await this.homeAssistant.callService(
'climate',
'set_temperature',
{ temperature: newValue / 100 },
{ entity_id: [this.entityId] },
);
};

private systemModeChanged = async (newValue: Thermostat.SystemMode, oldValue: Thermostat.SystemMode) => {
if (newValue === this.currentState.systemMode) {
return;
}
this.log.debug('FROM MATTER: changed SystemMode from %s to %s', oldValue, newValue);
await this.homeAssistant.callService(
'climate',
'set_hvac_mode',
{
hvac_mode: this.getHvacMode(newValue),
},
{
entity_id: [this.entityId],
},
);
};

private getState(entity: HomeAssistantMatterEntity): ThermostatState {
return {
systemMode: this.getSystemMode(entity.state),
minTemperature: this.getTemperature(entity.attributes.min_temp) ?? undefined,
maxTemperature: this.getTemperature(entity.attributes.max_temp) ?? undefined,
currentTemperature: this.getTemperature(entity.attributes.current_temperature),
targetTemperature: this.getTemperature(entity.attributes.temperature) ?? 2100,
};
}

private getSystemMode(state: string | undefined): Thermostat.SystemMode {
switch (state ?? 'off') {
case 'heat':
return Thermostat.SystemMode.Heat;
case 'cool':
return Thermostat.SystemMode.Cool;
}
return Thermostat.SystemMode.Off;
}

private getHvacMode(systemMode: Thermostat.SystemMode): string {
switch (systemMode) {
case Thermostat.SystemMode.Cool:
return 'cool';
case Thermostat.SystemMode.Heat:
return 'heat';
default:
return 'off';
}
}

private getTemperature(value: number | string | null | undefined): number | null {
const current = value != null ? +value : null;
if (current == null || isNaN(current)) {
return null;
} else {
return current * 100;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
import {
ClusterServer,
ClusterServerHandlers,
ClusterServerObj,
Thermostat,
ThermostatCluster,
} from '@project-chip/matter.js/cluster';

import { MatterDevice } from '@/devices/index.js';

import type { ThermostatState } from '../thermostat-aspect.js';

export type ThermostatHandlers = Required<ClusterServerHandlers<typeof Thermostat.Complete>>;
type ThermostatBase = typeof Thermostat.Base;
type ThermostatClusterServerObj = ClusterServerObj<ThermostatBase['attributes'], {}>;

export function thermostatWithCooling(device: MatterDevice, state: ThermostatState): ThermostatClusterServerObj {
const clusterServer = ClusterServer(
ThermostatCluster.with(Thermostat.Feature.Cooling),
{
minCoolSetpointLimit: state.minTemperature,
maxCoolSetpointLimit: state.maxTemperature,
localTemperature: state.currentTemperature,
occupiedCoolingSetpoint: state.targetTemperature,
controlSequenceOfOperation: Thermostat.ControlSequenceOfOperation.CoolingOnly,
systemMode: state.systemMode,
},
{
setpointRaiseLower: (...attrs) => device.executeCommandHandler('setpointRaiseLower', ...attrs),
},
);
clusterServer.attributes.systemMode.addValueSetListener((...args) =>
device.executeCommandHandler('systemMode', ...args),
);
clusterServer.attributes.occupiedCoolingSetpoint.addValueSetListener((...args) =>
device.executeCommandHandler('occupiedCoolingSetpoint', ...args),
);
return clusterServer;
}

export function thermostatWithHeating(device: MatterDevice, state: ThermostatState): ThermostatClusterServerObj {
const clusterServer = ClusterServer(
ThermostatCluster.with(Thermostat.Feature.Heating),
{
minHeatSetpointLimit: state.minTemperature,
maxHeatSetpointLimit: state.maxTemperature,
localTemperature: state.currentTemperature,
occupiedHeatingSetpoint: state.targetTemperature,
controlSequenceOfOperation: Thermostat.ControlSequenceOfOperation.HeatingOnly,
systemMode: state.systemMode,
},
{
setpointRaiseLower: (...attrs) => device.executeCommandHandler('setpointRaiseLower', ...attrs),
},
);
clusterServer.attributes.systemMode.addValueSetListener((...args) =>
device.executeCommandHandler('systemMode', ...args),
);
clusterServer.attributes.occupiedHeatingSetpoint.addValueSetListener((...args) =>
device.executeCommandHandler('occupiedHeatingSetpoint', ...args),
);
return clusterServer;
}

export function thermostatWithHeatingAndCooling(
device: MatterDevice,
state: ThermostatState,
): ThermostatClusterServerObj {
const clusterServer = ClusterServer(
ThermostatCluster.with(Thermostat.Feature.Cooling, Thermostat.Feature.Heating),
{
minHeatSetpointLimit: state.minTemperature,
maxHeatSetpointLimit: state.maxTemperature,
minCoolSetpointLimit: state.minTemperature,
maxCoolSetpointLimit: state.maxTemperature,
localTemperature: state.currentTemperature,
occupiedHeatingSetpoint: state.targetTemperature,
occupiedCoolingSetpoint: state.targetTemperature,
controlSequenceOfOperation: Thermostat.ControlSequenceOfOperation.CoolingAndHeating,
systemMode: state.systemMode,
},
{
setpointRaiseLower: (...attrs) => device.executeCommandHandler('setpointRaiseLower', ...attrs),
},
{},
);
clusterServer.attributes.systemMode.addValueSetListener((...args) =>
device.executeCommandHandler('systemMode', ...args),
);
clusterServer.attributes.occupiedCoolingSetpoint.addValueSetListener((...args) =>
device.executeCommandHandler('occupiedCoolingSetpoint', ...args),
);
clusterServer.attributes.occupiedHeatingSetpoint.addValueSetListener((...args) =>
device.executeCommandHandler('occupiedHeatingSetpoint', ...args),
);
return clusterServer;
}
Original file line number Diff line number Diff line change
@@ -1,25 +1,24 @@
import { DeviceTypes } from '@project-chip/matter.js/device';

import { IdentifyAspect, LevelControlAspect } from '@/aspects/index.js';
import { IdentifyAspect } from '@/aspects/index.js';
import { ThermostatAspect } from '@/aspects/thermostat-aspect.js';
import { HvacMode } from '@/devices/climate/hvac-mode.js';
import { HomeAssistantClient } from '@/home-assistant-client/index.js';
import { HomeAssistantMatterEntity } from '@/models/index.js';

import { DeviceBase, DeviceBaseConfig } from './device-base.js';

export class ClimateDevice extends DeviceBase {
constructor(homeAssistantClient: HomeAssistantClient, entity: HomeAssistantMatterEntity, config: DeviceBaseConfig) {
super(entity, DeviceTypes.HEATING_COOLING_UNIT, config);
super(entity, DeviceTypes.THERMOSTAT, config);

const supportedModes = entity.attributes.hvac_modes as HvacMode[];

this.addAspect(new IdentifyAspect(this.matter, entity));
this.addAspect(
new LevelControlAspect(homeAssistantClient, this.matter, entity, {
getValue: (entity) => entity.attributes.temperature,
getMinValue: (entity) => entity.attributes.min_temp,
getMaxValue: (entity) => entity.attributes.max_temp,
moveToLevel: {
service: 'climate.set_temperature',
data: (temperature) => ({ temperature }),
},
new ThermostatAspect(homeAssistantClient, this.matter, entity, {
supportsHeating: [HvacMode.heat, HvacMode.heat_cool].some((mode) => supportedModes.includes(mode)),
supportsCooling: [HvacMode.cool, HvacMode.heat_cool].some((mode) => supportedModes.includes(mode)),
}),
);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
export enum HvacMode {
off = 'off',
heat = 'heat',
cool = 'cool',
heat_cool = 'heat_cool',
dry = 'dry',
fan_only = 'fan_only',
}
Original file line number Diff line number Diff line change
@@ -1,24 +1,26 @@
import { createDefaultGroupsClusterServer, createDefaultScenesClusterServer } from '@project-chip/matter.js/cluster';
import { Device, DeviceTypeDefinition } from '@project-chip/matter.js/device';
import { DeviceTypeDefinition } from '@project-chip/matter.js/device';

import { AspectBase, BasicInformationAspect } from '@/aspects/index.js';
import { MatterDevice } from '@/devices/matter-device.js';
import { HomeAssistantMatterEntity } from '@/models/index.js';

export interface DeviceBaseConfig {
readonly vendorId: number;
readonly vendorName: string;
}

export type DeviceConstructor = (entity: HomeAssistantMatterEntity, definition: DeviceTypeDefinition) => Device;
export type DeviceConstructor = (entity: HomeAssistantMatterEntity, definition: DeviceTypeDefinition) => MatterDevice;

export abstract class DeviceBase {
public static setDeviceConstructor(ctr: DeviceConstructor): void {
this.deviceConstructor = ctr;
}

private static deviceConstructor: DeviceConstructor;

public readonly entityId: string;
public readonly matter: Device;
public readonly matter: MatterDevice;
private readonly aspects: AspectBase[] = [];

protected constructor(entity: HomeAssistantMatterEntity, definition: DeviceTypeDefinition, config: DeviceBaseConfig) {
Expand Down
2 changes: 2 additions & 0 deletions packages/home-assistant-matter-hub/core/src/devices/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
export * from './device-base.js';
export * from './matter-device.js';
export * from './binary_sensor-device.js';
export * from './climate-device.js';
export * from './light-device.js';
Expand All @@ -12,6 +13,7 @@ export * from './utils/unsupported-device-class-error.js';
export enum EntityDomain {
automation = 'automation',
binary_sensor = 'binary_sensor',
climate = 'climate',
cover = 'cover',
input_boolean = 'input_boolean',
light = 'light',
Expand Down
Loading

0 comments on commit 6ffebb3

Please sign in to comment.