-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
home-assistant.service.ts
197 lines (176 loc) · 5.65 KB
/
home-assistant.service.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
import {
Injectable,
Logger,
OnApplicationBootstrap,
OnApplicationShutdown,
OnModuleInit
} from '@nestjs/common';
import { Entity } from '../../entities/entity.entity';
import { Sensor } from '../../entities/sensor.entity';
import { EntityConfig } from './entity-config';
import { SensorConfig } from './sensor-config';
import * as _ from 'lodash';
import { ConfigService } from '../../config/config.service';
import mqtt, { AsyncMqttClient } from 'async-mqtt';
import { HomeAssistantConfig } from './home-assistant.config';
import { Device } from './device';
import { system } from 'systeminformation';
import { InjectEventEmitter } from 'nest-emitter';
import { EntitiesEventEmitter } from '../../entities/entities.events';
import { EntityCustomization } from '../../entities/entity-customization.interface';
const PROPERTY_BLACKLIST = ['component', 'configTopic'];
@Injectable()
export class HomeAssistantService
implements OnModuleInit, OnApplicationBootstrap, OnApplicationShutdown {
private config: HomeAssistantConfig;
private device: Device;
private entityConfigs: Map<string, EntityConfig> = new Map<
string,
EntityConfig
>();
private debounceFunctions: Map<string, () => void> = new Map<
string,
() => void
>();
private mqttClient: AsyncMqttClient;
private readonly logger: Logger = new Logger(HomeAssistantService.name);
constructor(
private readonly configService: ConfigService,
@InjectEventEmitter() private readonly emitter: EntitiesEventEmitter
) {
this.config = this.configService.get('homeAssistant');
}
onModuleInit(): void {
this.emitter.on('newEntity', this.handleNewEntity.bind(this));
this.emitter.on('stateUpdate', this.handleNewState.bind(this));
this.emitter.on('attributesUpdate', this.handleNewAttributes.bind(this));
}
async onApplicationBootstrap(): Promise<void> {
this.mqttClient = mqtt.connect(
this.config.mqttUrl,
this.config.mqttOptions
);
this.mqttClient.on('connect', () =>
this.logger.log(`Connected to ${this.config.mqttUrl}`)
);
const systemInfo = await system();
this.device = new Device(systemInfo.uuid);
this.device.name = this.configService.get('global').instanceName;
this.device.model = systemInfo.model;
this.device.manufacturer = systemInfo.manufacturer;
}
async onApplicationShutdown(signal?: string): Promise<void> {
this.entityConfigs.forEach(config => {
if (config.device.identifiers !== 'room-assistant-distributed') {
this.mqttClient.publish(
config.availabilityTopic,
config.payloadNotAvailable
);
}
});
return this.mqttClient.end();
}
handleNewEntity(
entity: Entity,
customizations: Array<EntityCustomization<any>> = []
): void {
const combinedId = this.getCombinedId(entity.id, entity.distributed);
let config: EntityConfig;
if (entity instanceof Sensor) {
config = new SensorConfig(combinedId, entity.name);
} else {
this.logger.warn(
`${combinedId} cannot be matched to a Home Assistant type and will not be transferred`
);
return;
}
config = this.applyCustomizations(config, customizations);
if (entity.distributed) {
config.device = new Device('room-assistant-distributed');
config.device.name = 'room-assistant hub';
} else {
config.device = this.device;
}
this.entityConfigs.set(combinedId, config);
this.mqttClient.publish(
config.configTopic,
JSON.stringify(this.formatMessage(config)),
{
qos: 0,
retain: true
}
);
this.mqttClient.publish(config.availabilityTopic, config.payloadAvailable);
}
handleNewState(
id: string,
state: number | string | boolean,
distributed: boolean = false
): void {
const config = this.entityConfigs.get(this.getCombinedId(id, distributed));
if (config === undefined) {
return;
}
this.mqttClient.publish(config.stateTopic, String(state));
}
handleNewAttributes(
entityId: string,
attributes: { [key: string]: any },
distributed: boolean = false
): void {
const config = this.entityConfigs.get(
this.getCombinedId(entityId, distributed)
);
if (config === undefined) {
return;
}
if (this.debounceFunctions.has(entityId)) {
this.debounceFunctions.get(entityId)();
} else {
const debouncedFunc = _.debounce(() => {
this.mqttClient.publish(
config.jsonAttributesTopic,
JSON.stringify(this.formatMessage(attributes))
);
});
this.debounceFunctions.set(entityId, debouncedFunc);
}
}
protected getCombinedId(
entityId: string,
distributed: boolean = false
): string {
return `${
distributed
? 'distributed'
: this.configService.get('global').instanceName
}_${entityId}`;
}
protected applyCustomizations(
config: EntityConfig,
customizations: Array<EntityCustomization<any>>
): EntityConfig {
const customization = customizations.find(
value => value.for.prototype instanceof EntityConfig
);
if (customization !== undefined) {
Object.assign(config, customization.overrides);
}
return config;
}
protected formatMessage(message: object): object {
const filteredMessage = _.omit(message, PROPERTY_BLACKLIST);
return this.deepMap(filteredMessage, obj => {
return _.mapKeys(obj, (v, k) => {
return _.snakeCase(k);
});
});
}
private deepMap(obj: object, mapper: (v: object) => object): object {
return mapper(
_.mapValues(obj, v => {
return _.isObject(v) && !_.isArray(v) ? this.deepMap(v, mapper) : v;
})
);
}
}