-
Notifications
You must be signed in to change notification settings - Fork 145
/
discoverAndCreateUserScript.js
59 lines (48 loc) · 2.42 KB
/
discoverAndCreateUserScript.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
const v3 = require('../../dist/cjs').v3
, discovery = require('../../dist/cjs').discovery
// If using this code outside of the examples directory, you will want to use the line below and remove the
// const v3 = require('node-hue-api').v3
// const discovery = require('node-hue-api').discovery
, hueApi = v3.api
;
const appName = 'node-hue-api';
const deviceName = 'example-code';
async function discoverBridge() {
const discoveryResults = await discovery.nupnpSearch();
if (discoveryResults.length === 0) {
console.error('Failed to resolve any Hue Bridges');
return null;
} else {
// Ignoring that you could have more than one Hue Bridge on a network as this is unlikely in 99.9% of users situations
return discoveryResults[0].ipaddress;
}
}
async function discoverAndCreateUser() {
const ipAddress = await discoverBridge();
// Create an unauthenticated instance of the Hue API so that we can create a new user
const unauthenticatedApi = await hueApi.createLocal(ipAddress).connect();
let createdUser;
try {
createdUser = await unauthenticatedApi.users.createUser(appName, deviceName);
console.log('*******************************************************************************\n');
console.log('User has been created on the Hue Bridge. The following username can be used to\n' +
'authenticate with the Bridge and provide full local access to the Hue Bridge.\n' +
'YOU SHOULD TREAT THIS LIKE A PASSWORD\n');
console.log(`Hue Bridge User: ${createdUser.username}`);
console.log(`Hue Bridge User Client Key: ${createdUser.clientkey}`);
console.log('*******************************************************************************\n');
// Create a new API instance that is authenticated with the new user we created
const authenticatedApi = await hueApi.createLocal(ipAddress).connect(createdUser.username);
// Do something with the authenticated user/api
const bridgeConfig = await authenticatedApi.configuration.getConfiguration();
console.log(`Connected to Hue Bridge: ${bridgeConfig.name} :: ${bridgeConfig.ipaddress}`);
} catch(err) {
if (err.getHueErrorType() === 101) {
console.error('The Link button on the bridge was not pressed. Please press the Link button and try again.');
} else {
console.error(`Unexpected Error: ${err.message}`);
}
}
}
// Invoke the discovery and create user code
discoverAndCreateUser();