var bg = document.getElementById("display_background");
var text = document.getElementById("image_background_text");
var lastValue = null;
var lastContrast = null;
var TOKEN = ubidots.token;
var VAR_ID_LV = "id-of-variable-to-be-displayed";
var VAR_ID_CONTRAST = "id-of-contrast-variable";
var scale = d3.scaleLinear().range([0, 4]).domain([0, 1023]);
setInterval(function () {
// Get LCD Screen last value
getLastValue(VAR_ID_LV, TOKEN, function (res) {
var value = null;
try {
value = res.results[0].value;
} catch (e) {
console.log("No data");
}
if (
(lastValue === null || value !== lastValue) &&
value !== null
) {
text.textContent = value;
lastValue = value;
}
});
// Get LCD Screen contrast
getLastValue(VAR_ID_CONTRAST, TOKEN, function (res) {
var value = null;
try {
value = res.results[0].value;
} catch (e) {
console.log("No data");
}
if (
(lastContrast === null || value !== lastContrast) &&
value !== null
) {
bg.style.filter = "contrast(" + scale(value) + ")";
lastContrast = value;
}
});
}, 2000);
function makeHttpRequest(method, url, headers, payload) {
return new Promise(function (resolve, reject) {
var options = {
method: method,
headers: headers,
};
if (payload) {
options.body = JSON.stringify(payload);
}
fetch(url, options)
.then(function (response) {
if (!response.ok) {
throw new Error(response.statusText);
}
return response.json();
})
.then(function (data) {
resolve(data);
})
.catch(function (error) {
reject(error);
});
});
}
function getLastValue(variableId, token, cb) {
var url =
"https://industrial.api.ubidots.com/api/v1.6/variables/" +
variableId +
"/values";
var headers = {
"X-Auth-Token": token,
"Content-Type": "application/json",
};
makeHttpRequest("GET", url + "?page_size=1", headers)
.then(function (res) {
if (typeof cb === "function") cb(res);
})
.catch(function (error) {
console.error(error);
});
}