fhem-tablet-ui.js 87 KB

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