Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //v13_14 альтернатиная мнемосхема_маскировка команд
- //v11++фото заголовки со ссылками
- "use strict";
- let hulla = new hullabaloo();
- let box = null;
- let circuit = null;
- let stlog = null;
- let dayly = null;
- let lastip = null;
- let lastmeter = null;
- //Антон: отображение команд с учетом маски
- let deviceObj = null;
- let dt = null, mdt = null;
- let liveMode = true;
- let renewTimer = null;
- let dtdt = null;
- let commands = null;
- var gallery_ro = true;
- let get = parseQuery(window.location.search);
- moment.locale(environment.language || window.navigator.userLanguage || window.navigator.language);
- $(async function () {
- $("#btnLive").prop("disabled", true);
- let result;
- let userTown;
- if (environment.login_name.indexOf("_") !== -1) {
- userTown = '&town=' + environment.login_name.split('_')[0].toLowerCase()
- } else {
- userTown = ''
- }
- try {
- result = await $.ajax({
- url: environment.base_url + "/" + '?do=api&fn=devices&id=' + get['id'] + userTown,
- type: 'GET',
- dataType: "json"
- });
- //Антон: отображение команд с учетом маски
- deviceObj = result;
- } catch (error) {
- console.error(error);
- $("#content").html("<h2>Device was not loaded</h2>");
- return;
- }
- if (result.rows.length > 0)
- box = result.rows.slice(0)[0];
- else {
- $("#content").html("<h2>Device not found</h2>");
- return;
- }
- if (box.DimProfile_id !== null) {
- try {
- dayly = await $.ajax({
- url: environment.base_url + "/" + '?do=api&fn=dimdetail&now&id=' + box.DimProfile_id,
- type: 'GET',
- dataType: "json"
- });
- } catch (error) {
- console.error(error);
- }
- }
- if (box.Type == 2)
- $("#strongState").text(i18next.t("Brightness"));
- drawBoxInfo();
- try {
- result = await $.ajax({
- url: environment.base_url + "/" + '?do=api&fn=circuit&id=' + get['id'],
- type: 'GET',
- dataType: "json"
- });
- } catch (error) {
- console.error(error);
- $("#content").html("<h2>Pattern was not loaded</h2>");
- return;
- }
- if (result.rows.length > 0)
- circuit = result.rows[0];
- else
- console.log("Pattern not found");
- let svg = "";
- if (circuit !== null) {
- let qs = circuit.qs;
- if (environment.language !== "en") {
- qs = qs.replace(/S/gi, "K");
- }
- try {
- svg = await $.ajax({
- url: environment.base_url + `/images/galbox.svg?v=${config.version}&noxml&cnf=` + qs,
- type: 'GET',
- processData: false
- });
- $("#circuit").html(`${svg}`);
- if (box.Name?.startsWith("TL") || box.Name?.startsWith("G")) await attachBackground();
- } catch (error) {
- console.error(error);
- }
- }
- stdatatable();
- meterdatatable();
- setTimeout(renew, 1);
- setTimeout(iprenew, 10);
- $("#circuit svg").addClass("col-12");
- $("#circuit svg").addClass("p-0");
- //Ссылки в зоголовках "статистика" и "журнал состояния" в форме Объект
- $("#statlink").attr("href", `${environment.base_url}/inlog?device=${get['id']}`);
- $("#stlink").attr("href", `${environment.base_url}/stlog?device=${get['id']}`);
- if (box.Smart) {
- try {
- result = await $.ajax({
- url: environment.base_url + "/" + '?do=api&fn=ServerCommand&type=1,3&DeviceType=' + box.Type,
- type: 'GET',
- dataType: "json"
- });
- } catch (error) {
- console.error(error);
- return;
- }
- commands = result.rows;
- $("#cmd").find('option').remove();
- for (let key in commands) {
- if (commands[key].Letter == "F")
- continue;
- $("#cmd").append($("<option></option>")
- .attr("value", commands[key].id)
- .text(i18next.t(commands[key].Name)));
- }
- } else {
- $("#manualDiv").hide();
- }
- //добавление картинки светильника из галлереи с проверкой её наличия, иначе - по умолчанию
- if (box.Type !== 1) {
- $.ajax({
- url: `${environment.base_url}/?do=api&fn=picture_list&Devices_id=${get['id']}&order=ASC&limit=1`,
- type: 'GET',
- dataType: "json",
- success: function (result) {
- if (result['list'].length > 0) {
- $("#circuit").html('<img class="img-fluid" src="' + result['list'][0].src + '">');
- } else {
- $("#circuit").html(`<img class="img-fluid" src="${environment.base_url}/images/lamp.png">`)
- }
- }
- });
- // $("#circuit").html(`<img class="img-fluid" src="${environment.base_url}/images/lamp.png">`);
- }
- $(".picture").click(() => {
- galleryOpen(get['id'])
- });
- /*
- let pl = await getPictureList(get['id'], 'desc', 100);
- if(pl.length == 0) {
- $(".picture").click( ()=>{galleryOpen(get['id'])});
- } else {
- let html="";
- let i=0;
- pl.forEach(el => {
- let title = "";
- let opt = {month: "long", day:"numeric", year:"numeric"};
- let separ=", ";
- let opt2= {hour:"numeric", minute:"numeric"};
- let disp="";
- if(el.Exiftime!==null) {
- let dda = el.Exiftime.split(" ");
- if(dda.length==2) {
- let dds = dda[0].replaceAll(":","-") + " " + dda[1]+"Z";
- let dd = new Date(dds);
- if(!(dd===NaN) && !dd!="Invalid Date") {
- disp = "<i class='fa fa-camera'></i> " + dd.toLocaleDateString(environment.language, opt) + separ +
- dd.toLocaleTimeString(environment.language, opt2);
- }
- }
- }
- let dd = new Date(el.Loaded+"Z");
- if(!(dd===NaN) && !dd!="Invalid Date") {
- if(disp!="")
- disp+="<br>";
- disp += "<i class='fa fa-upload'></i> " + dd.toLocaleDateString(environment.language, opt) + separ +
- dd.toLocaleTimeString(environment.language, opt2);
- }
- title = `data-container="body" data-html="true" data-placement="top" data-toggle="tooltip" title="${disp}"`;
- html += `<div ${title}><img onclick="galleryOpen(${get['id']}, ${i})" class="border border-primary rounded imgpic" width="60px" height="60px" src="${el.src}&thumb"></div>`;
- i++;
- });
- $("#pg").html(html);
- $('[data-toggle="tooltip"]').tooltip({
- boundary:"viewport",
- html: true
- });
- }
- */
- });
- async function runCmd() {
- $("#btnCmd").prop("disabled", true);
- setTimeout(() => $("#btnCmd").prop("disabled", false), 1500);
- let srvcmd = {};
- srvcmd.cmd = parseInt($("#cmd").val());
- let selcmd = commands.find(x => x.id == srvcmd.cmd);
- let cmdtext = i18next.t(selcmd.Name);
- srvcmd.devs = [box.id];
- let result = null;
- try {
- result = await $.ajax({
- url: environment.base_url + "/" + '?do=api&fn=makecalls',
- data: JSON.stringify(srvcmd),
- type: 'PUT',
- contentType: "application/json; charset=utf-8",
- dataType: "json"
- });
- } catch (error) {
- console.error(error);
- hulla.send(i18next.t("Device control error"));
- return false;
- }
- if (result.success) {
- switch (result.queued) {
- case 0:
- hulla.send(i18next.t("Command not queued"));
- break;
- case 1:
- hulla.send(`${i18next.t("Command")} "${cmdtext}" ${i18next.t("queued")}`, "success");
- break;
- default:
- hulla.send(`${cmdtext} - ${i18next.t("Command queued for multiple devices")} (${result.queued})`, "success");
- break;
- }
- } else {
- hulla.send(i18next.t("An error occurred while adding commands to the queue"));
- console.log(result);
- }
- return false;
- }
- let pbox = null, plines = null;
- async function drawBoxInfo() {
- $("#Phone").html(number10html(box.Phone));
- //Добавление строки "Серийный номер"
- for (let fld of ["CustomNum", "Name", "sn", "DimProfile_Name", "Station", "ControlTime"]) {
- let val = box[fld];
- if (val !== null) {
- if (fld == "ControlTime")
- $("#" + fld).text(val.substr(0, 5));
- else
- $("#" + fld).text(val);
- }
- }
- if (box.Station == null && box.Lines_id) {
- //let pbox =null, plines = null;
- try {
- pbox = await $.ajax({
- url: environment.base_url + "/" + '?do=api&fn=devices&id=' + box.Box_id,
- type: 'GET',
- dataType: "json"
- });
- } catch (error) {
- console.error(error);
- return;
- }
- try {
- plines = await $.ajax({
- url: environment.base_url + "/" + '?do=api&fn=lines&id=' + box.Box_id,
- type: 'GET',
- dataType: "json"
- });
- } catch (error) {
- console.error(error);
- return;
- }
- if (pbox && plines) {
- let ln = plines.rows.find(x => x.id == box.Lines_id)
- let txt = ln.Num.toString().padStart(2, "0") + ". " + i18next.t(appdata.LinesType.find(x => x.id == ln.Type).Name);
- if (ln.Switch > 0)
- txt += " " + i18next.t(appdata.Switches.find(x => x.id == ln.Switch).Name);
- if (ln.Phase > 0)
- txt += ", " + i18next.t("Phase") + " " + appdata.Phases.find(x => x.id == ln.Phase).Name;
- $("#Station").html(`<a target="obj${box.Box_id}" href="${environment.base_url}/obj?id=${box.Box_id}" id="aStation"></a>, ${txt}`);
- $("#aStation").text(`${i18next.t("Box")} № ${pbox.rows[0].CustomNum}`);
- }
- }
- $("#Mode").text(i18next.t(appdata.AutoModes.find(x => x.id == box.Mode).Name));
- $("#Location").text(makeAddress(box));
- $("#shiftdiv").hide();
- daylyTable();
- }
- function daylyTable() {
- if (dayly == null)
- return;
- let drw = dayly.rows;
- let aShift = null;
- if (box.PardShift)
- aShift = box.PardShift.split(",");
- let str1 = "<tr>", str2 = "<tr>", str3 = "<tr>";
- for (let i = 0; i < config.pard_maxvalue; i++) {
- let time = '', val = '';
- if (!(drw[i] === undefined)) {
- time = drw[i].Time.substr(0, 5);
- if (box.Type == 2) //lamp
- val = "" + drw[i].DimValue + "%";
- else
- val = SwitchStateForMask(drw[i].DimValue);//Антон: отображение команд с учетом маски
- }
- if (aShift) {
- let tt = '';
- if (aShift[i]) {
- let tti = parseInt(aShift[i]);
- let sign = "";
- if (tti < 0)
- sign = "-";
- if (tti > 0)
- sign = "+";
- tti = Math.abs(tti);
- let min = tti % 60;
- let hr = (tti - min) / 60;
- tt = `${sign}${new Intl.NumberFormat(environment.language, {minimumIntegerDigits: 2}).format(hr)}:${new Intl.NumberFormat(environment.language, {minimumIntegerDigits: 2}).format(min)}`;
- }
- str3 += `<td class="text-center">${tt}</td>`;
- }
- str1 += `<td class="text-center">${time}</td>`;
- str2 += `<td class="text-center">${val}</td>`;
- }
- str1 += "</tr>";
- str2 += "</tr>";
- $("#dimDetail").append(str1);
- if (aShift) {
- str3 += "</tr>";
- $("#dimDetail").append(str3);
- }
- $("#dimDetail").append(str2);
- }
- let loadfail = 0;
- async function dataload() {
- let url = environment.base_url + "/" + "?do=api&fn=stlog&limit=64&device=" + get['id'];
- let result, ret = false;
- try {
- result = await $.ajax({
- url: url,
- type: 'GET',
- dataType: "json",
- cache: false
- });
- } catch (error) {
- console.log("Error: ", error);
- if (error.status == 401) //unautorized
- window.location = environment.base_url + "/" + "?do=login&b=" + encodeURIComponent(window.location);
- loadfail++;
- if (stlog === null)
- $("#content").html("<h2>Log was not loaded</h2>");
- else if (loadfail > 1) {
- hulla.send(i18next.t(`No connection to the server (${error.statusText})`));
- loadfail = 0;
- }
- return ret;
- }
- loadfail = 0;
- if (stlog == null || stlog.timestamp != result.timestamp) {
- stlog = result;
- ret = true;
- }
- return ret;
- }
- async function ipload() {
- let url = environment.base_url + "/" + "?do=api&fn=lastip&device=" + get['id'];
- let result, ret = false;
- try {
- result = await $.ajax({
- url: url,
- type: 'GET',
- dataType: "json",
- });
- } catch (error) {
- console.log("Error: ", error);
- return ret;
- }
- if (lastip == null || lastip.timestamp != result.timestamp) {
- lastip = result;
- ret = true;
- }
- return ret;
- }
- async function meterload() {
- let url = environment.base_url + "/" + "?do=api&fn=lastmeter&device=" + get['id'];
- let result, ret = false;
- try {
- result = await $.ajax({
- url: url,
- type: 'GET',
- dataType: "json",
- });
- } catch (error) {
- console.log("Error: ", error);
- return ret;
- }
- if (lastmeter == null || result.timestamp != lastmeter.timestamp) {
- lastmeter = result;
- ret = true;
- }
- return ret;
- }
- async function renew() {
- // let nextt = 1000;
- // let isnew = await dataload();
- // if (isnew) {
- // onlogchane();
- // nextt = 2000;
- // }
- // setTimeout(renew, nextt);
- if (!liveMode) return;
- let nextt = 1000;
- const isnew = await dataload();
- if (isnew) {
- onlogchane();
- nextt = 2000;
- }
- renewTimer = setTimeout(renew, nextt);
- }
- async function iprenew() {
- let nextt = 1000;
- let isnew = await ipload();
- if (isnew) {
- if (lastip !== null && lastip.rowCount > 0) {
- let li = lastip.rows[0];
- let m = moment(li.unixtime * 1000);
- $("#iptime").text(m.format("L LT"));
- $("#ipdata").text(li.Msg);
- $("#divstat").show();
- } else
- $("#divstat").hide();
- let isnewmeter = await meterload();
- if (isnewmeter) {
- if (lastmeter !== null && lastmeter.rowCount > 0) {
- let lm = lastmeter.rows[0];
- let dd = new Date(lm.Timestamp + "Z");
- let disp = dd.toLocaleDateString(environment.language) + " " +
- dd.toLocaleTimeString(environment.language, {hour: "numeric", minute: "numeric"});
- $("#metertime").text(disp);
- $("#meterlink").attr("href", `${environment.base_url}/meterlog?device=${get['id']}`);
- //Открытие новой вкладки для "Показания учета"
- //$("#meterlink").attr("target", `meterlog${get['id']}`);
- mdt.ajax.reload();
- $("#meterstat").show();
- } else
- $("#meterstat").hide();
- }
- nextt = 5000;
- }
- setTimeout(iprenew, nextt);
- }
- async function onlogchane() {
- if (dt != null) {
- dt.ajax.reload();
- $('[data-toggle="tooltip"]').tooltip('dispose');
- $(".tooltip").remove();
- $('[data-toggle="tooltip"]').tooltip();
- }
- let result = null;
- try {
- result = await $.ajax({
- url: environment.base_url + "/" + "?do=api&fn=states&Devices_id=" + get['id'],
- type: 'GET',
- dataType: "json"
- });
- } catch (error) {
- console.error(error);
- }
- if (result !== null && result.rows.length > 0) {
- let state = result.rows[0];
- setSvgstate(state);
- setTextstate(state);
- }
- }
- function setTextstate(state) {
- let m = moment(state.unixtime * 1000);
- $("#StateTime").text(m.format("LT, L"));
- if (box.Type == 2)
- $("#SwState").text("" + state.State + "%");
- else
- $("#SwState").text(SwitchStateForMask(state.State));//Антон: отображение команд с учетом маски
- let mode = state.Mode == 4 ? "Manual" : "Auto";
- mode = i18next.t(mode);
- if (state.Mode == 1)
- mode += ", " + box.DimProfile_Name;
- $("#CurrentMode").text(mode);
- let door = i18next.t("Closed");
- if (!state.Door)
- door = '<span class="text-danger">' + i18next.t("Open") + "</span>";
- $("#DoorStatus").html(door);
- let sync = i18next.t("Synced");
- if (state.Ous)
- sync = '<span class="text-danger">' + i18next.t("Out of sync") + "</span>";
- $("#SyncStatus").html(sync);
- }
- function setSvgstate(state) {
- let onoff = SwitchState(state.State);
- const ruge = "#ecabab";
- const salat = "#abecab";
- const errorColor = state.Trouble == STATE_ERROR_UNKNOWN ? ruge : "red";
- const greenColor = state.Trouble == STATE_ERROR_UNKNOWN ? salat : "green";
- //const phasecolor = state.Power?"green":ruge;
- let aphst = [];
- for (let i = 0; i < 3; i++) {
- let plet = String.fromCharCode("A".charCodeAt() + i);
- let phst = state.Power & (1 << i);
- aphst[i] = phst;
- let phasecolor = phst ? greenColor : errorColor;
- $(`#phase_${plet}`).css("stroke", phasecolor);
- //V11
- $("#Volt" + i).text(plet);
- if (state.PhaseV) {
- let aVolt = JSON.parse(state.PhaseV);
- if (aVolt[i] !== null && aVolt[i] > 1)
- $("#Volt" + i).text(aVolt[i]);
- }
- }
- //$(".phase").css("stroke",phasecolor);
- // КОНТАКТОРЫ
- for (let i = 1; i <= 4; i++) {
- let swtrouble = state.Trouble & (1 << (i - 1)); //аварийность контактора
- let altsw = state.Trouble & (1 << (i + 27)); //альтернативное включение контактора
- let on = (onoff[i - 1] !== '0'); // значение управления on/off && aphst[0]; 20.07.21 - remove Phase A falsification
- // Команда на включение ON
- if (on) {
- $(`.S${i}_on`).attr("visibility", "visible"); //видимость состояния on
- $(`.S${i}_off`).attr("visibility", "hidden"); //скрыть состояние off
- $(`.S${i}_onoff`).attr("visibility", "hidden"); //скрыть состояние onoff
- $(`.S${i}_offon`).attr("visibility", "hidden"); //скрыть состояние offon
- let swc = "green";
- $(`#S${i}_rect1`).css("fill", "#AFEEEE"); // левый прямоугольник (голубой)
- $(`#S${i}_rect2`).css("fill", swc); // правый прямоугольник "зеленый"
- $(`#S${i}_tilda`).css("stroke", swc); //цвет контура синусоиды "зеленый"
- $(`#S${i}_tilda`).css("fill", swc); //цвет заполнения синусоиды "зеленый"
- $(`.fuse_S${i}`).css("fill", swc); //предохранители под напряжением "зеленые"
- //Отсутствие фазы «А»
- if (!aphst[0]) {
- $(`.S${i}_off`).attr("visibility", "hidden"); // не видимость контактора, как Off
- $(`.S${i}_on`).attr("visibility", "hidden"); //не видимость контактора, как ON
- $(`.S${i}_onoff`).attr("visibility", "visible"); //видимость состояния onoff
- $(`.S${i}_offon`).attr("visibility", "hidden"); //скрыть состояние offon
- swc = salat;
- $(`#S${i}_rect1`).css("fill", "#AFEEEE"); // левый прямоугольник "голубой"
- $(`#S${i}_rect2`).css("fill", swc); // правый прямоугольник "салатный"
- $(`#S${i}_tilda`).css("stroke", "white"); //белый синус
- $(`#S${i}_tilda`).css("fill", "white"); //белый синус
- $(`.fuse_S${i}`).css("fill", "white"); //предохранители "белые"
- if (altsw) { //если альтернативно-включенный контактор
- $(`.S${i}_onoff`).attr("visibility", "hidden"); //не видимость состояния onoff
- $(`.S${i}_offon`).attr("visibility", "visible"); //видимость состояния offon
- $(`#S${i}_rect2`).css("fill", "red"); // правый прямоугольник
- $(`.fuse_S${i}`).css("fill", "green"); //предохранители под напряжением "зеленые"_07_09
- }
- }
- //аварийность контактора
- if (swtrouble) {
- $(`.S${i}_onoff`).attr("visibility", "visible"); // видимость контактора, как onoff
- $(`.S${i}_offon`).attr("visibility", "hidden"); //скрыть состояние offon
- $(`.S${i}_off`).attr("visibility", "hidden"); // не видимость контактора, как Off
- $(`.S${i}_on`).attr("visibility", "hidden"); //не видимость включенного контактора
- $(`#S${i}_rect1`).css("fill", errorColor); // левый прямоугольник "красный"
- $(`#S${i}_rect2`).css("fill", salat); // правый прямоугольник "салатный"
- $(`#S${i}_tilda`).css("stroke", "white"); //белый синус
- $(`#S${i}_tilda`).css("fill", "white"); //белый синус
- $(`.fuse_S${i}`).css("fill", "white"); //предохранители "белые"
- }
- }
- // Команда на выключение OFF
- else {
- $(`.S${i}_on`).attr("visibility", "hidden"); //скрыть состояние ON
- $(`.S${i}_onoff`).attr("visibility", "hidden"); //скрыть состояние onoff
- $(`.S${i}_offon`).attr("visibility", "hidden"); //скрыть состояние offon
- $(`.S${i}_off`).attr("visibility", "visible"); //показать состояние OFF
- $(`#S${i}_rect2`).css("fill", "white"); // правый прямоугольник "белый"
- $(`#S${i}_rect1`).css("fill", "#AFEEEE"); // левый прямоугольник голубой
- $(`#S${i}_tilda`).css("stroke", "green"); //цвет контура синусоиды
- $(`#S${i}_tilda`).css("fill", "green"); //цвет заполнения синусоиды
- $(`.fuse_S${i}`).css("fill", "white"); //предохранители
- // Отсутствие фазы А
- if (!aphst[0]) {
- $(`#S${i}_tilda`).css("stroke", "white"); //белый синус
- $(`#S${i}_tilda`).css("fill", "white");
- } //белый синус
- // Авария контактора
- if (swtrouble) {
- $(`#S${i}_rect1`).css("fill", errorColor); // левый прямоугольник красный
- $(`#S${i}_tilda`).css("stroke", "white"); //белый синус
- $(`#S${i}_tilda`).css("fill", "white");
- } //белый синус
- // Альтернативное включение
- if (altsw) { //если есть альтернативно-включенный контактор
- $(`.S${i}_off`).attr("visibility", "hidden");
- $(`.S${i}_offon`).attr("visibility", "visible");
- $(`#S${i}_rect2`).css("fill", "red"); // правый прямоугольник красный
- $(`.fuse_S${i}`).css("green"); //предохранители под напряжением "зеленые"_07_09
- }
- }
- }
- //ПРЕДОХРАНИТЕЛИ
- for (let i = 0; i < 3; i++)
- if (!aphst[i])
- $(`.fuse_P${i}`).css("fill", "none");
- //V10__Отображение значений напряжения на линиях/предохранителях
- let volt = null;
- try {
- volt = JSON.parse(state.Voltage);
- } catch (e) {
- }
- //V11
- $('[id^="fuse_"]').find("title").remove();
- for (let i = 1; i <= 24; i++) {
- let ftrouble = state.Trouble & (1 << (i + 3));
- $(`.fuse_${i}_rect`).attr("visibility", "hidden"); //V14 Не видимость знака стрелок
- if (volt) {
- let fVolt = volt[i - 1];
- if (fVolt) {
- $(`#fuse_${i}_rect`).css("fill", "green");
- let titlestr = fVolt > 1 ? fVolt + "V" : "⚡";
- let title = document.createElementNS("http://www.w3.org/2000/svg", "title");
- title.textContent = titlestr;
- //V11
- $(`#fuse_${i}`).append(title);
- } else
- $(`#fuse_${i}_rect`).css("fill", "white");
- //V14 окраска встречки градиентом "зеленого" и символ "стрелки"
- if (ftrouble && fVolt) {
- $(`#fuse_${i}_rect`).css("fill", "url(#MyGradient)");
- $(`.fuse_${i}_rect`).attr("visibility", "visible"); // видимость знака стрелок
- }
- //V14 окраска пониженного напряжения градиентом2 "зеленого"
- if (fVolt < 180 && fVolt > 30) {
- $(`#fuse_${i}_rect`).css("fill", "url(#MyGradient2)");
- $(`.fuse_${i}_rect`).attr("visibility", "hidden"); // не видимость знака стрелок
- }
- if (ftrouble && !fVolt)
- $(`#fuse_${i}_rect`).css("fill", errorColor);
- }
- //else {
- //if(ftrouble)
- //$(`#fuse_${ i }_rect`).css("fill",errorColor);}
- }
- }
- function SwitchState(num) {
- if (num === null)
- return "-";
- num = Math.min(num, 0b1111);
- return num.toString(2).padStart("4", "0"); //For robot
- }
- //Антон: отображение команд с учетом маски
- function SwitchStateForMask(num) {
- if (num === null)
- return "-";
- let maskCommand = box ? box.Mask_Command : ''
- if (!maskCommand) {
- num = Math.min(num, 0b1111);
- return num.toString(2).padStart("4", "0");
- }
- let len = maskCommand ? maskCommand.length : 4;
- let binStr = num.toString(2).padStart(len, "0");
- let result = "";
- for (let i = 0; i < len; i++) {
- if (maskCommand[i] === "1") {
- result += binStr[i];
- }
- }
- return result;
- }
- function meterdatatable() {
- mdt = $('#meterlog').DataTable({
- "ajax": function (data, callback, settings) {
- let dt = [];
- if (lastmeter !== null)
- dt = lastmeter.rows;
- callback({data: dt});
- },
- "info": false,
- "rowId": "id",
- "language": datatables_locale,
- "paging": false,
- "ordering": false,
- "searching": false,
- "scrollX": true,
- "columns": [
- {
- "data": "Tag",
- render: function (data, type, row) {
- return i18next.t("msg_meter_" + data);
- }
- },
- {
- "data": "Value", className: 'text-right',
- render: function (data, type, row) {
- let tag = appdata.Meter[row.Tag];
- if (tag.type == "decimal") {
- let num = parseFloat(data);
- if (type == "export")
- return num;
- return Intl.NumberFormat(environment.language, {minimumFractionDigits: 3}).format(num);
- }
- return data;
- }
- },
- ],
- });
- mdt.on("draw", function () {
- $('[data-toggle="tooltip"]').tooltip();
- });
- mdt.on("init", function () {
- $('[data-toggle="tooltip"]').tooltip();
- });
- }
- function stdatatable() {
- dt = $('#stlog').DataTable({
- "ajax": function (data, callback, settings) {
- if (stlog !== null)
- callback({data: stlog.rows});
- },
- "info": false,
- "rowId": "id",
- "language": datatables_locale,
- "paging": false,
- "ordering": false,
- "searching": false,
- "scrollX": true,
- "scrollY": "27rem",
- "scrollCollapse": true,
- "deferRender": true,
- "columns": [
- {"data": "id", visible: false},
- {
- "data": "Timestamp",
- render: function (data, type, row) {
- if (type == "display") {
- let m = moment(row.unixtime * 1000);
- let td = moment();
- let fs = "L LT";
- if (td.isSame(m, 'd'))
- fs = "LT";
- let tz = row.tz.charAt(0) == "-" ? "" : "+" + row.tz;
- let stime = data + " " + tz;
- return `<span data-toggle="tooltip" title="${stime}">${m.format(fs)}</span>`;
- }
- return data;
- }
- },
- {
- "data": "Mode",
- render: function (data, type, row) {
- let strm = i18next.t("Unmanaged");
- if (row.Smart)
- strm = i18next.t(appdata.AutoModes.find(x => x.id == data).Name);
- return strm;
- }
- },
- {
- "data": "State",
- "className": "text-center", //Антон: центровка отображения команд с учетом маски
- render: function (data, type, row) {
- let str = data + "%";
- if (row.Type == 1) {//Box
- str = SwitchStateForMask(data);//Антон: отображение команд с учетом маски
- }
- return str;
- }
- },
- {
- "data": "Sip",
- "className": "text-center text-nowrap",
- render: function (data, type, row) {
- if (type == "display") {
- let ret = "";
- if (row.Power >= 7 || (row.Power && box.Type == 2))
- ret = `<span class="fa fa-plug text-success" data-toggle="tooltip" title="${i18next.t('Power Ok')}"></span> `;
- else {
- let title = i18next.t('Power Fail');
- title += " (" + reverseString(row.Power.toString(2).padStart(3, "0")) + ")";
- ret = `<span class="fa fa-plug text-danger" data-toggle="tooltip" title="${title}"></span> `;
- }
- if (!row.Trouble)
- ret += `<span class="fa fa-check-circle text-success" data-toggle="tooltip" title="${i18next.t('Facility is Ok')}"></span> `;
- else
- ret += `<span class="fa fa-exclamation-triangle text-danger" data-html="true" data-toggle="tooltip" title="${errDecode(row.Trouble, box.Type)}"></span> `;
- if (data)
- ret += `<span class="fa fa-phone-square text-success" data-toggle="tooltip" title="${i18next.t('SIP is Ok')}"></span> `;
- else
- ret += `<span class="fa fa-phone-square text-danger" data-toggle="tooltip" title="${i18next.t('SIP fault')}"></span> `;
- if (row.Ip)
- ret += `<span class="fa fa-wifi text-success" data-toggle="tooltip" title="${i18next.t('IP is Ok')}"></span> `;
- else
- ret += `<span class="fa fa-wifi text-danger" data-toggle="tooltip" title="${i18next.t('IP fault')}"></span> `;
- if (!row.Timeallert)
- ret += `<span class="fa fa-clock-o text-success" data-toggle="tooltip" title="${i18next.t('Clock is Ok')}"></span> `;
- else
- ret += `<span class="fa fa-clock-o text-danger" data-toggle="tooltip" title="${i18next.t('Clock error')}"></span> `;
- if (row.Controller)
- ret += `<span class="fa fa-microchip text-success" data-toggle="tooltip" title="${i18next.t('Controller is OK')}"></span> `;
- else
- ret += `<span class="fa fa-microchip text-danger" data-toggle="tooltip" title="${i18next.t('Controller error')}"></span> `;
- if (row.Door)
- ret += `<span class="fa fa-lock text-success" data-toggle="tooltip" title="${i18next.t('Case closed')}"></span> `;
- else
- ret += `<span class="fa fa-unlock text-danger" data-toggle="tooltip" title="${i18next.t('Case open')}"></span> `;
- if (row.Ous)
- ret += `<span class="fa fa-refresh text-danger" data-toggle="tooltip" title="${i18next.t('Out of sync')}"></span>`;
- else
- ret += `<span class="fa fa-refresh text-success" data-toggle="tooltip" title="${i18next.t('Synced')}"></span>`;
- return ret;
- }
- return data;
- }
- },
- {
- "data": "DimProfileName",
- "className": "text-nowrap",
- render: function (data, type, row) {
- let strd = "";
- let title = ""
- if (row.Smart) {
- if (!(row.IncomingLog_id === null)) {
- title = i18next.t("Notification");
- if (!(row.Status_name === null))
- strd = escapeQuote(i18next.t(row.Status_Name)) + " ";
- if (!(row.RemoteIP === null)) {
- strd = i18next.t("Statistics") + " ";
- title = "IP: " + row.RemoteIP;
- }
- strd += "(⇐)";
- if (type == "display")
- strd = `<span data-toggle="tooltip" title="${title}">${strd}</span>`;
- }
- if (!(row.OutgoingLog_id === null)) {
- strd = "⇒";
- strd = escapeQuote(i18next.t(row.Command_Name)) + " (" + strd + ")";
- if (row.IP_Name)
- strd = escapeQuote(i18next.t(row.IP_Name)) + ", " + strd;
- title = i18next.t("Command");
- if (type == "display")
- strd = `<span data-toggle="tooltip" title="${title}" class="text-${row.Hangupcause == 17 ? 'success' : 'danger'}">${strd}</span>`;
- }
- if (!(row.DimProfile_id === null)) {
- strd = data;
- title = i18next.t("Shedule");
- if (type == "display")
- strd = `<span data-toggle="tooltip" title="${title}"}">${strd}</span>`;
- }
- }
- return strd;
- }
- }
- ]
- });
- dt.on("draw", function () {
- $('[data-toggle="tooltip"]').tooltip();
- });
- dt.on("init", function () {
- $('[data-toggle="tooltip"]').tooltip();
- });
- $('#stlog tbody').on('click', 'tr', function () {
- const rowData = dt.row(this).data();
- if (!rowData) return;
- liveMode = false;
- clearTimeout(renewTimer);
- $("#btnLive").prop("disabled", false);
- setSvgstate(rowData);
- setTextstate(rowData);
- $(this).addClass('table-primary').siblings().removeClass('table-primary');
- });
- $('#btnLive').on('click', () => {
- if (stlog?.rows?.length) {
- if (liveMode) return;
- liveMode = true;
- $("#btnLive").prop("disabled", true);
- $('#stlog tbody tr').removeClass('table-primary');
- onlogchane();
- renew();
- }
- });
- }
- async function attachBackground() {
- const $svg = $("#circuit").children("svg");
- if (!$svg.length || $("#schemaWrapper").length) return;
- let typeCode = null;
- if (box.Name?.startsWith("TL")) typeCode = "TL";
- else if (box.Name?.startsWith("G")) typeCode = "G";
- let bgSrc = `${environment.base_url}/images/types/${typeCode || "default"}.png`;
- $svg.wrap(
- '<div id="schemaWrapper" ' +
- ' style="position:relative; display: flex;\n' +
- ' align-items: flex-end;\n' +
- ' justify-content: center;\n' +
- ' padding-bottom: 75px;margin-top: 5px;">' +
- "</div>"
- );
- $("#schemaWrapper").prepend(
- `<img id="schemaBg" ` +
- ` src="${bgSrc}" ` +
- ` style="position:absolute;top:-10px; bottom: 0;left:-3px;width:100%;` +
- ` height:100%; object-fit: contain;object-position: left;z-index:1;pointer-events:none;" />`
- );
- $svg.css({position: "relative", zIndex: 2, maxWidth: '60%', marginRight: '30%', marginBottom: '-70px'});
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement