From 27d3345c1a411beefde624732532eafe29ea42b3 Mon Sep 17 00:00:00 2001 From: knowthelist Date: Fri, 19 Jan 2018 22:31:29 +0100 Subject: [PATCH] Reactivated old kind of template function --- README.md | 2 +- www/tablet/js/fhem-tablet-ui.js | 41 ++++++++++++++++++++++------- www/tablet/js/fhem-tablet-ui.min.js | 2 +- 3 files changed, 34 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index acc07a99..b0004a21 100755 --- a/README.md +++ b/README.md @@ -330,7 +330,7 @@ See [examples](#label) of Label - **data-set** : name of the reading to set on FHEM (\ \ **\** \) (default '') - **data-cmd** : name of the command to send to FHEM (**\** \ \ \) (e.g. setstate, set, setreading, trigger) default: 'set' - **data-value**: default value -- **class** : wider, w1x, w2x, w3x, large, big, notransmit +- **class** : wider, w1x, w2x, w3x, large, big, notransmit, autoclear, autoselect data-device, data-get can be references (jQuery seletor) to select-widgets to change the source dynamically diff --git a/www/tablet/js/fhem-tablet-ui.js b/www/tablet/js/fhem-tablet-ui.js index 76263d5e..dfc72af2 100755 --- a/www/tablet/js/fhem-tablet-ui.js +++ b/www/tablet/js/fhem-tablet-ui.js @@ -2,7 +2,7 @@ /** * UI builder framework for FHEM * - * Version: 2.6.37 + * Version: 2.6.-37 * * Copyright (c) 2015-2017 Mario Stephan * Under MIT License (http://www.opensource.org/licenses/mit-license.php) @@ -187,6 +187,7 @@ var Modul_widget = function () { elem.text(me.widgetname); } + function reinit() {} function init() { ftui.log(1, "init widget: name=" + me.widgetname + " area=" + me.area); @@ -240,6 +241,7 @@ var Modul_widget = function () { widgetname: 'widget', area: '', init: init, + reinit: reinit, init_attr: init_attr, init_ui: init_ui, update: update, @@ -318,6 +320,15 @@ var plugins = { ftui.log(1, 'Load plugin "' + name + '" for area "' + area + '"'); return ftui.loadPlugin(name, area); }, + + reinit: function () { + $.each(this.modules, function (index, module) { + //Iterate each module and run update function if module is available + if (typeof module === 'object') { + module.reinit(); + } + }); + }, update: function (dev, par) { @@ -338,7 +349,7 @@ var plugins = { var ftui = { - version: '2.6.37', + version: '2.6.-37', config: { DEBUG: false, DEMO: false, @@ -703,15 +714,27 @@ var ftui = { ftui.initGridster(area); - //convert from template to include - $('[data-template]', area).each(function (index) { - var elem = $(this); - elem.attr('data-type', 'include'); - elem.attr('data-url', elem.data('template')); - elem.removeAttr('data-template'); + //include extern html code + var deferredArr = $.map($('[data-template]', area), function (templ, i) { + var templElem = $(templ); + return $.get( + templElem.data('template'), {}, + function (data) { + var parValues = templElem.data('parameter'); + for (var key in parValues) { + data = data.replace(new RegExp(key, 'g'), parValues[key]); + } + templElem.html(data); + } + ); }); - ftui.initWidgets(area); + //get current values of readings not before all widgets are loaded + $.when.apply(this, deferredArr).then(function () { + //continue after loading the includes + ftui.initWidgets(area); + ftui.log(1, 'init templates - Done'); + }); }, initWidgets: function (area) { diff --git a/www/tablet/js/fhem-tablet-ui.min.js b/www/tablet/js/fhem-tablet-ui.min.js index 3b2f0778..ff812ccb 100755 --- a/www/tablet/js/fhem-tablet-ui.min.js +++ b/www/tablet/js/fhem-tablet-ui.min.js @@ -1 +1 @@ -"use strict";function onjQueryLoaded(){ftui.init(),$(".menu").on("click",function(){$(".menu").toggleClass("show")}),$(window).on("beforeunload",function(){ftui.log(5,"beforeunload"),ftui.setOffline()}),$(window).on("online offline",function(){ftui.log(5,"online offline"),navigator.onLine?ftui.setOnline():ftui.setOffline()}),window.onerror=function(t,e,i,n,o){var a=e.split("/").pop();return ftui.toast([a+":"+i,o].join("
"),"error"),!1},$.fn.once=function(t,e){return this.each(function(){$(this).off(t).on(t,e)})},$.fn.widgetId=function(){return["ftui",$(this).data("type"),$(this).data("device").replace(" ","default"),$(this).data("get"),$(this).index()].join("_")},$.fn.wgid=function(){var t=$(this);if(!t.isValidData("wgid")){var e=t.data("type")+"_xxxx-xxxx-xxxx".replace(/[xy]/g,function(t){var e=16*Math.random()|0;return("x"==t?e:3&e|8).toString(16)});t.attr("data-wgid",e)}return t.data("wgid")},$.fn.filterData=function(t,e){return this.filter(function(){return $(this).data(t)==e})},$.fn.filterDeviceReading=function(t,e,i){return $(this).filter(function(){var n=$(this),o=n.data(t);return String(o)===i&&String(n.data("device"))===e||o===e+":"+i||o==="["+e+":"+i+"]"||$.inArray(i,o)>-1&&String(n.data("device"))===e||$.inArray(e+":"+i,o)>-1})},$.fn.isValidData=function(t){return void 0!==$(this).data(t)},$.fn.initData=function(t,e){var i=$(this);return i.data(t,i.isValidData(t)?i.data(t):e),i},$.fn.mappedColor=function(t){return ftui.getStyle("."+$(this).data(t),"color")||$(this).data(t)},$.fn.matchingState=function(t,e){if(!ftui.isValid(e))return"";var i,n,o,a,r=$(this),s=String(ftui.getPart(e,r.data(t+"-part"))),l=r.data(t+"-on"),u=r.data(t+"-off"),f=String(l);f.match(/:/)&&(n=(i=f.split(":"))[0].replace("[",""),o=i[1].replace("]",""),(a=ftui.getDeviceParameter(n,o))&&ftui.isValid(a)&&(f=a.val));var c=String(u);if(c.match(/:/)&&(n=(i=c.split(":"))[0].replace("[",""),o=i[1].replace("]",""),(a=ftui.getDeviceParameter(n,o))&&ftui.isValid(a)&&(c=a.val)),ftui.isValid(l)){if(s===f)return"on";if(s.match(new RegExp("^"+f+"$")))return"on"}if(ftui.isValid(u)){if(s===c)return"off";if(s.match(new RegExp("^"+c+"$")))return"off"}if(ftui.isValid(l)&&ftui.isValid(u)){if("!off"===f&&!s.match(new RegExp("^"+c+"$")))return"on";if("!on"===c&&!s.match(new RegExp("^"+f+"$")))return"off";if(f==="!"+c&&!s.match(new RegExp("^"+c+"$")))return"on";if(c==="!"+f&&!s.match(new RegExp("^"+f+"$")))return"off"}},$.fn.isDeviceReading=function(t){var e=$(this).data(t);return e&&!$.isNumeric(e)&&"string"==typeof e&&e.match(/^[\w\s-]:[\w\s-]$/)},$.fn.isExternData=function(t){var e=$(this).data(t);return e?e.match(/^[#\.\[][^:]*$/):""},$.fn.cleanWhitespace=function(){this.contents().filter(function(){return 3==this.nodeType&&!/\S/.test(this.nodeValue)}).remove();return this},$.fn.getReading=function(t,e){var i=String($(this).data("device")),n=$(this).data(t);if($.isArray(n)&&(n=n[e]),(n=String(n))&&n.match(/:/)){var o=n.split(":");i=o[0].replace("[",""),n=o[1].replace("]","")}if(i&&i.length>0){var a=ftui.deviceStates[i];return a&&a[n]?a[n]:{}}return{}},$.fn.valOfData=function(t){var e=$(this).data(t);return ftui.isValid(e)?e.toString().match(/^[#\.\[][^:]*$/)?$(e).data("value"):e:""},$.fn.transmitCommand=function(){if(!$(this).hasClass("notransmit")){var t=[$(this).valOfData("cmd"),$(this).valOfData("device")+$(this).valOfData("filter"),$(this).valOfData("set"),$(this).valOfData("value")].join(" ");ftui.setFhemStatus(t),ftui.toast(t)}}}if("function"==typeof Framework7){var f7={ftui:new Framework7({animateNavBackIcon:!0}),options:{dynamicNavbar:!0,domCache:!0},views:[]};Dom7(".view").each(function(t){var e=f7.ftui.addView("#"+Dom7(this)[0].id,{dynamicNavbar:!0});f7.ftui.views.push(e)}),f7.ftui.onPageInit("*",function(t){ftui.log(1,"f7: "+t.name+" initialized"),ftui.initWidgets('.page[data-page="'+t.name+'"]')})}var Modul_widget=function(){function update_lock(t,e){$.each(["lock","lock-on","lock-off"],function(i,n){me.elements.filterDeviceReading(n,t,e).each(function(t){var e=$(this),i=e.getReading("lock").val;"on"===e.matchingState("lock",i)&&e.addClass("lock"),"off"===e.matchingState("lock",i)&&e.removeClass("lock")})})}function update_hide(t,e){$.each(["hide","hide-on","hide-off"],function(i,n){me.elements.filterDeviceReading(n,t,e).each(function(t){var e=$(this),i=e.getReading("hide").val;"on"===e.matchingState("hide",i)&&(ftui.isValid(e.data("hideparents"))?e.parents(e.data("hideparents")).hide():e.hide()),"off"===e.matchingState("hide",i)&&(ftui.isValid(e.data("hideparents"))?e.parents(e.data("hideparents")).show():e.show())})})}function update_reachable(t,e){$.each(["reachable","reachable-on","reachable-off"],function(i,n){me.elements.filterDeviceReading(n,t,e).each(function(t){var e=$(this),i=e.getReading("reachable").val;"on"===e.matchingState("reachable",i)&&e.removeClass("unreachable"),"off"===e.matchingState("reachable",i)&&e.addClass("unreachable")})})}function substitution(value,subst){if(ftui.isValid(subst)&&ftui.isValid(value))if($.isArray(subst))for(var i=0,len=subst.length;i=0?Number(t).toFixed(e):t}function map(t,e,i){if("object"==typeof t&&null!==t)for(var n in t)if(e===n||e.match(new RegExp("^"+n+"$")))return t[n];return i}function init_attr(t){t.initData("get","STATE"),t.initData("set",""),t.initData("cmd","set"),t.initData("get-on","(true|1|on|open|ON)"),t.initData("get-off","(false|0|off|closed|OFF)"),me.addReading(t,"get"),t.isDeviceReading("get-on")&&me.addReading(t,"get-on"),t.isDeviceReading("get-off")&&me.addReading(t,"get-off"),t.initData("reachable-on","!off"),t.initData("reachable-off","(false|0)"),me.addReading(t,"reachable"),t.isValidData("hide")&&t.initData("hide-on","(true|1|on)"),t.initData("hide","STATE"),t.isValidData("hide-on")&&t.initData("hide-off","!on"),me.addReading(t,"hide"),t.isValidData("lock")&&t.initData("lock-on","(true|1|on)"),t.initData("lock",t.data("get")),t.isValidData("lock-on")&&t.initData("lock-off","!on"),me.addReading(t,"lock")}function init_ui(t){t.text(me.widgetname)}function init(){ftui.log(1,"init widget: name="+me.widgetname+" area="+me.area),me.elements=$('[data-type="'+me.widgetname+'"]',me.area),me.elements.each(function(t){var e=$(this);me.init_attr(e),e=me.init_ui(e)})}function addReading(t,e){var i=t.data(e);if(ftui.isValid(i)&&($.isArray(i)||!i.toString().match(/^[#\.\[][^:]*$/))){var n=t.data("device");$.isArray(i)||(i=new Array(i.toString()));for(var o=i.length-1;o>=0;o-=1){var a=i[o];if(a.match(/:/)){var r=a.split(":");n=r[0].replace("[",""),a=r[1].replace("]","")}if(ftui.isValid(n)&&ftui.isValid(a)&&""!==n&&""!==a&&" "!==n&&" "!==a){n=n.toString();var s="STATE"===a?n:[n,a].join("-");subscriptions[s]={},subscriptions[s].device=n,subscriptions[s].reading=a}}}}function update(t,e){ftui.log(1,"warning: "+me.widgetname+" has not implemented update function")}var subscriptions={},elements=[],me={widgetname:"widget",area:"",init:init,init_attr:init_attr,init_ui:init_ui,update:update,update_lock:update_lock,update_reachable:update_reachable,update_hide:update_hide,substitution:substitution,fix:fix,map:map,addReading:addReading,subscriptions:subscriptions,elements:elements};return me},plugins={modules:[],addModule:function(t){this.modules.push(t)},removeArea:function(t){for(var e=this.modules.length-1;e>=0;e-=1)this.modules[e].area===t&&this.modules.splice(e,1)},updateParameters:function(){ftui.subscriptions={},ftui.subscriptionTs={},ftui.devs=[ftui.config.webDevice],ftui.reads=["STATE","longpoll"];for(var t=this.modules.length-1;t>=0;t-=1){var e=this.modules[t];for(var i in e.subscriptions){ftui.subscriptions[i]=e.subscriptions[i],ftui.subscriptionTs[i+"-ts"]=e.subscriptions[i];var n=ftui.subscriptions[i].device;ftui.devs.indexOf(n)<0&&ftui.devs.push(n);var o=ftui.subscriptions[i].reading;ftui.reads.indexOf(o)<0&&ftui.reads.push(o)}}var a=ftui.devs.length>0?$.map(ftui.devs,$.trim).join():".*",r=ftui.reads.length>0?$.map(ftui.reads,$.trim).join(" "):"";ftui.config.longPollFilter?ftui.poll.longPollFilter=ftui.config.longPollFilter:ftui.poll.longPollFilter=a+", "+r,ftui.config.shortPollFilter?ftui.poll.shortPollFilter=ftui.config.shortPollFilter:ftui.poll.shortPollFilter=a+" "+r,ftui.states.lastShortpoll=0},load:function(t,e){return ftui.log(1,'Load plugin "'+t+'" for area "'+e+'"'),ftui.loadPlugin(t,e)},update:function(t,e){$.each(this.modules,function(i,n){"object"==typeof n&&n.update(t,e)}),ftui.updateBindElements("ftui.deviceStates"),ftui.log(1,'call "plugins.update" done for "'+t+":"+e+'"')}},ftui={version:"2.6.37",config:{DEBUG:!1,DEMO:!1,ICONDEMO:!1,dir:"",filename:"",basedir:"",fhemDir:"",debuglevel:0,doLongPoll:!0,lang:"de",toastPosition:"bottom-left",shortpollInterval:0,styleCollection:{},stdColors:["green","orange","red","ligthblue","blue","gray","white","mint"]},poll:{currLine:0,xhr:null,longPollRequest:null,shortPollTimer:null,longPollTimer:null,lastUpdateTimestamp:new Date,lastEventTimestamp:new Date,lastShortpollTimestamp:new Date},states:{width:0,lastSetOnline:0,lastShortpoll:0,longPollRestart:!1},deviceStates:{},paramIdMap:{},timestampMap:{},subscriptions:{},subscriptionTs:{},scripts:[],gridster:{instances:{},instance:null,baseX:0,baseY:0,margins:5,mincols:0,cols:0,rows:0},init:function(){function t(){$.toast&&!$('link[href$="lib/jquery.toast.min.css"]').length&&$("head").append('')}ftui.hideWidgets(),ftui.paramIdMap={},ftui.timestampMap={},ftui.config.longPollType=$("meta[name='longpoll_type']").attr("content")||"websocket";var e=$("meta[name='longpoll']").attr("content")||"1";ftui.config.doLongPoll="0"!=e,ftui.config.shortPollFilter=$("meta[name='shortpoll_filter']").attr("content"),ftui.config.longPollFilter=$("meta[name='longpoll_filter']").attr("content"),ftui.config.DEMO="1"==$("meta[name='demo']").attr("content"),ftui.config.ICONDEMO="1"==$("meta[name='icondemo']").attr("content"),ftui.config.debuglevel=$("meta[name='debug']").attr("content")||0,ftui.config.webDevice=$("meta[name='web_device']").attr("content")||$.trim($("body").data("webname"))||"WEB",ftui.config.maxLongpollAge=$("meta[name='longpoll_maxage']").attr("content")||240,ftui.config.DEBUG=ftui.config.debuglevel>0,ftui.config.TOAST=$("meta[name='toast']").attr("content")||5,ftui.config.toastPosition=$("meta[name='toast_position']").attr("content")||"bottom-left",ftui.config.shortpollInterval=$("meta[name='shortpoll_only_interval']").attr("content")||30,ftui.config.shortPollDelay=$("meta[name='shortpoll_restart_delay']").attr("content")||3e3;var i=window.location.pathname;ftui.config.filename=i.substring(i.lastIndexOf("/")+1),ftui.log(1,"Filename: "+ftui.config.filename),ftui.config.fhemDir=$("meta[name='fhemweb_url']").attr("content")||location.origin+"/fhem/",ftui.config.fhemDir=ftui.config.fhemDir.replace("///","//"),ftui.log(1,"FHEM dir: "+ftui.config.fhemDir);var n=navigator.language||navigator.userLanguage;ftui.config.lang=$("meta[name='lang']").attr("content")||ftui.isValid(n)?n.split("-")[0]:"de",ftui.config.username=$("meta[name='username']").attr("content"),ftui.config.password=$("meta[name='password']").attr("content"),ftui.devs=[ftui.config.webDevice],ftui.reads=["STATE"],ftui.getCSrf(),$.fn.toast?t():ftui.dynamicload(ftui.config.basedir+"lib/jquery.toast.min.js",!1).done(function(){t()}),$(document).on("visibilitychange",function(){"hidden"===document.visibilityState||(ftui.log(1,"Page became visible again -> start healthCheck in 3 secondes "),setTimeout(function(){ftui.healthCheck()},3e3))});try{localStorage.setItem("ftui",ftui.version),localStorage.removeItem("ftui")}catch(t){ftui.toast("You are in Privacy Mode
Please deactivate Privacy Mode and then reload the page.","error")}var o=ftui.getAndroidVersion(),a=/iPad|iPhone|iPod/.test(navigator.userAgent)&&!window.MSStream,r=o&&parseFloat(o)<5||a;if(ftui.config.clickEventType=r?"touchstart":"touchstart mousedown",ftui.config.moveEventType=r?"touchmove":"touchmove mousemove",ftui.config.releaseEventType=r?"touchend":"touchend mouseup",ftui.config.leaveEventType=r?"touchleave":"touchleave mouseout",ftui.config.enterEventType=r?"touchenter":"touchenter mouseenter",$("
").prependTo("body").hide(),$("#shade").on(ftui.config.clickEventType,function(t){$(document).trigger("shadeClicked")}),ftui.readStatesLocal(),0!==$('link[href$="css/fhem-tablet-ui.css"]').length||0!==$('link[href$="css/fhem-tablet-ui.min.css"]').length||f7)ftui.loadStyleSchema(),ftui.initPage();else{var s=ftui.config.basedir+"css/fhem-tablet-ui.css";$.when($.get(s,function(){$("",{rel:"stylesheet",type:"text/css",href:s}).prependTo("head")})).then(function(){var t=0,e=setInterval(function(){ftui.log(1,"fhem-tablet-ui.css dynamically loaded. Waiting until it is ready to use..."),"center"===$("body").css("text-align")&&(ftui.log(1,"fhem-tablet-ui.css is ready to use."),clearInterval(e),ftui.loadStyleSchema(),ftui.initPage()),++t>120&&(clearInterval(e),ftui.toast("fhem-tablet-ui.css not ready to use","error"))},50)})}$(document).on("changedSelection",function(){$(".gridster li > header ~ .hbox:only-of-type, .dialog > header ~ .hbox:first-of-type:nth-last-of-type(1), .gridster li > header ~ .center:not([data-type]):only-of-type, .card > header ~ div:not([data-type]):only-of-type, .gridster li header ~ div:first-of-type:nth-last-of-type(1)").each(function(t){$(this).siblings("header").outerHeight()>0&&$(this).css({height:"calc(100% - "+$(this).siblings("header").outerHeight()+"px)"})})}),$(document).on("initWidgetsDone",function(){ftui.startShortPollInterval(500),ftui.states.longPollRestart=!0,ftui.restartLongPoll(),ftui.initHeaderLinks(),$(document).trigger("changedSelection"),ftui.config.ICONDEMO||ftui.disableSelection()}),f7||$("*:not(select):not(textarea)").focus(function(){$(this).blur()}),setInterval(function(){ftui.healthCheck()},6e4)},initGridster:function(t){function e(){var e=-1,i=-1,n=0,o=0,a=0,r=0;$(".gridster > ul > li").each(function(){var t=$(this).data("col")+$(this).data("sizex")-1;t>e&&(e=t);var n=$(this).data("row")+$(this).data("sizey")-1;n>i&&(i=n)}),a=ftui.gridster.cols>0?ftui.gridster.cols:e,r=ftui.gridster.rows>0?ftui.gridster.rows:i;var s=2*a*ftui.gridster.margins,l=2*r*ftui.gridster.margins;n=ftui.gridster.baseX>0?ftui.gridster.baseX:(window.innerWidth-s)/a,o=ftui.gridster.baseY>0?ftui.gridster.baseY:(window.innerHeight-l)/r,n ul",t).gridster({widget_base_dimensions:[n,o],widget_margins:[ftui.gridster.margins,ftui.gridster.margins],draggable:{handle:".gridster li > header"},min_cols:parseInt(ftui.gridster.mincols)}).data("gridster"),ftui.gridster.instances[t]&&("1"==$("meta[name='gridster_disable']").attr("content")&&ftui.gridster.instances[t].disable(),"1"==$("meta[name='gridster_starthidden']").attr("content")&&$(".gridster").hide()),$(".gridster > ul > li:has(* .gridster)").each(function(){$(this).css({"background-color":"transparent",margin:"-"+ftui.gridster.margins+"px"})}),$(".gridster > ul > li >.center",t).parent().addClass("has_center"),$(".gridster > ul > li > .vbox",t).parent().addClass("has_vbox")}ftui.gridster.minX=parseInt($("meta[name='widget_min_width'],meta[name='gridster_min_width']").attr("content")||0),ftui.gridster.minY=parseInt($("meta[name='widget_min_height'],meta[name='gridster_min_height']").attr("content")||0),ftui.gridster.baseX=parseInt($("meta[name='widget_base_width'],meta[name='gridster_base_width']").attr("content")||0),ftui.gridster.baseY=parseInt($("meta[name='widget_base_height'],meta[name='gridster_base_height']").attr("content")||0),ftui.gridster.cols=parseInt($("meta[name='gridster_cols']").attr("content")||0),ftui.gridster.rows=parseInt($("meta[name='gridster_rows']").attr("content")||0),ftui.gridster.resize=parseInt($("meta[name='gridster_resize']").attr("content")||ftui.gridster.baseX+ftui.gridster.baseY>0?0:1),$("meta[name='widget_margin'],meta[name='gridster_margin']").attr("content")&&(ftui.gridster.margins=parseInt($("meta[name='widget_margin'],meta[name='gridster_margin']").attr("content"))),$(".gridster").length>0&&($('link[href$="lib/jquery.gridster.min.css"]').length||$("head").append(''),$.fn.gridster?e():ftui.dynamicload(ftui.config.basedir+"lib/jquery.gridster.min.js",!1).done(function(){e()}),ftui.gridster.resize&&$(window).on("resize",function(){ftui.states.width!==window.innerWidth&&(clearTimeout(ftui.states.delayResize),ftui.states.delayResize=setTimeout(e,500),ftui.states.width=window.innerWidth)}))},initPage:function(t){ftui.hideWidgets(t),t=ftui.isValid(t)?t:"",console.time("initPage"),ftui.log(2,"initPage - area="+t),ftui.initGridster(t),$("[data-template]",t).each(function(t){var e=$(this);e.attr("data-type","include"),e.attr("data-url",e.data("template")),e.removeAttr("data-template")}),ftui.initWidgets(t)},initWidgets:function(t){t=ftui.isValid(t)?t:"";var e=[];ftui.log(3,plugins),plugins.removeArea(t),ftui.log(3,plugins),ftui.log(2,"initWidgets - area="+t),$("[data-type]:not([data-ready])",t).each(function(t){var i=$(this).data("type");e.indexOf(i)<0&&e.push(i),$(this).attr("data-ready","")});var i=$.map(e,function(e,i){return plugins.load(e,t)});$.when.apply(this,i).then(function(){plugins.updateParameters(),ftui.log(1,"initWidgets - Done"),console.timeEnd("initPage"),$(document).trigger("initWidgetsDone",[t])})},initHeaderLinks:function(){($("[class*=fa-]").length>0||$('[data-type="select"]').length>0||$('[data-type="homestatus"]').length>0)&&!$('link[href$="lib/font-awesome.min.css"]').length&&$("head").append(''),$("[class*=oa-]").length>0&&!$('link[href$="lib/openautomation.css"]').length&&$("head").append(''),$("[class*=fs-]").length>0&&!$('link[href$="lib/fhemSVG.css"]').length&&$("head").append(''),$("[class*=mi-]").length>0&&!$('link[href$="lib/material-icons.min.css"]').length&&$("head").append(''),$("[class*=wi-]").length>0&&!$('link[href$="lib/weather-icons.min.css"]').length&&$("head").append(''),$("[class*=wi-wind]").length>0&&!$('link[href$="lib/weather-icons-wind.min.css"]').length&&$("head").append('')},startLongpoll:function(){ftui.log(2,"startLongpoll: "+ftui.config.doLongPoll),ftui.poll.lastEventTimestamp=new Date,ftui.config.doLongPoll&&(ftui.config.shortpollInterval=$("meta[name='shortpoll_interval']").attr("content")||900,ftui.longPollTimer=setTimeout(function(){ftui.longPoll()},100))},stopLongpoll:function(){ftui.log(2,"stopLongpoll"),clearInterval(ftui.longPollTimer),ftui.longPollRequest&&ftui.longPollRequest.abort(),ftui.websocket&&(ftui.websocket.close(),ftui.websocket=void 0,ftui.log(2,"stopped websocket"))},restartLongPoll:function(t,e){ftui.log(2,"restartLongpoll");var i;clearTimeout(ftui.longPollTimer),t&&ftui.toast("Disconnected from FHEM
"+t,e),ftui.stopLongpoll(),ftui.states.longPollRestart?i=2e3:(ftui.toast("Retry to connect in 10 seconds"),i=1e4),ftui.longPollTimer=setTimeout(function(){ftui.startLongpoll()},i)},startShortPollInterval:function(t){ftui.log(1,"start shortpoll in (ms):"+(t||1e3*ftui.config.shortpollInterval)),clearInterval(ftui.shortPollTimer),ftui.shortPollTimer=setTimeout(function(){ftui.shortPoll(),ftui.startShortPollInterval()},t||1e3*ftui.config.shortpollInterval)},shortPoll:function(t){var e=(new Date).getTime()/1e3;if(!(e-ftui.states.lastShortpollShortPoll Request Failed: : Result is null
","error");console.timeEnd("read jsonlist2")}).fail(function(t,e,i){var n=e+", "+i;ftui.log(1,"shortPoll request failed: "+n),ftui.states.lastSetOnline=0,ftui.states.lastShortpoll=0,e.indexOf("parsererror")<0?(ftui.toast("ShortPoll Request Failed, will retry in "+ftui.config.shortPollDelay/1e3+"s
"+n,"error"),ftui.getCSrf(),ftui.startShortPollInterval(3e3)):ftui.toast("ShortPoll Request Failed
"+n,"error")})}},longPoll:function(){if(ftui.config.DEMO)console.log("DEMO-Mode: no longpoll");else if("WebSocket"in window&&"websocket"===ftui.config.longPollType&&ftui.deviceStates[ftui.config.webDevice]&&ftui.deviceStates[ftui.config.webDevice].longpoll&&ftui.deviceStates[ftui.config.webDevice].longpoll.val&&"websocket"===ftui.deviceStates[ftui.config.webDevice].longpoll.val){if(ftui.websocket)return void ftui.log(3,"valid ftui.websocket found");ftui.config.DEBUG&&ftui.toast("Longpoll (WebSocket) started"),ftui.poll.URL=ftui.config.fhemDir.replace(/^http/i,"ws")+"?XHR=1&inform=type=status;filter="+ftui.poll.longPollFilter+";since="+ftui.poll.lastEventTimestamp.getTime()+";fmt=JSON×tamp="+(new Date).getTime(),ftui.log(1,"websockets URL="+ftui.poll.URL),ftui.states.longPollRestart=!1,ftui.websocket=new WebSocket(ftui.poll.URL),ftui.websocket.onclose=function(t){var e;e=1e3==t.code?"Normal closure, meaning that the purpose for which the connection was established has been fulfilled.":1001==t.code?'An endpoint is "going away", such as a server going down or a browser having navigated away from a page.':1002==t.code?"An endpoint is terminating the connection due to a protocol error":1003==t.code?"An endpoint is terminating the connection because it has received a type of data it cannot accept (e.g., an endpoint that understands only text data MAY send this if it receives a binary message).":1004==t.code?"Reserved. The specific meaning might be defined in the future.":1005==t.code?"No status code was actually present.":1006==t.code?"The connection was closed abnormally, e.g., without sending or receiving a Close control frame":1007==t.code?"An endpoint is terminating the connection because it has received data within a message that was not consistent with the type of the message (e.g., non-UTF-8 [http://tools.ietf.org/html/rfc3629] data within a text message).":1008==t.code?'An endpoint is terminating the connection because it has received a message that "violates its policy". This reason is given either if there is no other sutible reason, or if there is a need to hide specific details about the policy.':1009==t.code?"An endpoint is terminating the connection because it has received a message that is too big for it to process.":1010==t.code?"An endpoint (client) is terminating the connection because it has expected the server to negotiate one or more extension, but the server didn't return them in the response message of the WebSocket handshake.
Specifically, the extensions that are needed are: "+t.reason:1011==t.code?"A server is terminating the connection because it encountered an unexpected condition that prevented it from fulfilling the request.":1015==t.code?"The connection was closed due to a failure to perform a TLS handshake (e.g., the server certificate can't be verified).":"Unknown reason",ftui.log(1,"websocket (url="+t.target.url+") closed! reason="+e),t.target.url===ftui.poll.URL&&ftui.restartLongPoll(e)},ftui.websocket.onerror=function(t){ftui.log(1,"Error while longpoll: "+t.data),ftui.config.debuglevel>1&&t.target.url===ftui.poll.URL&&ftui.toast("Error while longpoll (websocket)","error")},ftui.websocket.onmessage=function(t){ftui.handleUpdates(t.data)}}else{if(ftui.log(1,"longpoll: websockets not supportetd or not activated > fall back to AJAX"),ftui.xhr)return void ftui.log(3,"valid ftui.xhr found");if(ftui.longPollRequest)return void ftui.log(3,"valid ftui.longPollRequest found");ftui.poll.currLine=0,ftui.config.DEBUG&&(ftui.states.longPollRestart?ftui.toast("Longpoll (AJAX) re-started"):ftui.toast("Longpoll (AJAX) started")),ftui.log(1,ftui.states.longPollRestart?"Longpoll re-started":"Longpoll started"),ftui.states.longPollRestart=!1,ftui.longPollRequest=$.ajax({url:ftui.config.fhemDir,cache:!1,async:!0,method:"GET",data:{XHR:1,inform:"type=status;filter="+ftui.poll.longPollFilter+";since="+ftui.poll.lastEventTimestamp.getTime()+";fmt=JSON",fwcsrf:ftui.config.csrf},username:ftui.config.username,password:ftui.config.password,xhr:function(){return ftui.xhr=new window.XMLHttpRequest,ftui.xhr.addEventListener("readystatechange",function(t){var e=t.target.responseText;4!==t.target.readyState&&3===t.target.readyState&&ftui.handleUpdates(e)},!1),ftui.log(1,"ajax lomgpoll responseURL="+ftui.xhr.responseURL),ftui.log(1,"ajax longpol statusText="+ftui.xhr.statusText),ftui.xhr}}).done(function(t){ftui.xhr&&(ftui.xhr.abort(),ftui.xhr=null),ftui.longPollRequest=null,ftui.states.longPollRestart?ftui.longPoll():(ftui.log(1,"Disconnected from FHEM - poll done - "+t),ftui.restartLongPoll(t))}).fail(function(t,e,i){ftui.xhr&&(ftui.xhr.abort(),ftui.xhr=null),ftui.longPollRequest=null,ftui.states.longPollRestart?ftui.longPoll():(ftui.log(1,"Error while longpoll: "+e+": "+i),ftui.config.debuglevel>1&&ftui.toast("Error while longpoll (ajax)
"+e+": "+i,"error"),ftui.restartLongPoll(e+": "+i))})}},handleUpdates:function(t){for(var e=t.split(/\n/),i=ftui.poll.currLine,n=e.length;i9999&&(ftui.states.longPollRestart=!0,ftui.longPollRequest.abort()))},setFhemStatus:function(t){ftui.config.DEMO?console.log("DEMO-Mode: no setFhemStatus"):(ftui.startShortPollInterval(),ftui.sendFhemCommand(t))},sendFhemCommand:function(t){var e="jsonlist"==(t=t.replace(" "," ")).substr(0,8)?"json":"text";return ftui.log(1,"send to FHEM: "+t),$.ajax({async:!0,cache:!1,method:"GET",dataType:e,url:ftui.config.fhemDir,username:ftui.config.username,password:ftui.config.password,data:{cmd:t,fwcsrf:ftui.config.csrf,XHR:"1"},error:function(t,e,i){ftui.toast("FHEM Command failed
"+e+": "+i,"error")}})},loadStyleSchema:function(){$.each($('link[href$="-ui.css"],link[href$="-ui.min.css"]'),function(t,e){if(e&&e.sheet&&e.sheet.cssRules&&!e.getAttribute("disabled")){var i=e.sheet.cssRules;for(var n in i)if(i[n].style){var o=i[n].style.cssText.split(";");o.pop();var a=i[n].selectorText,r={};for(var s in o){var l=o[s].toString().split(":");l[0].match(/color/)&&(r[$.trim(l[0])]=ftui.rgbToHex($.trim(l[1]).replace("! important","").replace("!important","")))}Object.keys(r).length>0&&(ftui.config.styleCollection[a]=r)}}})},onUpdateDone:function(){$(document).trigger("updateDone"),ftui.checkInvalidElements(),ftui.updateBindElements()},checkInvalidElements:function(){$(".autohide[data-get]").each(function(t){var e=$(this),i=e.getReading("get").valid;i&&!0===i?e.removeClass("invalid"):e.addClass("invalid")})},updateBindElements:function(filter){$('[data-bind*="'+filter+'"]').each(function(index){var elem=$(this),variable=elem.data("bind");variable&&elem.text(eval(variable))})},setOnline:function(){var t=(new Date).getTime()/1e3;if(t-ftui.states.lastSetOnline>60){if(ftui.config.DEBUG&&ftui.toast("FHEM connected"),ftui.states.lastSetOnline=t,ftui.states.lastShortpoll=0,ftui.startShortPollInterval(1e3),!ftui.config.doLongPoll){var e=$("meta[name='longpoll']").attr("content")||"1";ftui.config.doLongPoll="0"!=e,ftui.states.longPollRestart=!1,ftui.config.doLongPoll&&ftui.startLongpoll()}ftui.log(1,"FTUI is online")}},setOffline:function(){ftui.config.DEBUG&&ftui.toast("Lost connection to FHEM"),ftui.config.doLongPoll=!1,ftui.states.longPollRestart=!0,clearInterval(ftui.shortPollTimer),ftui.stopLongpoll(),ftui.saveStatesLocal(),ftui.log(1,"FTUI is offline")},readStatesLocal:function(){ftui.poll.shortPollDuration=localStorage.getItem("shortPollDuration")||1e3,ftui.config.DEMO?$.ajax({async:!1,method:"GET",url:"/fhem/tablet/data/"+ftui.config.filename.replace(".html",".dat")}).done(function(t){ftui.deviceStates=JSON.parse(t)||{}}):ftui.deviceStates=JSON.parse(localStorage.getItem("deviceStates"))||{}},saveStatesLocal:function(){var t=JSON.stringify(ftui.deviceStates);localStorage.setItem("deviceStates",t),localStorage.setItem("shortPollDuration",ftui.poll.shortPollDuration)},getDeviceParameter:function(t,e){if(t&&t.length>0){var i=ftui.deviceStates[t];return i&&i[e]?i[e]:null}return null},loadPlugin:function(t,e){var i=new $.Deferred;return ftui.log(2,'Start load plugin "'+t+'" for area "'+e+'"'),ftui.dynamicload(ftui.config.basedir+"js/widget_"+t+".js",!0).done(function(){var n=[],o=window["depends_"+t];if($.isFunction(o)){var a=o();a&&(a=$.isArray(a)?a:[a],$.map(a,function(t,e){t.match(new RegExp("^.*.(js|css)$"))?n.push(ftui.dynamicload(t,!1)):n.push(ftui.loadPlugin(t))}))}else ftui.log(2,"function depends_"+t+" not found (maybe ok)");$.when.apply(this,n).always(function(){var n=window["Modul_"+t]?new window["Modul_"+t]:null;if(n){if(void 0!==e){plugins.addModule(n),ftui.isValid(e)&&(n.area=e),ftui.log(1,"Try to init plugin: "+t),n.init();for(var o in n.subscriptions)n.update(n.subscriptions[o].device,n.subscriptions[o].reading)}ftui.log(1,'Finished load plugin "'+t+'" for area "'+e+'"'),$('[data-type="'+t+'"]',e).removeClass("widget-hide")}else ftui.log(1,'Failed to load plugin "'+t+'" for area "'+e+'"');i.resolve()})}).fail(function(){ftui.toast("Failed to load plugin : "+t),ftui.log(1,"Failed to load plugin : "+t+' - add