EntertainmentApi.js
2.64 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
'use strict';
const ApiError = require('../../ApiError')
, EntertainmentStream = require('./EntertainmentStream')
, HueStreamMessage = require('./HueStreamMessage')
;
module.exports = class EntertainmentApi {
constructor(hueApi) {
this._hueApi = hueApi;
this._stream = null;
this._id = -1;
this.streamMessage = new HueStreamMessage();
//TODO validate that we have a valid Hue API configuration, i.e. the clientkey is present in the config.
}
start(id) {
const self = this
, hueApi = self._getHueApi()
, config = hueApi._getConfig()
;
return getEntertainmentGroup(hueApi, id)
.then(group => {
return hueApi.groups.enableStreaming(group.id);
})
.then(enabled => {
if (!enabled) {
throw new ApiError(`Failed to enable streaming for entertainment group: ${id}`);
}
const stream = new EntertainmentStream(config.hostname, config.username, config.clientkey);
self._setEntertainmentGroupId(id);
self._setStream(stream);
return stream.connect()
.then(() => {
return self; //TODO should be the message sending class instead
});
});
}
stop() {
const self = this
, stream = self._stream
;
if (stream) {
return self._closeStream()
.then(self._stopStreamOnGroup());
} else {
return self._stopStreamOnGroup();
}
}
sendRGB(lightsToRGB) {
const self = this
, stream = self._stream
, streamMessage = self.streamMessage
;
if (! stream) {
throw new ApiError('There is no current stream active, make sure you have started the streaming before calling this.');
}
return stream.send(streamMessage.rgbMessage(lightsToRGB));
}
_stopStreamOnGroup() {
const self = this
, id = self._id
, hueApi = self._hueApi
;
if (id > -1) {
return hueApi.groups.disableStreaming(id)
.finally(() => {
self._setEntertainmentGroupId(-1);
});
} else {
return Promise.resolve(true);
}
}
_closeStream() {
const self = this;
return this._stream.close()
.finally(() => {
self._setStream(null);
});
}
_setStream(stream) {
this._stream = stream;
}
_setEntertainmentGroupId(id) {
this._id = id;
}
_getHueApi() {
return this._hueApi;
}
};
function getEntertainmentGroup(api, id) {
return api.groups.get(id)
.then(group => {
if (group.type !== 'Entertainment') {
throw new ApiError(`The group with id ${id} is not a Entertainment Group it has a type of '${group.type}'`);
}
return group;
});
}