generated from homebridge/homebridge-plugin-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
platform.ts
165 lines (114 loc) · 6.12 KB
/
platform.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
import { API, DynamicPlatformPlugin, Logger, PlatformAccessory, PlatformConfig, Service, Characteristic } from 'homebridge';
import { PLATFORM_NAME, PLUGIN_NAME } from './settings';
import { validate } from 'class-validator';
import { ConfigModel, ConfigModelAccessory, ConfigModelAccessoryType } from './config.model';
import { HomebridgeSwitchPlatformAccessory } from './accessories/switch.accessory';
const {createBluetooth} = require('node-ble')
/**
* HomebridgePlatform
* This class is the main constructor for your plugin, this is where you should
* parse the user config and discover/register accessories with Homebridge.
*/
export class BleHomebridgePlatform implements DynamicPlatformPlugin {
public readonly Service: typeof Service = this.api.hap.Service;
public readonly Characteristic: typeof Characteristic = this.api.hap.Characteristic;
public configModel: ConfigModel;
public bleDevices: any[] = [];
// this is used to track restored cached accessories
public readonly accessories: PlatformAccessory[] = [];
constructor(
public readonly log: Logger,
public readonly config: PlatformConfig,
public readonly api: API,
) {
this.log.debug('Finished initializing platform:', this.config.name);
// When this event is fired it means Homebridge has restored all cached accessories from disk.
// Dynamic Platform plugins should only register new accessories after this event was fired,
// in order to ensure they weren't added to homebridge already. This event can also be used
// to start discovery of new accessories.
this.api.on('didFinishLaunching', async () => {
log.debug('Executed didFinishLaunching callback');
// -----------------------------------------------------------------------
// Initialize and validate config
this.configModel = {...new ConfigModel, ...this.config};
const errors = await validate(this.configModel);
if (errors.length > 0) {
this.log.error('Config validation failed');
this.log.error(JSON.stringify(errors));
return;
}
// -----------------------------------------------------------------------
// Bluetooth
const processPerpheral = async (peripheral: any, accessory: ConfigModelAccessory) => {
// this.log.debug(`[CONNECTING] ble device ([SERVICE-ID: #${peripheral.advertisement.serviceUuids[0]}]) ${peripheral.address} (${peripheral.advertisement.localName}) ...`);
this.bleDevices.push({
accessory,
peripheral,
});
};
const {bluetooth, destroy} = createBluetooth();
const adapter = await bluetooth.defaultAdapter();
log.debug('Discovering devices ...');
if (! await adapter.isDiscovering())
await adapter.startDiscovery()
// while (true) {
// console.log(await adapter.devices());
// await new Promise(resolve => setTimeout(resolve, 1000));
// }
for (const accessory of this.configModel.accessories) {
log.info(`Waiting for ble device: ${accessory.deviceId}`);
const peripheral = await adapter.waitDevice(accessory.deviceId);
log.debug(`[FOUND] ble device: ${accessory.deviceId}`);
await processPerpheral(peripheral, accessory);
this.discoverDevices();
}
});
}
/**
* This function is invoked when homebridge restores cached accessories from disk at startup.
* It should be used to setup event handlers for characteristics and update respective values.
*/
configureAccessory(accessory: PlatformAccessory) {
this.log.info('Loading accessory from cache:', accessory.displayName);
// add the restored accessory to the accessories cache so we can track if it has already been registered
this.accessories.push(accessory);
}
/**
* This is an example method showing how to register discovered accessories.
* Accessories must only be registered once, previously created accessories
* must not be registered again to prevent "duplicate UUID" errors.
*/
discoverDevices() {
const accessories = this.configModel.accessories;
// this.api.unregisterPlatformAccessories(PLUGIN_NAME, PLATFORM_NAME, this.accessories);
// return;
for (const accessoryConfig of accessories) {
const uuid = this.api.hap.uuid.generate(accessoryConfig.serviceId);
// see if an accessory with the same uuid has already been registered and restored from
// the cached devices we stored in the `configureAccessory` method above
const existingAccessory = this.accessories.find(a => a.UUID === uuid);
// console.log(this.bleDevices.find(d => d.accessory.serviceId === accessoryConfig.serviceId));
if (existingAccessory) {
this.log.info('Loading existing accessory from cache:', existingAccessory.displayName);
// this.api.unregisterPlatformAccessories(PLUGIN_NAME, PLATFORM_NAME, [existingAccessory]);
new HomebridgeSwitchPlatformAccessory(this, existingAccessory, this.bleDevices.find(d => d.accessory.serviceId === accessoryConfig.serviceId));
} else {
// the accessory does not yet exist, so we need to create it
this.log.info('Adding new accessory:' + ` ${accessoryConfig.name} | ${uuid}`);
// create a new accessory
const accessory = new this.api.platformAccessory(accessoryConfig.name, uuid);
// store a copy of the device object in the `accessory.context`
// the `context` property can be used to store any data about the accessory you may need
accessory.context.config = accessoryConfig;
new HomebridgeSwitchPlatformAccessory(this, accessory, this.bleDevices.find(d => d.accessory.serviceId === accessoryConfig.serviceId));
// create the accessory handler for the newly create accessory
// this is imported from `platformAccessory.ts`
// switch (accessoryConfig.type) {
// case ConfigModelAccessoryType.switch: console.log('LOVE 2'); new HomebridgeSwitchPlatformAccessory(this, existingAccessory); break;
// }
// link the accessory to your platform
this.api.registerPlatformAccessories(PLUGIN_NAME, PLATFORM_NAME, [accessory]);
}
}
}
}