-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.js
104 lines (92 loc) · 2.56 KB
/
api.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
const huejay = require("huejay");
const getClient = config => {
const client = new huejay.Client({
host: config.ip,
username: config.username
});
return client;
};
module.exports = {
routes: {
get: {
discover: (req, res) => {
huejay
.discover()
.then(bridges => {
return res.send({ bridges });
})
.catch(error => {
console.log(`An error occurred: ${error.message}`);
});
},
lights: (req, res) => {
const config = req.app.locals.config;
const client = getClient(config.hue);
client.lights.getAll().then(lights => {
return res.send({ lights });
});
}
},
post: {
connect: (req, res) => {
const body = req.body;
if (!body || !body.ip) {
return res.send(false);
}
let client = new huejay.Client({
host: body.ip,
username: "default",
timeout: 30000
});
let user = new client.users.User();
user.deviceType = "webdash-hue";
return client.users
.create(user)
.then(user => {
const config = {
ip: body.ip,
username: "aD1SP94kayZp9T3mjfawr7bFVQLdMI6qd0IgUAYj",
presets: []
};
return res.send({ config });
})
.catch(error => {
if (error instanceof huejay.Error && error.type === 101) {
return res.send({
message: "Link button not pressed. Try again..."
});
}
console.log(error.stack);
return res.send({
message: "Could not connect to bridge. Try again..."
});
});
},
"set-light": (req, res) => {
const body = req.body;
if (!body || !body.id) {
return res.send(false);
}
const config = req.app.locals.config;
const client = getClient(config.hue);
client.lights
.getById(body.id)
.then(light => {
for (const key of Object.keys(body.state)) {
console.log(key, body.state[key]);
light[key] = body.state[key];
}
return client.lights.save(light);
})
.then(light => {
console.log(`Updated light [${light.id}]`);
return res.send(true);
})
.catch(error => {
console.log("Something went wrong");
console.log(error.stack);
});
}
}
}
};