-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcli.js
executable file
·243 lines (211 loc) · 7.15 KB
/
cli.js
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
#!/usr/bin/env node
const cliSelect = require("cli-select");
const cliProgress = require("cli-progress");
const commandLineArgs = require("command-line-args");
const commandLineUsage = require("command-line-usage");
const readline = require("readline");
const optionDefinitions = [
{
name: "discoverTime",
alias: "t",
type: Number,
defaultValue: 30,
typeLabel: "{underline number} in s",
description: "Time the device discovery runs in seconds",
},
{
name: "interface",
alias: "i",
type: String,
typeLabel: "{underline string}",
description: "Name of the network device to listen for HomeKit items. For example: {italic wlan0}",
},
{
name: "help",
alias: "h",
type: Boolean,
description: "Print this usage guide.",
},
];
const options = commandLineArgs(optionDefinitions);
if (options.help !== undefined) {
const sections = [
{
header: "HomeKit Device Discovery",
content: "Discovers available HomeKit devices on a network, pairs with them and writes the neccesary pairing-information into a file.",
},
{
header: "Options",
optionList: optionDefinitions,
},
];
const usage = commandLineUsage(sections);
console.log(usage);
process.exit(0);
}
(async () => {
const { IPDiscovery, HttpClient } = require("hap-controller");
const fs = require("fs");
const discover = () =>
new Promise((resolve, reject) => {
console.clear();
console.log("HomekitControl Device Discovery");
console.log("-------------------------------\n\n");
//term.clear()
const ipDiscovery = new IPDiscovery(options.interface);
const discoveryTimeout = options.discoverTime;
const services = [];
ipDiscovery.on("serviceUp", (service) => {
services.push(service);
});
ipDiscovery.start();
let discoveryTime = 0;
const progressBar = new cliProgress.SingleBar(
{
format: "Discovering Homekit Accessories | {bar} | {percentage}% | ETA: {eta}s",
hideCursor: false,
},
cliProgress.Presets.rect,
);
progressBar.start(100, 0);
const discoveryInterval = setInterval(() => {
discoveryTime++;
progressBar.update((discoveryTime / discoveryTimeout) * 100);
if (discoveryTime >= discoveryTimeout) {
progressBar.stop();
clearInterval(discoveryInterval);
ipDiscovery.stop();
resolve(services);
}
}, 1000);
});
const services = await discover();
if (services.length === 0) {
console.error("No Devices were found!!");
process.exit();
}
const selectService = (services) =>
new Promise((resolve, reject) => {
console.log("\n\n");
console.log("Please select a Device for pairing:");
const serviceMenuItems = services.map((service) => `${service.name} (${service.id})`);
serviceMenuItems.push("[CANCEL]");
cliSelect(
{
values: serviceMenuItems,
indentation: 2,
},
(response) => {
if (response.id === serviceMenuItems.length - 1) {
resolve(null);
}
const service = services[response.id];
resolve(service);
},
);
});
const service = await selectService(services);
if (service === null) {
console.log("Operation Cancled!");
process.exit(0);
}
const errorCallback = (error) => {
console.log("\n\n-------------------------------\n");
console.log(`\u274C ${error?.message}`);
if (error?.message?.includes("M2: Error: 6")) {
console.error(`\u27A1 Check how to fix the (M2: Error 6) here:\n https://github.com/minamoanes/homebridge-homekit-control#how-to-fix-known-errors`);
} else if (!error?.message?.includes("Invalid Pin")) {
console.error(`\u27A1 For further support check the Repo documentation or open an issue:\n https://github.com/minamoanes/homebridge-homekit-control`);
}
console.log("\n-------------------------------\n\n");
process.exit(1);
};
const pairService = (service) =>
new Promise((resolve, reject) => {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
console.clear();
rl.question(`Enter PIN for ${service.name} (XXX-XX-XXX or XXXX-XXXX or XXXXXXXX): `, async (pin) => {
const pinex = /(\d{3})-(\d{2})-(\d{3})|(\d{4})-(\d{4})|(\d{8})/;
const m = ((pin || "").match(pinex) || []).filter((e) => e !== undefined);
if (m.length === 4) {
pin = m[0];
} else if (m.length === 3 || m.length === 2) {
const p = m.length === 3 ? m[1] + m[2] : m[0];
pin = [p.slice(0, 3), p.slice(3, 5), p.slice(5, 8)].join("-");
} else {
return errorCallback(new Error("Invalid Pin: " + pin));
}
console.log(`Pin: ${pin}`);
rl.close();
try {
const discovery = new IPDiscovery();
const pairMethod = await discovery.getPairMethod(service);
const ipClient = new HttpClient(service.id, service.address, service.port);
await ipClient.pairSetup(pin, pairMethod);
return resolve(ipClient);
} catch (error) {
return errorCallback(error);
}
});
});
const saveServiceData = (service, client) =>
new Promise((resolve, reject) => {
console.log("\n\n");
const pairingData = client.getLongTermData();
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
rl.question(`Enter service data file name for saving: `, async (file) => {
console.log("Creating file:", file);
const accessories = await client.getAccessories();
const data = {
id: service.id,
name: service.name,
address: service.address,
port: service.port,
enableHistory: false,
pairingData,
accessories,
};
rl.close();
fs.writeFileSync(file, JSON.stringify(data, null, 4));
resolve(data);
});
rl.write(`${service.id}.json`.replace(/:/g, "-"));
// const pairingData = client.getLongTermData()
// term('Enter service data file name for saving: ')
// term.inputField(
// {
// default: `${service.id}.json`.replace(/:/g, '-'),
// },
// async (error, input) => {
// const accessories = await client.getAccessories()
// const data = {
// id: service.id,
// name: service.name,
// address: service.address,
// port: service.port,
// enableHistory: false,
// pairingData,
// accessories,
// }
// fs.writeFileSync(input, JSON.stringify(data, null, 4))
// resolve(data)
// }
// )
});
try {
const client = await pairService(service);
const data = await saveServiceData(service, client);
console.log("\n\n");
console.log("Paired with Service:");
console.log(data);
process.exit();
} catch (error) {
errorCallback(error);
}
})();