You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
102 lines
2.1 KiB
102 lines
2.1 KiB
import {randId} from "./random";
|
|
import {notNullish, nullish} from "./null";
|
|
import {fetchGet} from "./fetcher";
|
|
|
|
const localData = {};
|
|
const callbacks = [];
|
|
|
|
export function subscribeToLight(lightId, callback) {
|
|
const callbackId = randId();
|
|
|
|
callbacks.push({callbackId, lightId, callback});
|
|
|
|
if (lightId >= 0) {
|
|
if (notNullish(localData[lightId])) {
|
|
dispatch(localData[lightId]);
|
|
}
|
|
|
|
fetchOne(lightId);
|
|
} else {
|
|
const list = [];
|
|
for (let key in localData) {
|
|
if (localData.hasOwnProperty(key) && notNullish(localData[key])) {
|
|
list.push(localData[key]);
|
|
}
|
|
}
|
|
dispatch(list);
|
|
|
|
fetchAll();
|
|
}
|
|
}
|
|
|
|
export function unsubscribeFromLight(callbackId) {
|
|
const callback = callbacks.find(c => c !== null && c.callbackId === callbackId);
|
|
const index = callbacks.indexOf(callback);
|
|
callbacks[index] = null;
|
|
}
|
|
|
|
export function changeColor(lightId, newColor) {
|
|
console.dir(localData);
|
|
|
|
const light = localData[lightId];
|
|
if (nullish(light)) {
|
|
return;
|
|
}
|
|
|
|
localData[lightId].color = newColor;
|
|
dispatch(Object.values(localData));
|
|
|
|
// TODO: Send request
|
|
}
|
|
|
|
export function changeBrightness(lightId, newBrightness) {
|
|
|
|
}
|
|
|
|
function fetchAll() {
|
|
fetchGet(`/light/`).then(({data, error}) => {
|
|
if (error === null) {
|
|
handleLights(data);
|
|
}
|
|
});
|
|
}
|
|
|
|
function fetchOne(id) {
|
|
fetchGet(`/light/${id}`).then(({data, error}) => {
|
|
if (error === null) {
|
|
handleLight(data);
|
|
}
|
|
});
|
|
}
|
|
|
|
function handleLights(lights) {
|
|
lights.forEach(l => handleLight(l));
|
|
|
|
for (let key in localData) {
|
|
if (localData.hasOwnProperty(key) && nullish(lights.find(l => l.id === parseInt(key, 10)))) {
|
|
delete localData[key];
|
|
}
|
|
}
|
|
|
|
dispatch(lights);
|
|
}
|
|
|
|
function handleLight(light) {
|
|
localData[light.id] = light;
|
|
|
|
dispatch(light);
|
|
}
|
|
|
|
function dispatch(data) {
|
|
if (Array.isArray(data)) {
|
|
callbacks
|
|
.filter(c => c !== null)
|
|
.filter(c => c.lightId === -1)
|
|
.forEach(c => c.callback(data));
|
|
} else {
|
|
callbacks
|
|
.filter(c => c !== null)
|
|
.filter(c => c.lightId === data.id)
|
|
.forEach(c => c.callback(data));
|
|
}
|
|
}
|