-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhomekit-bridge.js
More file actions
265 lines (236 loc) · 12.3 KB
/
Copy pathhomekit-bridge.js
File metadata and controls
265 lines (236 loc) · 12.3 KB
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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
'use strict';
// ─── SmartBus → HomeKit bridge ────────────────────────────────────────────────
// Standalone hap-nodejs bridge (NOT Homebridge — the NAS is a 32-bit box with
// ~700 MB RAM, so we skip the plugin framework and web UI entirely).
//
// Reads rooms/lights from the smartbus REST API, exposes each as a HomeKit
// Lightbulb (or Switch for appliance-type channels so Siri's "turn off the
// lights" won't touch the water heater), relays commands to POST /api/light,
// and follows the SSE stream so wall-panel/app changes update HomeKit push-
// style. Accessory list is read at startup — restart the bridge after adding
// or removing devices in the app.
//
// Config lives in data/homekit.json:
// { "apiBase": "http://127.0.0.1:3003", "token": "<device token>",
// "pincode": "942-71-836", "port": 51826, "username": "<auto-generated>" }
// HAP pairing state persists in data/hap/ — deleting it unpairs the bridge.
const http = require('http');
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const { Bridge, Accessory, Service, Characteristic, Categories, uuid, HAPStorage } =
require('hap-nodejs');
// Timestamp every log line — this process can die and be respawned by the
// server's watchdog, and "when" matters when reading the log afterwards.
for (const level of ['log', 'warn', 'error']) {
const orig = console[level].bind(console);
console[level] = (...args) => orig(new Date().toISOString(), ...args);
}
// ─── Config ───────────────────────────────────────────────────────────────────
const DATA_DIR = path.join(__dirname, 'data');
const CONFIG_FILE = path.join(DATA_DIR, 'homekit.json');
if (!fs.existsSync(CONFIG_FILE)) {
console.error(`[HomeKit] Missing ${CONFIG_FILE} — create it with { apiBase, token }`);
process.exit(1);
}
const config = JSON.parse(fs.readFileSync(CONFIG_FILE, 'utf8'));
if (!config.token) { console.error('[HomeKit] config needs a "token" (enrolled device token)'); process.exit(1); }
config.apiBase = config.apiBase || 'http://127.0.0.1:3003';
// One HomeKit bridge per floor. A single bridge caps out around 100 accessories
// (Apple's spec) and this home has 96 — pairing failed with kCountErr on one
// big bridge, so we split by floor (~30 each). config.bridges maps a group name
// to its stable HomeKit identity; each is generated once and persisted.
config.bridges = config.bridges || {};
const BASE_PORT = 51826;
function bridgeIdentity(group, index) {
if (!config.bridges[group]) {
const b = crypto.randomBytes(5);
const p = crypto.randomInt(100000000, 999999999).toString(); // 9 digits
config.bridges[group] = {
username: ['1A', ...[...b].map(x => x.toString(16).padStart(2, '0').toUpperCase())].join(':'),
pincode: `${p.slice(0,3)}-${p.slice(3,5)}-${p.slice(5,8)}`,
port: BASE_PORT + index,
};
fs.writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2));
}
return config.bridges[group];
}
HAPStorage.setCustomStoragePath(path.join(DATA_DIR, 'hap'));
// Same in-place rotation trick as server.js — restart.sh appends with >>
const LOG_FILE = path.join(__dirname, 'homekit.log');
function rotateLogIfNeeded() {
try {
const st = fs.statSync(LOG_FILE);
if (st.size < 2 * 1024 * 1024) return;
fs.copyFileSync(LOG_FILE, LOG_FILE + '.old');
fs.truncateSync(LOG_FILE, 0);
} catch {}
}
rotateLogIfNeeded();
setInterval(rotateLogIfNeeded, 6 * 3600 * 1000);
// ─── Tiny API client (token auth, JSON) ───────────────────────────────────────
function api(method, apiPath, body) {
return new Promise((resolve, reject) => {
const url = new URL(config.apiBase + apiPath);
const payload = body ? JSON.stringify(body) : null;
const req = http.request(url, {
method,
headers: {
'Authorization': `Bearer ${config.token}`,
...(payload ? { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(payload) } : {}),
},
}, (res) => {
let raw = '';
res.on('data', c => raw += c);
res.on('end', () => {
if (res.statusCode === 401) return reject(new Error('unauthorized — token revoked?'));
try { resolve(JSON.parse(raw)); } catch { resolve(null); }
});
});
req.on('error', reject);
if (payload) req.write(payload);
req.end();
});
}
// ─── State ────────────────────────────────────────────────────────────────────
const lightState = {}; // "subnet.device.channel" -> level
const characteristics = new Map(); // key -> On characteristic (for push updates)
const key = (s, d, c) => `${s}.${d}.${c}`;
// Appliance-ish types are exposed as Switch so they're excluded from Siri's
// blanket "lights" commands; everything else is a Lightbulb.
const SWITCH_TYPES = new Set(['water-heater', 'pump', 'ac', 'heater', 'fan', 'tv', 'socket', 'gate', 'other']);
// HomeKit only allows alphanumerics, spaces and apostrophes in names, and iOS
// can refuse accessories that violate this. "A/C" is the common offender in
// this home — turn it into "AC", then scrub anything else that's left.
function hapName(name) {
return String(name)
.replace(/\b([A-Za-z])\/([A-Za-z])\b/g, '$1$2') // A/C -> AC
.replace(/[^A-Za-z0-9' ]+/g, ' ')
.replace(/\s+/g, ' ')
.trim()
.replace(/^[^A-Za-z0-9]+|[^A-Za-z0-9]+$/g, '') || 'Device';
}
// ─── SSE listener — push state changes into HomeKit ──────────────────────────
function connectSSE() {
const url = new URL(`${config.apiBase}/api/events?token=${encodeURIComponent(config.token)}`);
const req = http.request(url, { method: 'GET', headers: { Accept: 'text/event-stream' } }, (res) => {
if (res.statusCode !== 200) {
console.error(`[HomeKit] SSE rejected (${res.statusCode}) — retrying in 30s`);
res.resume();
setTimeout(connectSSE, 30000);
return;
}
console.log('[HomeKit] SSE connected — live state sync active');
let buf = '';
res.on('data', chunk => {
buf += chunk;
let idx;
while ((idx = buf.indexOf('\n\n')) >= 0) {
const frame = buf.slice(0, idx); buf = buf.slice(idx + 2);
const line = frame.split('\n').find(l => l.startsWith('data: '));
if (!line) continue;
try { handleEvent(JSON.parse(line.slice(6))); } catch {}
}
});
res.on('end', () => { console.warn('[HomeKit] SSE closed — reconnecting in 5s'); setTimeout(connectSSE, 5000); });
});
req.on('error', (e) => { console.warn(`[HomeKit] SSE error: ${e.message} — retrying in 10s`); setTimeout(connectSSE, 10000); });
req.end();
}
function handleEvent(msg) {
if (msg.type === 'init' && msg.lightState) {
Object.assign(lightState, msg.lightState);
for (const [k, ch] of characteristics) ch.updateValue((lightState[k] || 0) > 0);
} else if (msg.type === 'lightState') {
lightState[msg.key] = msg.level;
const ch = characteristics.get(msg.key);
if (ch) {
ch.updateValue(msg.level > 0);
console.log(`[HomeKit] State sync: ${msg.key} -> ${msg.level > 0 ? 'ON' : 'OFF'}`);
}
}
}
// Build one Accessory for a single light/channel, registering its On
// characteristic in the global map so SSE updates reach it.
function buildAccessory(room, l, nameCount) {
const k = key(l.subnet, l.device, l.channel);
const name = hapName(nameCount[l.name] > 1 ? `${room.name} ${l.name}` : l.name);
const acc = new Accessory(name, uuid.generate(`smartbus:light:${k}`));
acc.getService(Service.AccessoryInformation)
.setCharacteristic(Characteristic.Manufacturer, 'SmartBus G4')
.setCharacteristic(Characteristic.Model, l.type || 'relay')
.setCharacteristic(Characteristic.SerialNumber, k);
const svc = SWITCH_TYPES.has(l.type) ? new Service.Switch(name) : new Service.Lightbulb(name);
svc.getCharacteristic(Characteristic.On)
.onGet(() => (lightState[k] || 0) > 0)
.onSet(async (on) => {
try {
await api('POST', '/api/light',
{ subnet: l.subnet, device: l.device, channel: l.channel, level: on ? 100 : 0 });
lightState[k] = on ? 100 : 0;
} catch (e) {
console.error(`[HomeKit] Command failed for ${name}: ${e.message}`);
throw new (require('hap-nodejs').HapStatusError)(-70402 /* SERVICE_COMMUNICATION_FAILURE */);
}
});
acc.addService(svc);
characteristics.set(k, svc.getCharacteristic(Characteristic.On));
return acc;
}
// ─── Build & publish one bridge per floor ─────────────────────────────────────
async function main() {
const rooms = await api('GET', '/api/rooms');
const floors = await api('GET', '/api/floors');
const state = await api('GET', '/api/state');
if (!Array.isArray(rooms)) throw new Error('could not load rooms — check apiBase/token');
Object.assign(lightState, state || {});
// Duplicate light names across rooms get the room name prefixed
const nameCount = {};
for (const room of rooms)
for (const l of (room.lights || []))
nameCount[l.name] = (nameCount[l.name] || 0) + 1;
// Group rooms by floor, in floor order, with a trailing "Other" for any
// rooms not assigned to a floor. Each group becomes its own HomeKit bridge.
const floorName = {}; (floors || []).forEach(f => floorName[f.id] = f.name);
const groups = new Map(); // group label -> [rooms]
for (const f of (floors || [])) groups.set(f.name, []);
for (const room of rooms) {
const label = floorName[room.floorId] || 'Other';
if (!groups.has(label)) groups.set(label, []);
groups.get(label).push(room);
}
let index = 0, published = 0;
const summary = [];
for (const [label, groupRooms] of groups) {
const lights = groupRooms.flatMap(r => (r.lights || []).map(l => ({ room: r, l })));
if (lights.length === 0) continue;
const id = bridgeIdentity(label, index++);
const bridge = new Bridge(`SmartBus ${label}`, uuid.generate(`smartbus:bridge:${label}`));
bridge.getService(Service.AccessoryInformation)
.setCharacteristic(Characteristic.Manufacturer, 'SmartBus G4')
.setCharacteristic(Characteristic.Model, 'SmartGate Bridge')
.setCharacteristic(Characteristic.SerialNumber, id.username);
for (const { room, l } of lights) bridge.addBridgedAccessory(buildAccessory(room, l, nameCount));
await bridge.publish({
username: id.username,
pincode: id.pincode,
port: id.port,
category: Categories.BRIDGE,
});
published++;
summary.push({ label, count: lights.length, pincode: id.pincode, port: id.port });
console.log(`[HomeKit] Published "SmartBus ${label}": ${lights.length} accessories · code ${id.pincode} · port ${id.port}`);
}
if (published === 0) throw new Error('no accessories to publish');
console.log(`[HomeKit] ${published} bridge(s) live. Pair each separately in the Home app:`);
for (const s of summary) console.log(`[HomeKit] SmartBus ${s.label} → ${s.pincode}`);
connectSSE();
// Safety net: re-sync full state every 5 minutes in case SSE missed anything
setInterval(async () => {
try {
const s = await api('GET', '/api/state');
if (s) handleEvent({ type: 'init', lightState: s });
} catch {}
}, 5 * 60 * 1000);
}
main().catch(e => { console.error('[HomeKit] Fatal:', e.message); process.exit(1); });