You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

89 lines
2.4 KiB
JavaScript

const { HA_URL, TOKEN, TRANSITION_DURATION_DIVIDER } = require("./env.js");
11 months ago
const { sleep } = require("./util.js");
const latest_color = require("./latest_color.js");
const { lights } = require("./config.js");
async function send_color(
light_data,
color,
max_brightness,
duration = 0.18,
debug = false
) {
11 months ago
const brightness = (color[0] + color[1] + color[2]) / 3 / 255;
11 months ago
if (debug) {
11 months ago
console.log({
light_data,
sum: color[0] + color[1] + color[2],
brightness,
});
11 months ago
}
11 months ago
let body = { entity_id: `light.${light_data.id}`, transition: 0.18 };
if (light_data.type == "rgb") {
body.rgb_color = color;
11 months ago
body.brightness = Math.floor(Math.max(...color) * max_brightness);
11 months ago
} else {
// body.brightness = Math.max(1, Math.round(255 * brightness)); // 0 seems to turn it off and make it slower to react
11 months ago
body.brightness = Math.floor(Math.max(...color) * max_brightness);
11 months ago
}
11 months ago
if (debug) {
console.log("sending", body);
}
11 months ago
return fetch(`${HA_URL}/api/services/light/turn_on`, {
method: "POST",
headers: {
Authorization: `Bearer ${TOKEN}`,
"Content-Type": "application/x-www-form-urlencoded",
},
body: JSON.stringify(body),
}).then(async (response) => {
if (debug) {
console.log(await response.text());
}
});
}
module.exports = async function light_loop(light_index, max_brightness, debug) {
10 months ago
light_index = parseInt(light_index);
let duration = 0.18; // 180ms - the default for start, will be adjusted later based on how long did the http request take
11 months ago
let last_color = [0, 0, 0];
while (true) {
last_time = Date.now();
const from = 3 * light_index;
10 months ago
const to = 3 * (light_index + 1);
11 months ago
const current_color = latest_color.get().slice(from, to);
let is_changed = false;
for (i in last_color) {
11 months ago
if (last_color[i] != current_color[i]) {
11 months ago
is_changed = true;
break;
}
}
if (is_changed) {
if (debug) {
console.time(`light ${light_index} http request took`);
}
const before = Date.now();
11 months ago
await send_color(
lights[light_index],
current_color,
max_brightness,
duration,
11 months ago
debug
);
const after = Date.now();
duration = (after - before) / 1000 / TRANSITION_DURATION_DIVIDER;
if (debug) {
console.timeEnd(`light ${light_index} http request took`);
}
11 months ago
last_color = current_color;
} else {
await sleep(10);
}
}
};