-
Notifications
You must be signed in to change notification settings - Fork 5
/
pureDirectAccessory.ts
84 lines (67 loc) · 2.59 KB
/
pureDirectAccessory.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
import { Service, PlatformAccessory, CharacteristicValue } from 'homebridge';
import fetch from 'node-fetch';
import { YamahaAVRPlatform } from './platform.js';
import { AccessoryContext, BaseResponse } from './types.js';
import { getZoneStatus } from './utils/getZoneStatus.js';
export class YamahaPureDirectAccessory {
private baseApiUrl: AccessoryContext['device']['baseApiUrl'];
private service: Service;
constructor(
private readonly platform: YamahaAVRPlatform,
private readonly accessory: PlatformAccessory<AccessoryContext>,
) {
// set the AVR accessory information
this.accessory
.getService(this.platform.Service.AccessoryInformation)!
.setCharacteristic(this.platform.Characteristic.Manufacturer, 'Yamaha')
.setCharacteristic(this.platform.Characteristic.Model, this.accessory.context.device.modelName)
.setCharacteristic(this.platform.Characteristic.SerialNumber, this.accessory.context.device.systemId)
.setCharacteristic(
this.platform.Characteristic.FirmwareRevision,
`${this.accessory.context.device.firmwareVersion}`,
);
this.service = this.accessory.addService(this.platform.Service.Switch);
this.baseApiUrl = this.accessory.context.device.baseApiUrl;
this.init();
// regularly ping the AVR to keep power/input state syncronised
setInterval(this.updateState.bind(this), 5000);
}
async init() {
try {
await this.createService();
} catch (err) {
this.platform.log.error(err as string);
}
}
async createService() {
this.service
.getCharacteristic(this.platform.Characteristic.On)
.onGet(this.getState.bind(this))
.onSet(this.setState.bind(this));
}
async updateState() {
const zoneStatus = await getZoneStatus(this.platform, this.accessory, 'main');
if (!zoneStatus) {
return;
}
this.service.updateCharacteristic(this.platform.Characteristic.On, zoneStatus.pure_direct);
}
async getState(): Promise<CharacteristicValue> {
const zoneStatus = await getZoneStatus(this.platform, this.accessory, 'main');
if (!zoneStatus) {
return false;
}
return zoneStatus.pure_direct;
}
async setState(state: CharacteristicValue) {
try {
const setPureDirectResponse = await fetch(`${this.baseApiUrl}/${'main'}/setPureDirect?enable=${state}`);
const responseJson = (await setPureDirectResponse.json()) as BaseResponse;
if (responseJson.response_code !== 0) {
throw new Error('Failed to set pure direct');
}
} catch (error) {
this.platform.log.error((error as Error).message);
}
}
}