fhem-tablet-ui.js 83 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205
  1. /* FHEM tablet ui */
  2. /**
  3. * UI builder framework for FHEM
  4. *
  5. * Version: 2.6.32
  6. *
  7. * Copyright (c) 2015-2017 Mario Stephan <mstephan@shared-files.de>
  8. * Under MIT License (http://www.opensource.org/licenses/mit-license.php)
  9. *
  10. */
  11. /* global Framework7:true, jQuery:true, Dom7:true */
  12. "use strict";
  13. // -------- Framework7---------
  14. // https://framework7.io/docs/
  15. if (typeof Framework7 === 'function') {
  16. var f7 = {
  17. ftui: new Framework7({
  18. animateNavBackIcon: true
  19. }),
  20. options: {
  21. dynamicNavbar: true,
  22. domCache: true
  23. },
  24. views: []
  25. };
  26. Dom7('.view').each(function (index) {
  27. var view = f7.ftui.addView('#' + Dom7(this)[0].id, {
  28. dynamicNavbar: true
  29. });
  30. f7.ftui.views.push(view);
  31. });
  32. f7.ftui.onPageInit('*', function (page) {
  33. ftui.log(1, 'f7: ' + page.name + ' initialized');
  34. ftui.initWidgets('.page[data-page="' + page.name + '"]');
  35. });
  36. }
  37. // -------- Widget Base---------
  38. var Modul_widget = function () {
  39. var subscriptions = {};
  40. var elements = [];
  41. function update_lock(dev, par) {
  42. $.each(['lock', 'lock-on', 'lock-off'], function (index, key) {
  43. me.elements.filterDeviceReading(key, dev, par)
  44. .each(function (idx) {
  45. var elem = $(this);
  46. var value = elem.getReading('lock').val;
  47. if (elem.matchingState('lock', value) === 'on') {
  48. elem.addClass('lock');
  49. }
  50. if (elem.matchingState('lock', value) === 'off') {
  51. elem.removeClass('lock');
  52. }
  53. });
  54. });
  55. }
  56. function update_hide(dev, par) {
  57. $.each(['hide', 'hide-on', 'hide-off'], function (index, key) {
  58. me.elements.filterDeviceReading(key, dev, par)
  59. .each(function (idx) {
  60. var elem = $(this);
  61. var value = elem.getReading('hide').val;
  62. if (elem.matchingState('hide', value) === 'on') {
  63. if (ftui.isValid(elem.data('hideparents'))) {
  64. elem.parents(elem.data('hideparents')).hide();
  65. } else {
  66. elem.hide();
  67. }
  68. }
  69. if (elem.matchingState('hide', value) === 'off') {
  70. if (ftui.isValid(elem.data('hideparents'))) {
  71. elem.parents(elem.data('hideparents')).show();
  72. } else {
  73. elem.show();
  74. }
  75. }
  76. });
  77. });
  78. }
  79. function update_reachable(dev, par) {
  80. $.each(['reachable', 'reachable-on', 'reachable-off'], function (index, key) {
  81. me.elements.filterDeviceReading(key, dev, par)
  82. .each(function (idx) {
  83. var elem = $(this);
  84. var value = elem.getReading('reachable').val;
  85. if (elem.matchingState('reachable', value) === 'on') {
  86. elem.removeClass('unreachable');
  87. }
  88. if (elem.matchingState('reachable', value) === 'off') {
  89. elem.addClass('unreachable');
  90. }
  91. });
  92. });
  93. }
  94. function substitution(value, subst) {
  95. if (ftui.isValid(subst) && ftui.isValid(value)) {
  96. if ($.isArray(subst)) {
  97. for (var i = 0, len = subst.length; i < len; i += 2) {
  98. if (i + 1 < len) {
  99. value=value.replace(new RegExp(String(subst[i]) , "g"),String(subst[i+1]));
  100. }
  101. }
  102. } else if (subst.match(/^s/)) {
  103. var f = subst.substr(1, 1);
  104. var sub = subst.split(f);
  105. return (value) ? value.replace(new RegExp(sub[1], sub[3]), sub[2]) : '';
  106. } else if (subst.match(/weekdayshort/))
  107. return ftui.dateFromString(value).ee();
  108. else if (subst.match(/.*\(\)/))
  109. return eval('value.' + subst);
  110. }
  111. return value;
  112. }
  113. function fix(value, fix) {
  114. return ($.isNumeric(value) && fix >= 0) ? Number(value).toFixed(fix) : value;
  115. }
  116. function map(mapObj, readval, defaultVal) {
  117. if ((typeof mapObj === "object") && (mapObj !== null)) {
  118. for (var key in mapObj) {
  119. if (readval === key || readval.match(new RegExp('^' + key + '$'))) {
  120. return mapObj[key];
  121. }
  122. }
  123. }
  124. return defaultVal;
  125. }
  126. function init_attr(elem) {
  127. elem.initData('get', 'STATE');
  128. elem.initData('set', '');
  129. elem.initData('cmd', 'set');
  130. me.addReading(elem, 'get');
  131. // reachable parameter
  132. elem.initData('reachable-on', '!off');
  133. elem.initData('reachable-off', '(false|0)');
  134. me.addReading(elem, 'reachable');
  135. // if hide reading is defined, set defaults for comparison
  136. if (elem.isValidData('hide')) {
  137. elem.initData('hide-on', '(true|1|on)');
  138. }
  139. elem.initData('hide', 'STATE');
  140. if (elem.isValidData('hide-on')) {
  141. elem.initData('hide-off', '!on');
  142. }
  143. me.addReading(elem, 'hide');
  144. // if lock reading is defined, set defaults for comparison
  145. if (elem.isValidData('lock')) {
  146. elem.initData('lock-on', '(true|1|on)');
  147. }
  148. elem.initData('lock', elem.data('get'));
  149. if (elem.isValidData('lock-on')) {
  150. elem.initData('lock-off', '!on');
  151. }
  152. me.addReading(elem, 'lock');
  153. }
  154. function init_ui(elem) {
  155. elem.text(me.widgetname);
  156. }
  157. function init() {
  158. ftui.log(1, "init widget: name=" + me.widgetname + " area=" + me.area);
  159. me.elements = $('[data-type="' + me.widgetname + '"]', me.area);
  160. me.elements.each(function (index) {
  161. var elem = $(this);
  162. me.init_attr(elem);
  163. elem = me.init_ui(elem);
  164. });
  165. }
  166. function addReading(elem, key) {
  167. var data = elem.data(key);
  168. if (ftui.isValid(data)) {
  169. if ($.isArray(data) || !data.toString().match(/^[#\.\[][^:]*$/)) {
  170. var device = elem.data('device');
  171. if (!$.isArray(data)) {
  172. data = new Array(data.toString());
  173. }
  174. for (var i = data.length - 1; i >= 0; i -= 1) {
  175. var reading = data[i];
  176. // fully qualified readings => DEVICE:READING
  177. if (reading.match(/:/)) {
  178. var fqreading = reading.split(':');
  179. device = fqreading[0].replace('[', '');
  180. reading = fqreading[1].replace(']', '');
  181. }
  182. // fill objects for mapping from FHEMWEB paramid to device + reading
  183. if (ftui.isValid(device) && ftui.isValid(reading) &&
  184. device !== '' && reading !== '' &&
  185. device !== ' ' && reading !== ' ') {
  186. device = device.toString();
  187. var paramid = (reading === 'STATE') ? device : [device, reading].join('-');
  188. subscriptions[paramid] = {};
  189. subscriptions[paramid].device = device;
  190. subscriptions[paramid].reading = reading;
  191. }
  192. }
  193. }
  194. }
  195. }
  196. function update(dev, par) {
  197. ftui.log(1, 'warning: ' + me.widgetname + ' has not implemented update function');
  198. }
  199. var me = {
  200. widgetname: 'widget',
  201. area: '',
  202. init: init,
  203. init_attr: init_attr,
  204. init_ui: init_ui,
  205. update: update,
  206. update_lock: update_lock,
  207. update_reachable: update_reachable,
  208. update_hide: update_hide,
  209. substitution: substitution,
  210. fix: fix,
  211. map: map,
  212. addReading: addReading,
  213. subscriptions: subscriptions,
  214. elements: elements
  215. };
  216. return me;
  217. };
  218. // ------- Plugins --------
  219. var plugins = {
  220. modules: [],
  221. addModule: function (module) {
  222. this.modules.push(module);
  223. },
  224. removeArea: function (area) {
  225. for (var i = this.modules.length - 1; i >= 0; i -= 1) {
  226. if (this.modules[i].area === area) {
  227. this.modules.splice(i, 1);
  228. }
  229. }
  230. },
  231. updateParameters: function () {
  232. ftui.subscriptions = {};
  233. ftui.subscriptionTs = {};
  234. ftui.devs = [ftui.config.webDevice];
  235. ftui.reads = ['STATE', 'longpoll'];
  236. for (var i = this.modules.length - 1; i >= 0; i -= 1) {
  237. var module = this.modules[i];
  238. for (var key in module.subscriptions) {
  239. ftui.subscriptions[key] = module.subscriptions[key];
  240. ftui.subscriptionTs[key + '-ts'] = module.subscriptions[key];
  241. var d = ftui.subscriptions[key].device;
  242. if (ftui.devs.indexOf(d) < 0) {
  243. ftui.devs.push(d);
  244. }
  245. var r = ftui.subscriptions[key].reading;
  246. if (ftui.reads.indexOf(r) < 0) {
  247. ftui.reads.push(r);
  248. }
  249. }
  250. }
  251. // build filter
  252. var devicelist = (ftui.devs.length > 0) ? $.map(ftui.devs, $.trim).join() : '.*';
  253. var readinglist = (ftui.reads.length > 0) ? $.map(ftui.reads, $.trim).join(' ') : '';
  254. if (!ftui.config.longPollFilter) {
  255. ftui.poll.longPollFilter = devicelist + ', ' + readinglist;
  256. } else {
  257. ftui.poll.longPollFilter = ftui.config.longPollFilter;
  258. }
  259. if (!ftui.config.shortPollFilter) {
  260. ftui.poll.shortPollFilter = devicelist + ' ' + readinglist;
  261. } else {
  262. ftui.poll.shortPollFilter = ftui.config.shortPollFilter;
  263. }
  264. // force shortpoll
  265. ftui.states.lastShortpoll = 0;
  266. },
  267. load: function (name, area) {
  268. ftui.log(1, 'Load widget : ' + name);
  269. return ftui.loadPlugin(name, area);
  270. },
  271. update: function (dev, par) {
  272. $.each(this.modules, function (index, module) {
  273. //Iterate each module and run update function if module is available
  274. if (typeof module === 'object') {
  275. module.update(dev, par);
  276. }
  277. });
  278. // update data-bind elements
  279. ftui.updateBindElements('ftui.deviceStates');
  280. ftui.log(1, 'call "plugins.update" done for "' + dev + ':' + par + '"');
  281. }
  282. };
  283. // -------- FTUI ----------
  284. var ftui = {
  285. version: '2.6.32',
  286. config: {
  287. DEBUG: false,
  288. DEMO: false,
  289. ICONDEMO: false,
  290. dir: '',
  291. filename: '',
  292. basedir: '',
  293. fhemDir: '',
  294. debuglevel: 0,
  295. doLongPoll: true,
  296. lang: 'de',
  297. toastPosition: 'bottom-left',
  298. shortpollInterval: 0,
  299. styleCollection: {},
  300. stdColors: ["green", "orange", "red", "ligthblue", "blue", "gray", "white", "mint"]
  301. },
  302. poll: {
  303. currLine: 0,
  304. xhr: null,
  305. longPollRequest: null,
  306. shortPollTimer: null,
  307. longPollTimer: null,
  308. lastUpdateTimestamp: new Date(),
  309. lastEventTimestamp: new Date(),
  310. lastShortpollTimestamp: new Date(),
  311. },
  312. states: {
  313. width: 0,
  314. lastSetOnline: 0,
  315. lastShortpoll: 0,
  316. longPollRestart: false
  317. },
  318. deviceStates: {},
  319. paramIdMap: {},
  320. timestampMap: {},
  321. subscriptions: {},
  322. subscriptionTs: {},
  323. gridster: {
  324. instances: {},
  325. instance: null,
  326. baseX: 0,
  327. baseY: 0,
  328. margins: 5,
  329. mincols: 0,
  330. cols: 0,
  331. rows: 0
  332. },
  333. init: function () {
  334. ftui.hideWidgets();
  335. ftui.paramIdMap = {};
  336. ftui.timestampMap = {};
  337. ftui.config.longPollType = $("meta[name='longpoll_type']").attr("content") || 'websocket';
  338. var longpoll = $("meta[name='longpoll']").attr("content") || '1';
  339. ftui.config.doLongPoll = (longpoll != '0');
  340. ftui.config.shortPollFilter = $("meta[name='shortpoll_filter']").attr("content");
  341. ftui.config.longPollFilter = $("meta[name='longpoll_filter']").attr("content");
  342. ftui.config.DEMO = ($("meta[name='demo']").attr("content") == '1');
  343. ftui.config.ICONDEMO = ($("meta[name='icondemo']").attr("content") == '1');
  344. ftui.config.debuglevel = $("meta[name='debug']").attr("content") || 0;
  345. ftui.config.webDevice = $("meta[name='web_device']").attr("content") || $.trim($('body').data('webname')) || 'WEB';
  346. ftui.config.maxLongpollAge = $("meta[name='longpoll_maxage']").attr("content") || 240;
  347. ftui.config.DEBUG = (ftui.config.debuglevel > 0);
  348. ftui.config.TOAST = $("meta[name='toast']").attr("content") || 5; //1,2,3...= n Toast-Messages, 0: No Toast-Messages
  349. ftui.config.toastPosition = $("meta[name='toast_position']").attr("content") || 'bottom-left';
  350. ftui.config.shortpollInterval = $("meta[name='shortpoll_only_interval']").attr("content") || 30;
  351. ftui.config.shortPollDelay = $("meta[name='shortpoll_restart_delay']").attr("content") || 3000;
  352. //self path
  353. var url = window.location.pathname;
  354. ftui.config.filename = url.substring(url.lastIndexOf('/') + 1);
  355. ftui.log(1, 'Filename: ' + ftui.config.filename);
  356. ftui.config.fhemDir = $("meta[name='fhemweb_url']").attr("content") || location.origin + "/fhem/";
  357. ftui.config.fhemDir = ftui.config.fhemDir.replace('///', '//');
  358. ftui.log(1, 'FHEM dir: ' + ftui.config.fhemDir);
  359. // lang
  360. var userLang = navigator.language || navigator.userLanguage;
  361. ftui.config.lang = $("meta[name='lang']").attr("content") || (ftui.isValid(userLang)) ? userLang.split('-')[0] : 'de';
  362. // credentials
  363. ftui.config.username = $("meta[name='username']").attr("content");
  364. ftui.config.password = $("meta[name='password']").attr("content");
  365. // subscriptions
  366. ftui.devs = [ftui.config.webDevice];
  367. ftui.reads = ['STATE'];
  368. // Get CSFS Token
  369. ftui.getCSrf();
  370. // init Toast
  371. function configureToast() {
  372. if ($.toast && !$('link[href$="lib/jquery.toast.min.css"]').length)
  373. $('head').append('<link rel="stylesheet" href="' + ftui.config.basedir +
  374. 'lib/jquery.toast.min.css" type="text/css" />');
  375. }
  376. if (!$.fn.toast) {
  377. ftui.dynamicload(ftui.config.basedir + "lib/jquery.toast.min.js", false).done(function () {
  378. configureToast();
  379. });
  380. } else {
  381. configureToast();
  382. }
  383. // after the page became visible, check server connection
  384. $(document).on('visibilitychange', function () {
  385. if (document.visibilityState === 'hidden') {
  386. // page is hidden
  387. } else {
  388. // page is visible
  389. ftui.log(1, 'Page became visible again -> start healthCheck in 3 secondes ');
  390. setTimeout(function () {
  391. ftui.healthCheck();
  392. }, 3000);
  393. }
  394. });
  395. try {
  396. // try to use localStorage
  397. localStorage.setItem('ftui', ftui.version);
  398. localStorage.removeItem('ftui');
  399. } catch (e) {
  400. // there was an error so...
  401. ftui.toast('You are in Privacy Mode<br>Please deactivate Privacy Mode and then reload the page.', 'error');
  402. }
  403. // detect clickEventType
  404. var android = ftui.getAndroidVersion();
  405. var iOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
  406. var onlyTouch = ((android && parseFloat(android) < 5) || iOS);
  407. ftui.config.clickEventType = (onlyTouch) ? 'touchstart' : 'touchstart mousedown';
  408. ftui.config.moveEventType = ((onlyTouch) ? 'touchmove' : 'touchmove mousemove');
  409. ftui.config.releaseEventType = ((onlyTouch) ? 'touchend' : 'touchend mouseup');
  410. ftui.config.leaveEventType = ((onlyTouch) ? 'touchleave' : 'touchleave mouseout');
  411. ftui.config.enterEventType = ((onlyTouch) ? 'touchenter' : 'touchenter mouseenter');
  412. //add background for modal dialogs
  413. $("<div id='shade' />").prependTo('body').hide();
  414. $('#shade').on(ftui.config.clickEventType, function (e) {
  415. $(document).trigger("shadeClicked");
  416. });
  417. ftui.readStatesLocal();
  418. // init FTUI CSS if not already loaded
  419. if ($('link[href$="css/fhem-tablet-ui.css"]').length === 0 &&
  420. $('link[href$="css/fhem-tablet-ui.min.css"]').length === 0 &&
  421. !f7) {
  422. var cssUrl = ftui.config.basedir + 'css/fhem-tablet-ui.css';
  423. $.when($.get(cssUrl, function () {
  424. $('<link>', {
  425. rel: 'stylesheet',
  426. type: 'text/css',
  427. 'href': cssUrl
  428. }).prependTo('head');
  429. })).then(function () {
  430. var ii = 0;
  431. var cssListener = setInterval(function () {
  432. ftui.log(1, 'fhem-tablet-ui.css dynamically loaded. Waiting until it is ready to use...');
  433. if ($("body").css("text-align") === "center") {
  434. ftui.log(1, 'fhem-tablet-ui.css is ready to use.');
  435. clearInterval(cssListener);
  436. ftui.loadStyleSchema();
  437. ftui.initPage();
  438. }
  439. ii++;
  440. if (ii > 120) {
  441. clearInterval(cssListener);
  442. ftui.toast("fhem-tablet-ui.css not ready to use", 'error');
  443. }
  444. }, 50);
  445. });
  446. } else {
  447. ftui.loadStyleSchema();
  448. ftui.initPage();
  449. }
  450. $(document).on("changedSelection", function () {
  451. $(
  452. '.gridster li > header ~ .hbox:only-of-type, ' +
  453. '.gridster li > header ~ .center:not([data-type]):only-of-type, ' +
  454. '.card > header ~ div:not([data-type]):only-of-type, ' +
  455. '.gridster li header ~ div:first-of-type:nth-last-of-type(1)'
  456. ).each(function (index) {
  457. var heightHeader = $(this).siblings('header').outerHeight();
  458. if (heightHeader > 0) {
  459. $(this).css({
  460. 'height': 'calc(100% - ' + $(this).siblings('header').outerHeight() + 'px)'
  461. });
  462. }
  463. });
  464. });
  465. $(document).on("initWidgetsDone", function () {
  466. // start shortpoll delayed
  467. ftui.startShortPollInterval(500);
  468. // restart longpoll
  469. ftui.states.longPollRestart = true;
  470. ftui.restartLongPoll();
  471. ftui.initHeaderLinks();
  472. // trigger refreshs
  473. $(document).trigger('changedSelection');
  474. if (!ftui.config.ICONDEMO) {
  475. ftui.disableSelection();
  476. }
  477. });
  478. if (!f7) {
  479. // dont show focus frame
  480. $("*:not(select):not(textarea)").focus(function () {
  481. $(this).blur();
  482. });
  483. }
  484. setInterval(function () {
  485. ftui.healthCheck();
  486. }, 60000);
  487. },
  488. initGridster: function (area) {
  489. ftui.gridster.minX = parseInt($("meta[name='widget_min_width'],meta[name='gridster_min_width']").attr("content") || 0);
  490. ftui.gridster.minY = parseInt($("meta[name='widget_min_height'],meta[name='gridster_min_height']").attr("content") || 0);
  491. ftui.gridster.baseX = parseInt($("meta[name='widget_base_width'],meta[name='gridster_base_width']").attr("content") || 0);
  492. ftui.gridster.baseY = parseInt($("meta[name='widget_base_height'],meta[name='gridster_base_height']").attr("content") || 0);
  493. ftui.gridster.cols = parseInt($("meta[name='gridster_cols']").attr("content") || 0);
  494. ftui.gridster.rows = parseInt($("meta[name='gridster_rows']").attr("content") || 0);
  495. ftui.gridster.resize = parseInt($("meta[name='gridster_resize']").attr("content") || (ftui.gridster.baseX + ftui.gridster.baseY) >
  496. 0 ? 0 : 1);
  497. if ($("meta[name='widget_margin'],meta[name='gridster_margin']").attr("content"))
  498. ftui.gridster.margins = parseInt($("meta[name='widget_margin'],meta[name='gridster_margin']").attr("content"));
  499. function configureGridster() {
  500. var highestCol = -1;
  501. var highestRow = -1;
  502. var baseX = 0;
  503. var baseY = 0;
  504. var cols = 0;
  505. var rows = 0;
  506. $(".gridster > ul > li").each(function () {
  507. var colVal = $(this).data("col") + $(this).data("sizex") - 1;
  508. if (colVal > highestCol)
  509. highestCol = colVal;
  510. var rowVal = $(this).data("row") + $(this).data("sizey") - 1;
  511. if (rowVal > highestRow)
  512. highestRow = rowVal;
  513. });
  514. //console.log(ftui.gridster.cols, ftui.gridster.rows, ftui.gridster.baseX, ftui.gridster.baseY);
  515. cols = (ftui.gridster.cols > 0) ? ftui.gridster.cols : highestCol;
  516. rows = (ftui.gridster.rows > 0) ? ftui.gridster.rows : highestRow;
  517. var colMargins = 2 * cols * ftui.gridster.margins;
  518. var rowMargins = 2 * rows * ftui.gridster.margins;
  519. baseX = (ftui.gridster.baseX > 0) ? ftui.gridster.baseX : (window.innerWidth - colMargins) / cols;
  520. baseY = (ftui.gridster.baseY > 0) ? ftui.gridster.baseY : (window.innerHeight - rowMargins) / rows;
  521. if (baseX < ftui.gridster.minX) {
  522. baseX = ftui.gridster.minX;
  523. }
  524. if (baseY < ftui.gridster.minY) {
  525. baseY = ftui.gridster.minY;
  526. }
  527. ftui.gridster.mincols = parseInt($("meta[name='widget_min_cols'],meta[name='gridster_min_cols']").attr("content") ||
  528. cols);
  529. if (ftui.gridster.instances[area])
  530. ftui.gridster.instances[area].destroy();
  531. ftui.gridster.instances[area] = $(".gridster > ul", area).gridster({
  532. widget_base_dimensions: [baseX, baseY],
  533. widget_margins: [ftui.gridster.margins, ftui.gridster.margins],
  534. draggable: {
  535. handle: '.gridster li > header'
  536. },
  537. min_cols: parseInt(ftui.gridster.mincols),
  538. }).data('gridster');
  539. if (ftui.gridster.instances[area]) {
  540. if ($("meta[name='gridster_disable']").attr("content") == '1') {
  541. ftui.gridster.instances[area].disable();
  542. }
  543. if ($("meta[name='gridster_starthidden']").attr("content") == '1') {
  544. $('.gridster').hide();
  545. }
  546. }
  547. // corrections for gridster in gridster element
  548. var gridgrid = $('.gridster > ul > li:has(* .gridster)');
  549. if (gridgrid.length > 0) {
  550. gridgrid.css({
  551. 'background-color': 'transparent',
  552. 'margin': '-' + ftui.gridster.margins + 'px',
  553. 'width': gridgrid.parent().width() - gridgrid.position().left,
  554. 'height': '100%'
  555. });
  556. }
  557. $('.gridster > ul > li >.center', area).parent().addClass('has_center');
  558. // max height for inner boxes
  559. $('.gridster > ul > li > .vbox', area).parent().addClass('has_vbox');
  560. }
  561. if ($('.gridster').length > 0) {
  562. if (!$('link[href$="lib/jquery.gridster.min.css"]').length)
  563. $('head').append('<link rel="stylesheet" href="' + ftui.config.basedir +
  564. 'lib/jquery.gridster.min.css" type="text/css" />');
  565. if (!$.fn.gridster) {
  566. ftui.dynamicload(ftui.config.basedir + "lib/jquery.gridster.min.js", false).done(function () {
  567. configureGridster();
  568. });
  569. } else {
  570. configureGridster();
  571. }
  572. if (ftui.gridster.resize) {
  573. $(window).on('resize', function () {
  574. if (ftui.states.width !== window.innerWidth) {
  575. clearTimeout(ftui.states.delayResize);
  576. ftui.states.delayResize = setTimeout(configureGridster, 500);
  577. ftui.states.width = window.innerWidth;
  578. }
  579. });
  580. }
  581. }
  582. },
  583. initPage: function (area) {
  584. //hideWidgets
  585. ftui.hideWidgets(area);
  586. //init gridster
  587. area = (ftui.isValid(area)) ? area : '';
  588. console.time('initPage');
  589. ftui.log(2, 'initPage - area=' + area);
  590. ftui.initGridster(area);
  591. //include extern html code
  592. var deferredArr = $.map($('[data-template]', area), function (templ, i) {
  593. var templElem = $(templ);
  594. return $.get(
  595. templElem.data('template'), {},
  596. function (data) {
  597. var parValues = templElem.data('parameter');
  598. for (var key in parValues) {
  599. data = data.replace(new RegExp(key, 'g'), parValues[key]);
  600. }
  601. templElem.html(data);
  602. }
  603. );
  604. });
  605. //get current values of readings not before all widgets are loaded
  606. $.when.apply(this, deferredArr).then(function () {
  607. //continue after loading the includes
  608. ftui.initWidgets(area);
  609. ftui.log(1, 'init templates - Done');
  610. });
  611. },
  612. initWidgets: function (area) {
  613. area = (ftui.isValid(area)) ? area : '';
  614. var types = [];
  615. ftui.log(3, plugins);
  616. plugins.removeArea(area);
  617. ftui.log(3, plugins);
  618. ftui.log(2, 'initWidgets - area=' + area);
  619. //collect required widgets types
  620. $('[data-type]', area).each(function (index) {
  621. var type = $(this).data("type");
  622. //console.log('type:' + type);
  623. if (types.indexOf(type) < 0) {
  624. types.push(type);
  625. }
  626. });
  627. //init widgets
  628. var deferredArr = $.map(types, function (type, i) {
  629. return plugins.load(type, area);
  630. });
  631. //get current values of readings not before all widgets are loaded
  632. $.when.apply(this, deferredArr).then(function () {
  633. plugins.updateParameters();
  634. ftui.log(1, 'initWidgets - Done');
  635. console.timeEnd('initPage');
  636. $(document).trigger("initWidgetsDone", [area]);
  637. });
  638. },
  639. initHeaderLinks: function () {
  640. if (($('[class*=fa-]').length > 0 ||
  641. $('[data-type="select"]').length > 0 ||
  642. $('[data-type="homestatus"]').length > 0) &&
  643. !$('link[href$="lib/font-awesome.min.css"]').length
  644. )
  645. $('head').append('<link rel="stylesheet" href="' + ftui.config.basedir + 'lib/font-awesome.min.css" type="text/css" />');
  646. if ($('[class*=oa-]').length > 0 && !$('link[href$="lib/openautomation.css"]').length)
  647. $('head').append('<link rel="stylesheet" href="' + ftui.config.basedir + 'lib/openautomation.css" type="text/css" />');
  648. if ($('[class*=fs-]').length > 0 && !$('link[href$="lib/fhemSVG.css"]').length)
  649. $('head').append('<link rel="stylesheet" href="' + ftui.config.basedir + 'lib/fhemSVG.css" type="text/css" />');
  650. if ($('[class*=mi-]').length > 0 && !$('link[href$="lib/material-icons.min.css"]').length)
  651. $('head').append('<link rel="stylesheet" href="' + ftui.config.basedir +
  652. 'lib/material-icons.min.css" type="text/css" />');
  653. if ($('[class*=wi-]').length > 0 && !$('link[href$="lib/weather-icons.min.css"]').length)
  654. $('head').append('<link rel="stylesheet" href="' + ftui.config.basedir +
  655. 'lib/weather-icons.min.css" type="text/css" />');
  656. if ($('[class*=wi-wind]').length > 0 && !$('link[href$="lib/weather-icons-wind.min.css"]').length)
  657. $('head').append('<link rel="stylesheet" href="' + ftui.config.basedir +
  658. 'lib/weather-icons-wind.min.css" type="text/css" />');
  659. },
  660. startLongpoll: function () {
  661. ftui.log(2, 'startLongpoll: ' + ftui.config.doLongPoll);
  662. ftui.poll.lastEventTimestamp = new Date();
  663. if (ftui.config.doLongPoll) {
  664. ftui.config.shortpollInterval = $("meta[name='shortpoll_interval']").attr("content") || 15 * 60; // 15 minutes
  665. ftui.longPollTimer = setTimeout(function () {
  666. ftui.longPoll();
  667. }, 100);
  668. }
  669. },
  670. stopLongpoll: function () {
  671. ftui.log(2, 'stopLongpoll');
  672. clearInterval(ftui.longPollTimer);
  673. if (ftui.longPollRequest)
  674. ftui.longPollRequest.abort();
  675. if (ftui.websocket) {
  676. //ftui.websocket.send('bye');
  677. ftui.websocket.close();
  678. ftui.websocket = undefined;
  679. ftui.log(2, 'stopped websocket');
  680. }
  681. },
  682. restartLongPoll: function (msg, error) {
  683. ftui.log(2, 'restartLongpoll');
  684. var delay;
  685. clearTimeout(ftui.longPollTimer);
  686. if (msg) {
  687. ftui.toast("Disconnected from FHEM<br>" + msg, error);
  688. }
  689. ftui.stopLongpoll();
  690. if (ftui.states.longPollRestart) {
  691. delay = 2000;
  692. } else {
  693. ftui.toast("Retry to connect in 10 seconds");
  694. delay = 10000;
  695. }
  696. ftui.longPollTimer = setTimeout(function () {
  697. ftui.startLongpoll();
  698. }, delay);
  699. },
  700. startShortPollInterval: function (delay) {
  701. ftui.log(1, 'start shortpoll in (ms):' + (delay || ftui.config.shortpollInterval * 1000));
  702. clearInterval(ftui.shortPollTimer);
  703. ftui.shortPollTimer = setTimeout(function () {
  704. //get current values of readings every x seconds
  705. ftui.shortPoll();
  706. ftui.startShortPollInterval();
  707. }, (delay || ftui.config.shortpollInterval * 1000));
  708. },
  709. shortPoll: function (silent) {
  710. var ltime = new Date().getTime() / 1000;
  711. if ((ltime - ftui.states.lastShortpoll) < ftui.config.shortpollInterval)
  712. return;
  713. ftui.log(1, 'start shortpoll');
  714. var startTime = new Date();
  715. // invalidate all readings for detection of outdated ones
  716. for (var i = 0, len = ftui.devs.length; i < len; i++) {
  717. var params = ftui.deviceStates[ftui.devs[i]];
  718. for (var reading in params) {
  719. params[reading].valid = false;
  720. }
  721. }
  722. console.time('get jsonlist2');
  723. ftui.shortPollRequest =
  724. ftui.sendFhemCommand('jsonlist2 ' + ftui.poll.shortPollFilter)
  725. .done(function (fhemJSON) {
  726. console.timeEnd('get jsonlist2');
  727. console.time('read jsonlist2');
  728. ftui.log(3, 'fhemJSON: 0=' + Object.keys(fhemJSON)[0] + ' 1=' + Object.keys(fhemJSON)[1]);
  729. // function to import data
  730. function checkReading(device, section) {
  731. for (var reading in section) {
  732. var isUpdated = false;
  733. var paramid = (reading === 'STATE') ? device : [device, reading].join('-');
  734. var newParam = section[reading];
  735. if (typeof newParam !== 'object') {
  736. //ftui.log(5,'newParam='+newParam);
  737. newParam = {
  738. "Value": newParam,
  739. "Time": ''
  740. };
  741. }
  742. // is there a subscription, then check and update widgets
  743. if (ftui.subscriptions[paramid]) {
  744. var oldParam = ftui.getDeviceParameter(device, reading);
  745. isUpdated = (!oldParam || oldParam.val !== newParam.Value || oldParam.date !== newParam.Time);
  746. //ftui.log(5,'isUpdated='+isUpdated);
  747. }
  748. //write into internal cache object
  749. var params = ftui.deviceStates[device] || {};
  750. var param = params[reading] || {};
  751. param.date = newParam.Time;
  752. param.val = newParam.Value;
  753. //console.log('*****',device);
  754. param.valid = true;
  755. params[reading] = param;
  756. ftui.deviceStates[device] = params;
  757. ftui.paramIdMap[paramid] = {};
  758. ftui.paramIdMap[paramid].device = device;
  759. ftui.paramIdMap[paramid].reading = reading;
  760. ftui.timestampMap[paramid + '-ts'] = {};
  761. ftui.timestampMap[paramid + '-ts'].device = device;
  762. ftui.timestampMap[paramid + '-ts'].reading = reading;
  763. //update widgets only if necessary
  764. if (isUpdated) {
  765. ftui.log(5, '[shortPoll] do update for ' + device + ',' + reading);
  766. plugins.update(device, reading);
  767. }
  768. }
  769. }
  770. // import the whole fhemJSON
  771. if (fhemJSON && fhemJSON.Results) {
  772. var len = fhemJSON.Results.length;
  773. ftui.log(2, 'shortpoll: fhemJSON.Results.length=' + len);
  774. var results = fhemJSON.Results;
  775. for (var i = len - 1; i >= 0; i -= 1) {
  776. var res = results[i];
  777. var devName = res.Name;
  778. if (devName.indexOf('FHEMWEB') < 0 && devName.indexOf('WEB_') < 0) {
  779. checkReading(devName, res.Internals);
  780. checkReading(devName, res.Attributes);
  781. checkReading(devName, res.Readings);
  782. }
  783. }
  784. // finished
  785. var duration = ftui.diffSeconds(startTime, new Date());
  786. if (ftui.config.DEBUG) {
  787. var paramCount = Object.keys(ftui.paramIdMap).length;
  788. ftui.toast("Full refresh done in " +
  789. duration + "s for " +
  790. paramCount + " parameter(s)");
  791. }
  792. ftui.log(1, 'shortPoll - Done');
  793. ftui.states.lastShortpoll = ltime;
  794. ftui.poll.lastShortpollTimestamp = new Date();
  795. ftui.saveStatesLocal();
  796. ftui.updateBindElements('ftui.');
  797. if (!silent) {
  798. ftui.onUpdateDone();
  799. }
  800. } else {
  801. ftui.log(1, "shortPoll request failed: Result is null");
  802. ftui.toast("<u>ShortPoll Request Failed: : Result is null </u><br>", 'error');
  803. }
  804. console.timeEnd('read jsonlist2');
  805. })
  806. .fail(function (jqxhr, textStatus, error) {
  807. var err = textStatus + ", " + error;
  808. ftui.log(1, "shortPoll request failed: " + err);
  809. ftui.states.lastSetOnline = 0;
  810. ftui.states.lastShortpoll = 0;
  811. if (textStatus.indexOf('parsererror') < 0) {
  812. ftui.toast("<u>ShortPoll Request Failed, will retry in " + ftui.config.shortPollDelay / 1000 + "s</u><br>" +
  813. err, 'error');
  814. ftui.getCSrf();
  815. ftui.startShortPollInterval(3000);
  816. } else {
  817. ftui.toast("<u>ShortPoll Request Failed</u><br>" + err, 'error');
  818. }
  819. });
  820. },
  821. longPoll: function () {
  822. if (ftui.config.DEMO) {
  823. console.log('DEMO-Mode: no longpoll');
  824. return;
  825. }
  826. if ('WebSocket' in window &&
  827. ftui.config.longPollType === 'websocket' &&
  828. ftui.deviceStates[ftui.config.webDevice] &&
  829. ftui.deviceStates[ftui.config.webDevice].longpoll &&
  830. ftui.deviceStates[ftui.config.webDevice].longpoll.val &&
  831. ftui.deviceStates[ftui.config.webDevice].longpoll.val === 'websocket') {
  832. if (ftui.websocket) {
  833. ftui.log(3, 'valid ftui.websocket found');
  834. return;
  835. }
  836. if (ftui.config.DEBUG) {
  837. ftui.toast("Longpoll (WebSocket) started");
  838. }
  839. ftui.poll.URL = ftui.config.fhemDir.replace(/^http/i, "ws") + "?XHR=1&inform=type=status;filter=" +
  840. ftui.poll.longPollFilter + ";since=" + ftui.poll.lastEventTimestamp.getTime() + ";fmt=JSON" +
  841. "&timestamp=" + new Date().getTime();
  842. //"&fwcsrf=" + ftui.config.csrf;
  843. ftui.log(1, 'websockets URL=' + ftui.poll.URL);
  844. ftui.states.longPollRestart = false;
  845. ftui.websocket = new WebSocket(ftui.poll.URL);
  846. ftui.websocket.onclose = function (event) {
  847. var reason;
  848. if (event.code == 1000)
  849. reason =
  850. "Normal closure, meaning that the purpose for which the connection was established has been fulfilled.";
  851. else if (event.code == 1001)
  852. reason =
  853. "An endpoint is \"going away\", such as a server going down or a browser having navigated away from a page.";
  854. else if (event.code == 1002)
  855. reason = "An endpoint is terminating the connection due to a protocol error";
  856. else if (event.code == 1003)
  857. reason =
  858. "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).";
  859. else if (event.code == 1004)
  860. reason = "Reserved. The specific meaning might be defined in the future.";
  861. else if (event.code == 1005)
  862. reason = "No status code was actually present.";
  863. else if (event.code == 1006)
  864. reason = "The connection was closed abnormally, e.g., without sending or receiving a Close control frame";
  865. else if (event.code == 1007)
  866. reason =
  867. "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).";
  868. else if (event.code == 1008)
  869. reason =
  870. "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.";
  871. else if (event.code == 1009)
  872. reason =
  873. "An endpoint is terminating the connection because it has received a message that is too big for it to process.";
  874. else if (event.code == 1010) // Note that this status code is not used by the server, because it can fail the WebSocket handshake instead.
  875. reason =
  876. "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. <br /> Specifically, the extensions that are needed are: " +
  877. event.reason;
  878. else if (event.code == 1011)
  879. reason =
  880. "A server is terminating the connection because it encountered an unexpected condition that prevented it from fulfilling the request.";
  881. else if (event.code == 1015)
  882. reason =
  883. "The connection was closed due to a failure to perform a TLS handshake (e.g., the server certificate can't be verified).";
  884. else
  885. reason = "Unknown reason";
  886. ftui.log(1, "websocket (url=" + event.target.url + ") closed! reason=" + reason);
  887. // if current socket closes then restart websocket
  888. if (event.target.url === ftui.poll.URL) {
  889. ftui.restartLongPoll(reason);
  890. }
  891. };
  892. ftui.websocket.onerror = function (event) {
  893. ftui.log(1, "Error while longpoll: " + event.data);
  894. if (ftui.config.debuglevel > 1 && event.target.url === ftui.poll.URL) {
  895. ftui.toast("Error while longpoll (websocket)", 'error');
  896. }
  897. };
  898. ftui.websocket.onmessage = function (msg) {
  899. ftui.handleUpdates(msg.data);
  900. };
  901. } else {
  902. ftui.log(1, 'longpoll: websockets not supportetd or not activated > fall back to AJAX');
  903. if (ftui.xhr) {
  904. ftui.log(3, 'valid ftui.xhr found');
  905. return;
  906. }
  907. if (ftui.longPollRequest) {
  908. ftui.log(3, 'valid ftui.longPollRequest found');
  909. return;
  910. }
  911. ftui.poll.currLine = 0;
  912. if (ftui.config.DEBUG) {
  913. if (ftui.states.longPollRestart)
  914. ftui.toast("Longpoll (AJAX) re-started");
  915. else
  916. ftui.toast("Longpoll (AJAX) started");
  917. }
  918. ftui.log(1, (ftui.states.longPollRestart) ? "Longpoll re-started" : "Longpoll started");
  919. ftui.states.longPollRestart = false;
  920. ftui.longPollRequest = $.ajax({
  921. url: ftui.config.fhemDir,
  922. cache: false,
  923. async: true,
  924. method: 'GET',
  925. data: {
  926. XHR: 1,
  927. inform: "type=status;filter=" + ftui.poll.longPollFilter + ";since=" +
  928. ftui.poll.lastEventTimestamp.getTime() + ";fmt=JSON",
  929. fwcsrf: ftui.config.csrf
  930. },
  931. username: ftui.config.username,
  932. password: ftui.config.password,
  933. xhr: function () {
  934. ftui.xhr = new window.XMLHttpRequest();
  935. ftui.xhr.addEventListener("readystatechange", function (e) {
  936. var data = e.target.responseText;
  937. if (e.target.readyState === 4) {
  938. return;
  939. }
  940. if (e.target.readyState === 3) {
  941. ftui.handleUpdates(data);
  942. }
  943. }, false);
  944. ftui.log(1, 'ajax lomgpoll responseURL=' + ftui.xhr.responseURL);
  945. ftui.log(1, 'ajax longpol statusText=' + ftui.xhr.statusText);
  946. return ftui.xhr;
  947. }
  948. })
  949. .done(function (data) {
  950. if (ftui.xhr) {
  951. ftui.xhr.abort();
  952. ftui.xhr = null;
  953. }
  954. ftui.longPollRequest = null;
  955. if (ftui.states.longPollRestart) {
  956. ftui.longPoll();
  957. } else {
  958. ftui.log(1, "Disconnected from FHEM - poll done - " + data);
  959. ftui.restartLongPoll(data);
  960. }
  961. })
  962. .fail(function (jqXHR, textStatus, errorThrown) {
  963. if (ftui.xhr) {
  964. ftui.xhr.abort();
  965. ftui.xhr = null;
  966. }
  967. ftui.longPollRequest = null;
  968. if (ftui.states.longPollRestart) {
  969. ftui.longPoll();
  970. } else {
  971. ftui.log(1, "Error while longpoll: " + textStatus + ": " + errorThrown);
  972. if (ftui.config.debuglevel > 1) {
  973. ftui.toast("Error while longpoll (ajax)<br>" + textStatus + ": " + errorThrown, 'error');
  974. }
  975. ftui.restartLongPoll(textStatus + ": " + errorThrown);
  976. }
  977. });
  978. }
  979. },
  980. handleUpdates: function (data) {
  981. var lines = data.split(/\n/);
  982. for (var i = ftui.poll.currLine, len = lines.length; i < len; i++) {
  983. ftui.log(5, lines[i]);
  984. var lastChar = lines[i].slice(-1);
  985. if (ftui.isValid(lines[i]) && lines[i] !== '' && lastChar === "]") {
  986. try {
  987. var dataJSON = JSON.parse(lines[i]);
  988. var params = null;
  989. var param = null;
  990. var isSTATE = (dataJSON[1] !== dataJSON[2]);
  991. var isTrigger = (dataJSON[1] === '' && dataJSON[2] === '');
  992. ftui.log(4, dataJSON);
  993. var pmap = ftui.paramIdMap[dataJSON[0]];
  994. var tmap = ftui.timestampMap[dataJSON[0]];
  995. var subscription = ftui.subscriptions[dataJSON[0]];
  996. // update for a parameter
  997. if (pmap) {
  998. if (isSTATE)
  999. pmap.reading = 'STATE';
  1000. params = ftui.deviceStates[pmap.device] || {};
  1001. param = params[pmap.reading] || {};
  1002. param.val = dataJSON[1];
  1003. param.valid = true;
  1004. params[pmap.reading] = param;
  1005. ftui.deviceStates[pmap.device] = params;
  1006. // dont wait for timestamp for STATE paramters
  1007. if (isSTATE && ftui.subscriptions[dataJSON[0]]) {
  1008. ftui.poll.lastDevice = pmap.device;
  1009. ftui.poll.lastReading = pmap.reading;
  1010. ftui.poll.lastValue = param.val;
  1011. plugins.update(pmap.device, pmap.reading);
  1012. }
  1013. }
  1014. // update for a timestamp
  1015. // STATE updates has no timestamp
  1016. if (tmap && !isSTATE) {
  1017. params = ftui.deviceStates[tmap.device] || {};
  1018. param = params[tmap.reading] || {};
  1019. param.date = dataJSON[1];
  1020. params[tmap.reading] = param;
  1021. ftui.poll.lastUpdateTimestamp = param.date.toDate();
  1022. ftui.deviceStates[tmap.device] = params;
  1023. // paramter + timestamp update now completed -> update widgets
  1024. if (ftui.subscriptionTs[dataJSON[0]]) {
  1025. ftui.poll.lastDevice = tmap.device;
  1026. ftui.poll.lastReading = tmap.reading;
  1027. ftui.poll.lastValue = param.val;
  1028. plugins.update(tmap.device, tmap.reading);
  1029. }
  1030. }
  1031. // just a trigger
  1032. if (isTrigger && subscription) {
  1033. plugins.update(subscription.device, subscription.reading);
  1034. }
  1035. } catch (err) {
  1036. ftui.log(1, "Error: (longpoll) " + err);
  1037. ftui.log(1, "Bad line : " + lines[i]);
  1038. }
  1039. }
  1040. }
  1041. ftui.poll.lastEventTimestamp = new Date();
  1042. ftui.updateBindElements('ftui.poll');
  1043. if (!ftui.websocket) {
  1044. // Ajax longpoll
  1045. // cumulative data -> remember last line
  1046. // restart after 9999 lines to avoid overflow
  1047. ftui.poll.currLine = lines.length - 1;
  1048. if (ftui.poll.currLine > 9999) {
  1049. ftui.states.longPollRestart = true;
  1050. ftui.longPollRequest.abort();
  1051. }
  1052. }
  1053. },
  1054. setFhemStatus: function (cmdline) {
  1055. if (ftui.config.DEMO) {
  1056. console.log('DEMO-Mode: no setFhemStatus');
  1057. return;
  1058. }
  1059. // postpone update
  1060. ftui.startShortPollInterval();
  1061. ftui.sendFhemCommand(cmdline);
  1062. },
  1063. sendFhemCommand: function (cmdline) {
  1064. cmdline = cmdline.replace(' ', ' ');
  1065. var dataType = (cmdline.substr(0, 8) == "jsonlist") ? 'json' : 'text';
  1066. ftui.log(1, 'send to FHEM: ' + cmdline);
  1067. return $.ajax({
  1068. async: true,
  1069. cache: false,
  1070. method: 'GET',
  1071. dataType: dataType,
  1072. url: ftui.config.fhemDir,
  1073. username: ftui.config.username,
  1074. password: ftui.config.password,
  1075. data: {
  1076. cmd: cmdline,
  1077. fwcsrf: ftui.config.csrf,
  1078. XHR: "1"
  1079. },
  1080. error: function (jqXHR, textStatus, errorThrown) {
  1081. ftui.toast("<u>FHEM Command failed</u><br>" + textStatus + ": " + errorThrown, 'error');
  1082. }
  1083. });
  1084. },
  1085. loadStyleSchema: function () {
  1086. $.each($('link[href$="-ui.css"],link[href$="-ui.min.css"]'), function (index, thisSheet) {
  1087. if (!thisSheet || !thisSheet.sheet || !thisSheet.sheet.cssRules) return;
  1088. var rules = thisSheet.sheet.cssRules;
  1089. for (var r in rules) {
  1090. if (rules[r].style) {
  1091. var styles = rules[r].style.cssText.split(';');
  1092. styles.pop();
  1093. var elmName = rules[r].selectorText;
  1094. var params = {};
  1095. for (var s in styles) {
  1096. var param = styles[s].toString().split(':');
  1097. if (param[0].match(/color/)) {
  1098. params[$.trim(param[0])] = ftui.rgbToHex($.trim(param[1]).replace('! important', '').replace(
  1099. '!important', ''));
  1100. }
  1101. }
  1102. if (Object.keys(params).length > 0)
  1103. ftui.config.styleCollection[elmName] = params;
  1104. }
  1105. }
  1106. });
  1107. },
  1108. onUpdateDone: function () {
  1109. $(document).trigger("updateDone");
  1110. ftui.checkInvalidElements();
  1111. ftui.updateBindElements();
  1112. },
  1113. checkInvalidElements: function () {
  1114. $('.autohide[data-get]').each(function (index) {
  1115. var elem = $(this);
  1116. var valid = elem.getReading('get').valid;
  1117. if (valid && valid === true)
  1118. elem.removeClass('invalid');
  1119. else
  1120. elem.addClass('invalid');
  1121. });
  1122. },
  1123. updateBindElements: function (filter) {
  1124. $('[data-bind*="' + filter + '"]').each(function (index) {
  1125. var elem = $(this);
  1126. var variable = elem.data('bind');
  1127. if (variable) {
  1128. elem.text(eval(variable));
  1129. }
  1130. });
  1131. },
  1132. setOnline: function () {
  1133. var ltime = new Date().getTime() / 1000;
  1134. if ((ltime - ftui.states.lastSetOnline) > 60) {
  1135. if (ftui.config.DEBUG) ftui.toast("FHEM connected");
  1136. ftui.states.lastSetOnline = ltime;
  1137. // force shortpoll
  1138. ftui.states.lastShortpoll = 0;
  1139. ftui.startShortPollInterval(1000);
  1140. if (!ftui.config.doLongPoll) {
  1141. var longpoll = $("meta[name='longpoll']").attr("content") || '1';
  1142. ftui.config.doLongPoll = (longpoll != '0');
  1143. ftui.states.longPollRestart = false;
  1144. if (ftui.config.doLongPoll) {
  1145. ftui.startLongpoll();
  1146. }
  1147. }
  1148. ftui.log(1, 'FTUI is online');
  1149. }
  1150. },
  1151. setOffline: function () {
  1152. if (ftui.config.DEBUG) ftui.toast("Lost connection to FHEM");
  1153. ftui.config.doLongPoll = false;
  1154. ftui.states.longPollRestart = true;
  1155. clearInterval(ftui.shortPollTimer);
  1156. ftui.stopLongpoll();
  1157. ftui.saveStatesLocal();
  1158. ftui.log(1, 'FTUI is offline');
  1159. },
  1160. readStatesLocal: function () {
  1161. if (!ftui.config.DEMO)
  1162. ftui.deviceStates = JSON.parse(localStorage.getItem('deviceStates')) || {};
  1163. else {
  1164. $.ajax({
  1165. async: false,
  1166. method: 'GET',
  1167. url: "/fhem/tablet/data/" + ftui.config.filename.replace(".html", ".dat"),
  1168. })
  1169. .done(function (data) {
  1170. ftui.deviceStates = JSON.parse(data) || {};
  1171. });
  1172. }
  1173. },
  1174. saveStatesLocal: function () {
  1175. //save deviceStates into localStorage
  1176. var dataToStore = JSON.stringify(ftui.deviceStates);
  1177. localStorage.setItem('deviceStates', dataToStore);
  1178. localStorage.setItem('shortPollDuration', ftui.poll.shortPollDuration);
  1179. },
  1180. getDeviceParameter: function (devname, paraname) {
  1181. if (devname && devname.length > 0) {
  1182. var params = ftui.deviceStates[devname];
  1183. return (params && params[paraname]) ? params[paraname] : null;
  1184. }
  1185. return null;
  1186. },
  1187. loadPlugin: function (name, area) {
  1188. var deferredLoad = new $.Deferred();
  1189. ftui.log(2, 'Create widget : ' + name);
  1190. // get the plugin
  1191. ftui.dynamicload(ftui.config.basedir + "js/widget_" + name + ".js", true).done(function () {
  1192. // get all dependencies of this plugin
  1193. var depsPromises = [];
  1194. var getDependencies = window["depends_" + name];
  1195. // load all dependencies recursive before
  1196. if ($.isFunction(getDependencies)) {
  1197. var deps = getDependencies();
  1198. if (deps) {
  1199. deps = ($.isArray(deps)) ? deps : [deps];
  1200. $.map(deps, function (dep, i) {
  1201. if (dep.indexOf(".js") < 0) {
  1202. depsPromises.push(ftui.loadPlugin(dep));
  1203. } else {
  1204. depsPromises.push(ftui.dynamicload(dep, false));
  1205. }
  1206. });
  1207. }
  1208. } else {
  1209. ftui.log(2, "function depends_" + name + " not found (maybe ok)");
  1210. }
  1211. $.when.apply(this, depsPromises).always(function () {
  1212. var module = (window["Modul_" + name]) ? new window["Modul_" + name]() : null;
  1213. if (module) {
  1214. if (typeof area !== 'undefined') {
  1215. // add only real widgets not dependencies
  1216. plugins.addModule(module);
  1217. if (ftui.isValid(area))
  1218. module.area = area;
  1219. ftui.log(1, 'Try to init plugin: ' + name);
  1220. module.init();
  1221. //update all what we have until now
  1222. for (var key in module.subscriptions) {
  1223. module.update(module.subscriptions[key].device, module.subscriptions[key].reading);
  1224. }
  1225. }
  1226. ftui.log(1, 'Loaded plugin: ' + name);
  1227. $('[data-type="' + name + '"]', area).removeClass('widget-hide');
  1228. } else {
  1229. ftui.log(1, 'Failed to create widget: ' + name);
  1230. }
  1231. deferredLoad.resolve();
  1232. });
  1233. })
  1234. .fail(function () {
  1235. ftui.toast('Failed to load plugin : ' + name);
  1236. ftui.log(1, 'Failed to load plugin : ' + name + ' - add <script src="js/widget_' + name +
  1237. '.js" defer></script> do your page, to see more informations about this failure');
  1238. deferredLoad.resolve();
  1239. });
  1240. // return with promise to deliver the plugin deferred
  1241. return deferredLoad.promise();
  1242. },
  1243. dynamicload: function (url, async) {
  1244. var cache = (ftui.config.DEBUG) ? false : true;
  1245. ftui.log(3, 'dynamic load file:' + url + ' / async:' + async);
  1246. var deferred = new $.Deferred();
  1247. var script = document.createElement("script");
  1248. script.type = "text/javascript";
  1249. script.async = (async) ? true : false;
  1250. script.src = url;
  1251. script.onload = function () {
  1252. ftui.log(3, 'dynamic load done:' + url);
  1253. deferred.resolve();
  1254. };
  1255. document.getElementsByTagName('head')[0].appendChild(script);
  1256. return deferred.promise();
  1257. },
  1258. getCSrf: function () {
  1259. $.ajax({
  1260. 'url': ftui.config.fhemDir,
  1261. 'type': 'GET',
  1262. cache: false,
  1263. username: ftui.config.username,
  1264. password: ftui.config.password,
  1265. data: {
  1266. XHR: "1"
  1267. },
  1268. 'success': function (data, textStatus, jqXHR) {
  1269. ftui.config.csrf = jqXHR.getResponseHeader('X-FHEM-csrfToken');
  1270. ftui.log(1, 'Got csrf from FHEM:' + ftui.config.csrf);
  1271. }
  1272. }).fail(function (jqXHR, textStatus, errorThrown) {
  1273. ftui.log(1, "Failed to get csrfToken: " + textStatus + ": " + errorThrown);
  1274. ftui.config.shortPollDelay = 30000;
  1275. });
  1276. },
  1277. healthCheck: function () {
  1278. if (ftui.config.debuglevel > 0) {
  1279. var d = new Date();
  1280. d.setTime(ftui.states.lastShortpoll * 1000);
  1281. console.log('--------- start healthCheck --------------');
  1282. console.log('now: ' + new Date());
  1283. console.log('FTUI version: ' + ftui.version);
  1284. console.log('Longpoll: ' + ftui.config.doLongPoll);
  1285. console.log('Longpoll type: ' + ftui.config.longPollType);
  1286. console.log('Longpoll objects there: ' + (ftui.isValid(ftui.longPollRequest) && ftui.isValid(ftui.xhr) || ftui.isValid(
  1287. ftui.websocket)));
  1288. console.log('Longpoll current line: ' + ftui.poll.currLine);
  1289. console.log('Longpoll last event before: ' + ftui.poll.lastEventTimestamp.ago());
  1290. console.log('Longpoll last reading update before: ' + ftui.poll.lastUpdateTimestamp.ago());
  1291. console.log('Shortpoll interval: ' + ftui.config.shortpollInterval);
  1292. console.log('Shortpoll last run before: ' + d.ago());
  1293. console.log('FHEM dev/par count: ' + Object.keys(ftui.paramIdMap).length);
  1294. console.log('FTUI known devices count: ' + Object.keys(ftui.deviceStates).length);
  1295. console.log('Page length: ' + $('html').html().length);
  1296. console.log('Widgets count: ' + $('[data-type]').length);
  1297. console.log('--------- end healthCheck ---------------');
  1298. }
  1299. var timeDiff = new Date() - ftui.poll.lastEventTimestamp;
  1300. if (timeDiff / 1000 > ftui.config.maxLongpollAge &&
  1301. ftui.config.maxLongpollAge > 0 &&
  1302. !ftui.config.DEMO &&
  1303. ftui.config.doLongPoll) {
  1304. ftui.log(1, 'No longpoll event since ' + timeDiff / 1000 + 'secondes -> restart polling');
  1305. ftui.setOnline();
  1306. ftui.restartLongPoll();
  1307. }
  1308. },
  1309. FS20: {
  1310. 'dimmerArray': [0, 6, 12, 18, 25, 31, 37, 43, 50, 56, 62, 68, 75, 81, 87, 93, 100],
  1311. 'dimmerValue': function (value) {
  1312. var idx = ftui.indexOfNumeric(this.dimmerArray, value);
  1313. return (idx > -1) ? this.dimmerArray[idx] : 0;
  1314. }
  1315. },
  1316. rgbToHsl: function (rgb) {
  1317. var r = parseInt(rgb.substring(0, 2), 16);
  1318. var g = parseInt(rgb.substring(2, 4), 16);
  1319. var b = parseInt(rgb.substring(4, 6), 16);
  1320. r /= 255;
  1321. g /= 255;
  1322. b /= 255;
  1323. var max = Math.max(r, g, b),
  1324. min = Math.min(r, g, b);
  1325. var h, s, l = (max + min) / 2;
  1326. if (max == min) {
  1327. h = s = 0; // achromatic
  1328. } else {
  1329. var d = max - min;
  1330. s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
  1331. switch (max) {
  1332. case r:
  1333. h = (g - b) / d + (g < b ? 6 : 0);
  1334. break;
  1335. case g:
  1336. h = (b - r) / d + 2;
  1337. break;
  1338. case b:
  1339. h = (r - g) / d + 4;
  1340. break;
  1341. }
  1342. h /= 6;
  1343. }
  1344. return [h, s, l];
  1345. },
  1346. hslToRgb: function (h, s, l) {
  1347. var r, g, b;
  1348. var hex = function (x) {
  1349. return ("0" + parseInt(x).toString(16)).slice(-2);
  1350. };
  1351. var hue2rgb;
  1352. if (s === 0) {
  1353. r = g = b = l; // achromatic
  1354. } else {
  1355. hue2rgb = function (p, q, t) {
  1356. if (t < 0) t += 1;
  1357. if (t > 1) t -= 1;
  1358. if (t < 1 / 6) return p + (q - p) * 6 * t;
  1359. if (t < 1 / 2) return q;
  1360. if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
  1361. return p;
  1362. };
  1363. var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
  1364. var p = 2 * l - q;
  1365. r = hue2rgb(p, q, h + 1 / 3);
  1366. g = hue2rgb(p, q, h);
  1367. b = hue2rgb(p, q, h - 1 / 3);
  1368. }
  1369. return [hex(Math.round(r * 255)), hex(Math.round(g * 255)), hex(Math.round(b * 255))].join('');
  1370. },
  1371. rgbToHex: function (rgb) {
  1372. var tokens = rgb.match(/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?/i);
  1373. return (tokens && tokens.length === 4) ? "#" +
  1374. ("0" + parseInt(tokens[1], 10).toString(16)).slice(-2) +
  1375. ("0" + parseInt(tokens[2], 10).toString(16)).slice(-2) +
  1376. ("0" + parseInt(tokens[3], 10).toString(16)).slice(-2) : rgb;
  1377. },
  1378. getGradientColor: function (start_color, end_color, percent) {
  1379. // strip the leading # if it's there
  1380. start_color = this.rgbToHex(start_color).replace(/^\s*#|\s*$/g, '');
  1381. end_color = this.rgbToHex(end_color).replace(/^\s*#|\s*$/g, '');
  1382. // convert 3 char codes --> 6, e.g. `E0F` --> `EE00FF`
  1383. if (start_color.length == 3) {
  1384. start_color = start_color.replace(/(.)/g, '$1$1');
  1385. }
  1386. if (end_color.length == 3) {
  1387. end_color = end_color.replace(/(.)/g, '$1$1');
  1388. }
  1389. // get colors
  1390. var start_red = parseInt(start_color.substr(0, 2), 16),
  1391. start_green = parseInt(start_color.substr(2, 2), 16),
  1392. start_blue = parseInt(start_color.substr(4, 2), 16);
  1393. var end_red = parseInt(end_color.substr(0, 2), 16),
  1394. end_green = parseInt(end_color.substr(2, 2), 16),
  1395. end_blue = parseInt(end_color.substr(4, 2), 16);
  1396. // calculate new color
  1397. var diff_red = end_red - start_red;
  1398. var diff_green = end_green - start_green;
  1399. var diff_blue = end_blue - start_blue;
  1400. diff_red = ((diff_red * percent) + start_red).toString(16).split('.')[0];
  1401. diff_green = ((diff_green * percent) + start_green).toString(16).split('.')[0];
  1402. diff_blue = ((diff_blue * percent) + start_blue).toString(16).split('.')[0];
  1403. // ensure 2 digits by color
  1404. if (diff_red.length == 1)
  1405. diff_red = '0' + diff_red;
  1406. if (diff_green.length == 1)
  1407. diff_green = '0' + diff_green;
  1408. if (diff_blue.length == 1)
  1409. diff_blue = '0' + diff_blue;
  1410. return '#' + diff_red + diff_green + diff_blue;
  1411. },
  1412. getPart: function (value, part) {
  1413. if (ftui.isValid(part)) {
  1414. if ($.isNumeric(part)) {
  1415. var tokens = (ftui.isValid(value)) ? value.toString().split(" ") : '';
  1416. return (tokens.length >= part && part > 0) ? tokens[part - 1] : value;
  1417. } else {
  1418. var ret = '';
  1419. if (ftui.isValid(value)) {
  1420. var matches = value.match(new RegExp('^' + part + '$'));
  1421. if (matches) {
  1422. for (var i = 1, len = matches.length; i < len; i++) {
  1423. ret += matches[i];
  1424. }
  1425. }
  1426. }
  1427. return ret;
  1428. }
  1429. }
  1430. return value;
  1431. },
  1432. showModal: function (modal) {
  1433. if (modal)
  1434. $("#shade").fadeIn();
  1435. else
  1436. $("#shade").fadeOut();
  1437. },
  1438. precision: function (a) {
  1439. var s = a + "",
  1440. d = s.indexOf('.') + 1;
  1441. return !d ? 0 : s.length - d;
  1442. },
  1443. // 1. numeric, 2. regex, 3. negation double, 4. indexof
  1444. indexOfGeneric: function (array, find) {
  1445. if (!array) return -1;
  1446. for (var i = 0, len = array.length; i < len; i++) {
  1447. // leave the loop on first none numeric item
  1448. if (!$.isNumeric(array[i]))
  1449. return ftui.indexOfRegex(array, find);
  1450. }
  1451. return ftui.indexOfNumeric(array, find);
  1452. },
  1453. indexOfNumeric: function (array, val) {
  1454. var ret = -1;
  1455. for (var i = 0, len = array.length; i < len; i++) {
  1456. if (Number(val) >= Number(array[i]))
  1457. ret = i;
  1458. }
  1459. return ret;
  1460. },
  1461. indexOfRegex: function (array, find) {
  1462. var len = array.length;
  1463. for (var i = 0; i < len; i++) {
  1464. try {
  1465. var match = find.match(new RegExp('^' + array[i] + '$'));
  1466. if (match)
  1467. return i;
  1468. } catch (e) {}
  1469. }
  1470. // negation double
  1471. if (len === 2 && array[0] === '!' + array[1] && find !== array[0]) {
  1472. return 0;
  1473. }
  1474. if (len === 2 && array[1] === '!' + array[0] && find !== array[1]) {
  1475. return 1;
  1476. }
  1477. // last chance: index of
  1478. return array.indexOf(find);
  1479. },
  1480. isValid: function (v) {
  1481. return (typeof v !== 'undefined' && v !== undefined && typeof v !== typeof notusedvar);
  1482. },
  1483. // global date format functions
  1484. dateFromString: function (str) {
  1485. var m = str.match(/(\d+)-(\d+)-(\d+)[_\s](\d+):(\d+):(\d+).*/);
  1486. var m2 = str.match(/^(\d+)$/);
  1487. var m3 = str.match(/(\d\d).(\d\d).(\d\d\d\d)/);
  1488. var offset = new Date().getTimezoneOffset();
  1489. return (m) ? new Date(+m[1], +m[2] - 1, +m[3], +m[4], +m[5], +m[6]) :
  1490. (m2) ? new Date(70, 1, 1, 0, 0, m2[1], 0) :
  1491. (m3) ? new Date(+m3[3], +m3[2] - 1, +m3[1], 0, -offset, 0, 0) : new Date();
  1492. },
  1493. diffMinutes: function (date1, date2) {
  1494. var diff = new Date(date2 - date1);
  1495. return (diff / 1000 / 60).toFixed(0);
  1496. },
  1497. diffSeconds: function (date1, date2) {
  1498. var diff = new Date(date2 - date1);
  1499. return (diff / 1000).toFixed(1);
  1500. },
  1501. durationFromSeconds: function (time) {
  1502. var hrs = Math.floor(time / 3600);
  1503. var mins = Math.floor((time % 3600) / 60);
  1504. var secs = time % 60;
  1505. var ret = "";
  1506. if (hrs > 0) {
  1507. ret += "" + hrs + ":" + (mins < 10 ? "0" : "");
  1508. }
  1509. ret += "" + mins + ":" + (secs < 10 ? "0" : "");
  1510. ret += "" + secs;
  1511. return ret;
  1512. },
  1513. mapColor: function (value) {
  1514. return ftui.getStyle('.' + value, 'color') || value;
  1515. },
  1516. parseJsonFromString: function (str) {
  1517. return JSON.parse(str);
  1518. },
  1519. getAndroidVersion: function (ua) {
  1520. ua = (ua || navigator.userAgent).toLowerCase();
  1521. var match = ua.match(/android\s([0-9\.]*)/);
  1522. return match ? match[1] : false;
  1523. },
  1524. getStyle: function (selector, prop) {
  1525. var props = ftui.config.styleCollection[selector];
  1526. var style = (props && props[prop]) ? props[prop] : null;
  1527. if (style === null) {
  1528. var reverseSelector = '.' + selector.split('.').reverse().join('.');
  1529. reverseSelector = reverseSelector.substring(0, reverseSelector.length - 1);
  1530. props = ftui.config.styleCollection[reverseSelector];
  1531. style = (props && props[prop]) ? props[prop] : null;
  1532. }
  1533. return style;
  1534. },
  1535. getClassColor: function (elem) {
  1536. for (var i = ftui.config.stdColors.length - 1; i >= 0; i -= 1) {
  1537. if (elem.hasClass(ftui.config.stdColors[i])) {
  1538. return ftui.getStyle('.' + ftui.config.stdColors[i], 'color');
  1539. }
  1540. }
  1541. return null;
  1542. },
  1543. getIconId: function (iconName) {
  1544. if (!iconName || iconName === '' || !$('link[href$="lib/font-awesome.min.css"]').length)
  1545. return "?";
  1546. var cssFile = $('link[href$="lib/font-awesome.min.css"]')[0];
  1547. if (cssFile && cssFile.sheet && cssFile.sheet.cssRules) {
  1548. var rules = cssFile.sheet.cssRules;
  1549. for (var rule in rules) {
  1550. if (rules[rule].selectorText && rules[rule].selectorText.match(new RegExp(iconName + ':'))) {
  1551. var id = rules[rule].style.content;
  1552. if (!id)
  1553. return iconName;
  1554. id = id.replace(/"/g, '').replace(/'/g, "");
  1555. return (/[^\u0000-\u00ff]/.test(id)) ? id :
  1556. String.fromCharCode(parseInt(id.replace('\\', ''), 16));
  1557. }
  1558. }
  1559. }
  1560. },
  1561. disableSelection: function () {
  1562. $("body").each(function () {
  1563. this.onselectstart = function () {
  1564. return false;
  1565. };
  1566. this.unselectable = "on";
  1567. $(this).css('-moz-user-select', 'none');
  1568. $(this).css('-webkit-user-select', 'none');
  1569. });
  1570. },
  1571. hideWidgets: function (area) {
  1572. $('[data-type]', area).addClass('widget-hide');
  1573. },
  1574. toast: function (text, error) {
  1575. //https://github.com/kamranahmedse/jquery-toast-plugin
  1576. if (ftui.config.TOAST !== 0) {
  1577. var tstack = ftui.config.TOAST;
  1578. if (ftui.config.TOAST == 1)
  1579. tstack = false;
  1580. if (error && error === 'error') {
  1581. if (f7) {
  1582. f7.ftui.addNotification({
  1583. title: 'FTUI',
  1584. message: text,
  1585. hold: 1500
  1586. });
  1587. } else if ($.toast) {
  1588. $.toast({
  1589. heading: 'Error',
  1590. text: text,
  1591. hideAfter: 20000, // in milli seconds
  1592. icon: 'error',
  1593. loader: false,
  1594. position: ftui.config.toastPosition,
  1595. stack: tstack
  1596. });
  1597. }
  1598. } else
  1599. if (f7) {
  1600. f7.ftui.addNotification({
  1601. title: 'FTUI',
  1602. message: text,
  1603. hold: 1500
  1604. });
  1605. } else if ($.toast) {
  1606. $.toast({
  1607. text: text,
  1608. loader: false,
  1609. position: ftui.config.toastPosition,
  1610. stack: tstack
  1611. });
  1612. }
  1613. }
  1614. },
  1615. log: function (level, text) {
  1616. if (ftui.config.debuglevel >= level)
  1617. console.log(text);
  1618. },
  1619. };
  1620. // global helper functions
  1621. String.prototype.toDate = function () {
  1622. return ftui.dateFromString(this);
  1623. };
  1624. String.prototype.parseJson = function () {
  1625. return ftui.parseJsonFromString(this);
  1626. };
  1627. String.prototype.toMinFromSec = function () {
  1628. var x = Number(this);
  1629. var ss = (Math.floor(x % 60)).toString();
  1630. var mm = (Math.floor(x /= 60)).toString();
  1631. return mm + ":" + (ss[1] ? ss : "0" + ss[0]);
  1632. };
  1633. String.prototype.toHoursFromSec = function () {
  1634. var x = Number(this);
  1635. var hh = (Math.floor(x / 3600)).toString();
  1636. var ss = (Math.floor(x % 60)).toString();
  1637. var mm = (Math.floor(x / 60) - (hh * 60)).toString();
  1638. return hh + ":" + (mm[1] ? mm : "0" + mm[0]) + ":" + (ss[1] ? ss : "0" + ss[0]);
  1639. };
  1640. Date.prototype.addMinutes = function (minutes) {
  1641. return new Date(this.getTime() + minutes * 60000);
  1642. };
  1643. Date.prototype.ago = function (format) {
  1644. var now = new Date();
  1645. var ms = (now - this);
  1646. var x = ms / 1000;
  1647. var seconds = Math.floor(x % 60);
  1648. x /= 60;
  1649. var minutes = Math.floor(x % 60);
  1650. x /= 60;
  1651. var hours = Math.floor(x % 24);
  1652. x /= 24;
  1653. var days = Math.floor(x);
  1654. var strUnits = (ftui.config.lang === 'de') ? ['Tag(e)', 'Stunde(n)', 'Minute(n)', 'Sekunde(n)'] : ['day(s)', 'hour(s)', 'minute(s)',
  1655. 'second(s)'];
  1656. var ret;
  1657. if (ftui.isValid(format)) {
  1658. ret = format.replace('dd', days);
  1659. ret = ret.replace('hh', (hours > 9) ? hours : '0' + hours);
  1660. ret = ret.replace('mm', (minutes > 9) ? minutes : '0' + minutes);
  1661. ret = ret.replace('ss', (seconds > 9) ? seconds : '0' + seconds);
  1662. ret = ret.replace('h', hours);
  1663. ret = ret.replace('m', minutes);
  1664. ret = ret.replace('s', seconds);
  1665. } else {
  1666. ret = (days > 0) ? days + " " + strUnits[0] + " " : "";
  1667. ret += (hours > 0) ? hours + " " + strUnits[1] + " " : "";
  1668. ret += (minutes > 0) ? minutes + " " + strUnits[2] + " " : "";
  1669. ret += seconds + " " + strUnits[3];
  1670. }
  1671. return ret;
  1672. };
  1673. Date.prototype.yyyymmdd = function () {
  1674. var yyyy = this.getFullYear().toString();
  1675. var mm = (this.getMonth() + 1).toString(); // getMonth() is zero-based
  1676. var dd = this.getDate().toString();
  1677. return yyyy + '-' + (mm[1] ? mm : "0" + mm[0]) + '-' + (dd[1] ? dd : "0" + dd[0]); // padding
  1678. };
  1679. Date.prototype.ddmmyyyy = function () {
  1680. var yyyy = this.getFullYear().toString();
  1681. var mm = (this.getMonth() + 1).toString(); // getMonth() is zero-based
  1682. var dd = this.getDate().toString();
  1683. return (dd[1] ? dd : "0" + dd[0]) + '.' + (mm[1] ? mm : "0" + mm[0]) + '.' + yyyy; // padding
  1684. };
  1685. Date.prototype.hhmm = function () {
  1686. var hh = this.getHours().toString();
  1687. var mm = this.getMinutes().toString();
  1688. return (hh[1] ? hh : "0" + hh[0]) + ':' + (mm[1] ? mm : "0" + mm[0]); // padding
  1689. };
  1690. Date.prototype.hhmmss = function () {
  1691. var hh = this.getHours().toString();
  1692. var mm = this.getMinutes().toString();
  1693. var ss = this.getSeconds().toString();
  1694. return (hh[1] ? hh : "0" + hh[0]) + ':' + (mm[1] ? mm : "0" + mm[0]) + ':' + (ss[1] ? ss : "0" + ss[0]); // padding
  1695. };
  1696. Date.prototype.ddmm = function () {
  1697. var mm = (this.getMonth() + 1).toString(); // getMonth() is zero-based
  1698. var dd = this.getDate().toString();
  1699. return (dd[1] ? dd : "0" + dd[0]) + '.' + (mm[1] ? mm : "0" + mm[0]) + '.'; // padding
  1700. };
  1701. Date.prototype.ddmmhhmm = function () {
  1702. var MM = (this.getMonth() + 1).toString(); // getMonth() is zero-based
  1703. var dd = this.getDate().toString();
  1704. var hh = this.getHours().toString();
  1705. var mm = this.getMinutes().toString();
  1706. return (dd[1] ? dd : "0" + dd[0]) + '.' + (MM[1] ? MM : "0" + MM[0]) + '. ' +
  1707. (hh[1] ? hh : "0" + hh[0]) + ':' + (mm[1] ? mm : "0" + mm[0]);
  1708. };
  1709. Date.prototype.eeee = function () {
  1710. var weekday_de = ['Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag'];
  1711. var weekday = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
  1712. if (ftui.config.lang === 'de')
  1713. return weekday_de[this.getDay()];
  1714. return weekday[this.getDay()];
  1715. };
  1716. Date.prototype.eee = function () {
  1717. var weekday_de = ['Son', 'Mon', 'Die', 'Mit', 'Don', 'Fre', 'Sam'];
  1718. var weekday = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
  1719. if (ftui.config.lang === 'de')
  1720. return weekday_de[this.getDay()];
  1721. return weekday[this.getDay()];
  1722. };
  1723. Date.prototype.ee = function () {
  1724. var weekday_de = ['So', 'Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa'];
  1725. var weekday = ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'];
  1726. if (ftui.config.lang === 'de')
  1727. return weekday_de[this.getDay()];
  1728. return weekday[this.getDay()];
  1729. };
  1730. function onjQueryLoaded() {
  1731. /* EVENTS */
  1732. // event "page is loaded" -> start FTUI
  1733. ftui.init();
  1734. $('.menu').on('click', function () {
  1735. $('.menu').toggleClass('show');
  1736. });
  1737. $(window).on('beforeunload', function () {
  1738. ftui.log(5, 'beforeunload');
  1739. ftui.setOffline();
  1740. });
  1741. $(window).on('online offline', function () {
  1742. ftui.log(5, 'online offline');
  1743. if (navigator.onLine)
  1744. ftui.setOnline();
  1745. else
  1746. ftui.setOffline();
  1747. });
  1748. window.onerror = function (msg, url, lineNo, columnNo, error) {
  1749. var file = url.split('/').pop();
  1750. ftui.toast([file + ':' + lineNo, error].join('<br/>'), 'error');
  1751. return false;
  1752. };
  1753. $.fn.once = function (a, b) {
  1754. return this.each(function () {
  1755. $(this).off(a).on(a, b);
  1756. });
  1757. };
  1758. //for widget
  1759. $.fn.widgetId = function () {
  1760. return ['ftui', $(this).data('type'), $(this).data('device').replace(' ', 'default'), $(this).data('get'), $(this).index()].join('_');
  1761. };
  1762. $.fn.uuid = function () {
  1763. if (!$(this).isValidData('uuid')) {
  1764. var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  1765. var r = Math.random() * 16 | 0,
  1766. v = c == 'x' ? r : (r & 0x3 | 0x8);
  1767. return v.toString(16);
  1768. });
  1769. $(this).attr('data-uuid', uuid);
  1770. }
  1771. return $(this).data('uuid');
  1772. };
  1773. $.fn.filterData = function (key, value) {
  1774. return this.filter(function () {
  1775. return $(this).data(key) == value;
  1776. });
  1777. };
  1778. $.fn.filterDeviceReading = function (key, device, param) {
  1779. return this.filter(function () {
  1780. var elem = $(this);
  1781. var value = elem.data(key);
  1782. return (String(value) === param && String(elem.data('device')) === device) ||
  1783. (value === device + ':' + param || value === '[' + device + ':' + param + ']') ||
  1784. ($.inArray(param, value) > -1 && String(elem.data('device')) === device) ||
  1785. ($.inArray(device + ':' + param, value) > -1);
  1786. });
  1787. };
  1788. $.fn.isValidData = function (key) {
  1789. return typeof $(this).data(key) != 'undefined';
  1790. };
  1791. $.fn.initData = function (key, value) {
  1792. var elem = $(this);
  1793. elem.data(key, elem.isValidData(key) ? elem.data(key) : value);
  1794. return elem;
  1795. };
  1796. $.fn.mappedColor = function (key) {
  1797. return ftui.getStyle('.' + $(this).data(key), 'color') || $(this).data(key);
  1798. };
  1799. $.fn.matchingState = function (key, value) {
  1800. if (!ftui.isValid(value)) {
  1801. return '';
  1802. }
  1803. var elm = $(this);
  1804. var state = String(ftui.getPart(value, elm.data(key + '-part')));
  1805. var onData = elm.data(key + '-on');
  1806. var offData = elm.data(key + '-off');
  1807. var on = String(onData);
  1808. var temp, device, reading, param;
  1809. if (on.match(/:/)) {
  1810. temp = on.split(':');
  1811. device = temp[0].replace('[', '');
  1812. reading = temp[1].replace(']', '');
  1813. param = ftui.getDeviceParameter(device, reading);
  1814. if (param && ftui.isValid(param)) {
  1815. on = param.val;
  1816. }
  1817. }
  1818. var off = String(offData);
  1819. if (off.match(/:/)) {
  1820. temp = off.split(':');
  1821. device = temp[0].replace('[', '');
  1822. reading = temp[1].replace(']', '');
  1823. param = ftui.getDeviceParameter(device, reading);
  1824. if (param && ftui.isValid(param)) {
  1825. off = param.val;
  1826. }
  1827. }
  1828. if (ftui.isValid(onData)) {
  1829. if (state === on) {
  1830. return 'on';
  1831. } else if (state.match(new RegExp('^' + on + '$'))) {
  1832. return 'on';
  1833. }
  1834. }
  1835. if (ftui.isValid(offData)) {
  1836. if (state === off) {
  1837. return 'off';
  1838. } else if (state.match(new RegExp('^' + off + '$'))) {
  1839. return 'off';
  1840. }
  1841. }
  1842. if (ftui.isValid(onData) && ftui.isValid(offData)) {
  1843. if (on === '!off' && !state.match(new RegExp('^' + off + '$'))) {
  1844. return 'on';
  1845. } else if (off === '!on' && !state.match(new RegExp('^' + on + '$'))) {
  1846. return 'off';
  1847. } else if (on === '!' + off && !state.match(new RegExp('^' + off + '$'))) {
  1848. return 'on';
  1849. } else if (off === '!' + on && !state.match(new RegExp('^' + on + '$'))) {
  1850. return 'off';
  1851. }
  1852. }
  1853. };
  1854. $.fn.isDeviceReading = function (key) {
  1855. var reading = $(this).data(key);
  1856. return reading && !$.isNumeric(reading) && typeof reading === 'string' && reading.match(/:/);
  1857. };
  1858. $.fn.isExternData = function (key) {
  1859. var data = $(this).data(key);
  1860. if (!data) return '';
  1861. return (data.match(/^[#\.\[][^:]*$/));
  1862. };
  1863. $.fn.cleanWhitespace = function () {
  1864. var textNodes = this.contents().filter(
  1865. function () {
  1866. return (this.nodeType == 3 && !/\S/.test(this.nodeValue));
  1867. })
  1868. .remove();
  1869. return this;
  1870. };
  1871. $.fn.getReading = function (key, idx) {
  1872. var devname = String($(this).data('device')),
  1873. paraname = $(this).data(key);
  1874. if ($.isArray(paraname)) {
  1875. paraname = paraname[idx];
  1876. }
  1877. paraname = String(paraname);
  1878. if (paraname && paraname.match(/:/)) {
  1879. var temp = paraname.split(':');
  1880. devname = temp[0].replace('[', '');
  1881. paraname = temp[1].replace(']', '');
  1882. }
  1883. if (devname && devname.length > 0) {
  1884. var params = ftui.deviceStates[devname];
  1885. return (params && params[paraname]) ? params[paraname] : {};
  1886. }
  1887. return {};
  1888. };
  1889. $.fn.valOfData = function (key) {
  1890. var data = $(this).data(key);
  1891. if (!ftui.isValid(data)) return '';
  1892. return (data.toString().match(/^[#\.\[][^:]*$/)) ? $(data).data('value') : data;
  1893. };
  1894. $.fn.transmitCommand = function () {
  1895. if ($(this).hasClass('notransmit')) return;
  1896. var cmdl = [$(this).valOfData('cmd'), $(this).valOfData('device') + $(this).valOfData('filter'), $(this).valOfData('set'), $(
  1897. this).valOfData('value')].join(' ');
  1898. ftui.setFhemStatus(cmdl);
  1899. ftui.toast(cmdl);
  1900. };
  1901. }
  1902. // detect self location
  1903. var src = document.querySelector('script[src*="fhem-tablet-ui"]').getAttribute('src');
  1904. var file = src.split('/').pop();
  1905. src = src.replace('/' + file, '');
  1906. var dir = src.split('/').pop();
  1907. ftui.config.basedir = src.replace(dir, '');
  1908. if (ftui.config.basedir === '') ftui.config.basedir = './';
  1909. console.log('Base dir: ' + ftui.config.basedir);
  1910. // load jQuery lib
  1911. if (!ftui.isValid(window.jQuery)) {
  1912. var script = document.createElement('script');
  1913. script.type = 'text/javascript';
  1914. script.onload = function () {
  1915. (function ($) {
  1916. $(document).ready(function () {
  1917. console.log('jQuery dynamically loaded');
  1918. onjQueryLoaded();
  1919. });
  1920. })(jQuery);
  1921. };
  1922. script.src = ftui.config.basedir + "lib/jquery.min.js";
  1923. document.getElementsByTagName('head')[0].appendChild(script);
  1924. } else {
  1925. $(document).ready(function () {
  1926. onjQueryLoaded();
  1927. });
  1928. }