philips-hue-light-api
Version:
An API client for the Philips Hue API.
98 lines • 3.57 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const hue_fetch_client_1 = require("./utils/hue-fetch-client");
const index_1 = require("./index");
class Bridge {
constructor(ip, clientName) {
this._ip = ip;
this._clientName = clientName;
this._fetchClient = new hue_fetch_client_1.HueFetchClient(ip);
}
get apiKey() {
return this._apiKey;
}
async login(apiKey) {
if (apiKey) {
await this.loginViaApiKey(apiKey);
const isLoggedIn = await this.isLoggedIn();
if (!isLoggedIn) {
throw new Error('The API key is invalid.');
}
}
else {
await this.loginWithoutApiKey();
const isLoggedIn = await this.isLoggedIn();
if (!isLoggedIn) {
throw new Error('Error while logging in. Please try again.');
}
}
}
async getAllLights() {
if (!this._apiKey) {
throw new Error('You have to login first.');
}
const path = `/${this._apiKey}/lights`;
const response = await this._fetchClient.get(path);
if (response.error) {
throw new Error(response.error.description);
}
const lightbulbData = response.value;
const lightbulbIds = Object.keys(lightbulbData);
const lightbulbs = [];
for (const lightbulbId of lightbulbIds) {
const lightbulbName = lightbulbData[lightbulbId].name;
const lightbulb = new index_1.Lightbulb(this._ip, this._apiKey, lightbulbId, lightbulbName);
lightbulbs.push(lightbulb);
}
return lightbulbs;
}
async getAllGroups() {
if (!this._apiKey) {
throw new Error('You have to login first.');
}
const path = `/${this._apiKey}/groups`;
const response = await this._fetchClient.get(path);
if (response.error) {
throw new Error(response.error.description);
}
const lightbulbData = response.value;
const lightgroupIds = Object.keys(lightbulbData);
const lightgroups = [];
for (const lightgroupId of lightgroupIds) {
const lightgroupName = lightbulbData[lightgroupId].name;
const lightgroup = new index_1.Lightgroup(this._ip, this._apiKey, lightgroupId, lightgroupName);
lightgroups.push(lightgroup);
}
return lightgroups;
}
async getGroupByName(name) {
const lightgroups = await this.getAllGroups();
const searchedLightgroup = lightgroups.find((lightgroup) => lightgroup.name === name);
if (!searchedLightgroup) {
throw new Error(`Lightgroup with name ${name} not found.`);
}
return searchedLightgroup;
}
async isLoggedIn() {
const path = `/${this._apiKey}`;
const response = await this._fetchClient.get(path);
return !response.error;
}
async loginWithoutApiKey() {
const path = '/';
const body = JSON.stringify({
devicetype: `Hue-Api-Client#${this._clientName}`,
});
const options = { body: body };
const response = await this._fetchClient.post(path, options);
if (response.error) {
throw new Error(response.error.description);
}
this._apiKey = response.value[0].success.username;
}
async loginViaApiKey(apiKey) {
this._apiKey = apiKey;
}
}
exports.Bridge = Bridge;
//# sourceMappingURL=Bridge.js.map