";
// favoriteTemplate += "
";
favoriteTemplate += "
";
favoriteTemplate += "
";
favoriteTemplate += "";
favoriteTemplate += "{0}";
favoriteTemplate += " ";
favoriteTemplate += "
";
favoriteTemplate += "{1}";
favoriteTemplate += "
";
favoriteTemplate += "
";
var html = "";
// $(".altui-favorites").toggle(false);
MultiBox.getDevices(null , function(device) { return device.favorite; }, function(devices) {
html += "
";
html += "
";
$.each(devices, function(idx,device) {
html +=favoriteTemplate.format(device.name,_drawFavoriteDevice(device));
})
MultiBox.getScenes(null, function(scene) { return scene.favorite; }, function (scenes) {
$.each(scenes, function(idx,scene) {
html +=favoriteTemplate.format(scene.name,_drawFavoriteScene(scene));
})
// html += "
";
// html += "
";
// html += "
";
// html +="
"+_T("This plugin is a work in progress, it will continuously evolve over time.");
// html += _T("You may check out the evolutions on the Micasaverde Forum ")+"
";
// html += "
";
$(".altui-favorites").replaceWith(html);
// $(".altui-favorites").toggle(true);
_resizeFavorites();
})
});
};
function _refreshUI( bFull, bFirstTime ) {
// refresh rooms
// refresh devices
// AltuiDebug.debug("_refreshUI( {0}, {1} )".format(bFull,bFirstTime));
// $(".altui-device") which do not have a btngroup in open state
// to avoid a refresh to erase an opened popup menu
$(".altui-device:not(.altui-norefresh)").not(":has(div.btn-group.open)").each( function( index, element) {
// $(".altui-device:not(:has(div.btn-group.open))").not(".altui-norefresh").each( function( index, element) {
var devid = $(this).data("altuiid");
var device = MultiBox.getDeviceByAltuiID( devid );
if ( (device!=null) && (bFull==true || device.dirty==true) ) {
// get HTML for device and draw it
var Html = _deviceDraw(device);
$(this).replaceWith( Html );
// draw job information.
if (device.Jobs != undefined) {
$.each( device.Jobs, function( idx, job ) {
PageMessage.jobMessage( device,job );
});
}
else
{
PageMessage.clearJobMessage( device );
}
}
});
// refresh scenes
$(".altui-scene").not(".altui-norefresh").each( function(index,element) {
var altuiid = $(element).data("altuiid");
var scene = MultiBox.getSceneByAltuiID( altuiid );
// get HTML for scene and draw it
if (scene) {
var html = _sceneDraw( scene);
$(element).replaceWith( html );
}
else {
$(element).parent().remove();
}
});
// refresh custom pages
if ($(".altui-page-contents").not(".altui-norefresh").length>0)
{
var pagename = _getActivePageName();
var page = PageManager.getPageFromName( pagename );
// for all widget present which need refresh
var selector = "#altui-page-content-{0} .altui-widget".format(pagename.replace(' ','_'));
$(selector).each( function (idx,elem) {
var widgetid = $(elem).prop('id');
var widget = PageManager.getWidgetByID( page, widgetid );
var tool = _getToolByClass( widget.cls );
if (tool.no_refresh !=true) {
var html = _getWidgetHtml( widget, false ); // not edit mode
$(elem).replaceWith( html );
}
});
_updateDynamicDisplayTools( false );
}
// refresh favorites
_redrawFavorites();
};
var ALTUI_hometimer=null;
function _stoprefreshModes() {
// console.log("stop refresh");
if (ALTUI_hometimer!=null)
clearTimeout(ALTUI_hometimer);
};
function _refreshModes() {
// console.log("refresh");
_stoprefreshModes();
if (UIManager.UI7Check()==true) {
MultiBox.getHouseMode( function (mode) {
// console.log("mode="+mode);
if (mode) {
$("div.housemode").removeClass("preset_selected").addClass("preset_unselected");
$("#altui-mode"+mode).removeClass("preset_unselected").addClass("preset_selected");
}
ALTUI_hometimer=setTimeout( _refreshModes, 10000 );
});
};
};
function _initOptions(serveroptions) {
if (isNullOrEmpty(serveroptions))
serveroptions="{}";
var defaults = JSON.parse(serveroptions);
// option1=val1,option2=val2,...
// serveroptions = atob(serveroptions);
// var tbl = serveroptions.split(',');
// var defaults={};
// $.each(tbl, function(idx,elem) {
// var key_vals=elem.split('=');
// defaults[ key_vals[0] ] = key_vals[1];
// });
$.each(_checkOptions, function(idx,opt) {
if (MyLocalStorage.getSettings(opt.id) == null)
if (defaults[opt.id] != undefined )
MyLocalStorage.setSettings(opt.id, atob(defaults[opt.id]) );
else
MyLocalStorage.setSettings(opt.id, opt._default);
});
};
function _initBlockly() {
var language = getQueryStringValue("lang") || window.navigator.userLanguage || window.navigator.language;
language = language.substring(0, 2);
var len = $('script[src="J_ALTUI_b_lua_compressed.js"]').length;
if (len==0) {
_loadScript("J_ALTUI_b_blockly_compressed.js",function() {
_loadScript("J_ALTUI_b_blocks_compressed.js",function() {
_loadScript("J_ALTUI_b_"+language+".js",function() {
_loadScript("J_ALTUI_b_javascript_compressed.js",function() {
_loadScript("J_ALTUI_b_lua_compressed.js",function() {
});
});
});
});
});
}
};
function _initMultiSelect() {
$("title").before("".format(bootstrap_multiselect_css));
};
function _initUIEngine(css) {
$("title").before("".format(css));
};
function _setTheme(themecss) {
if (isNullOrEmpty(themecss)) {
themecss = g_OrgTheme;
$("link[href='"+g_CustomTheme+"']").attr('href',themecss);
g_CustomTheme = themecss;
MyLocalStorage.setSettings("Theme",null);
} else {
var link = $("link[href='{0}']".format(g_CustomTheme));
if (link.length>0) {
$(link).attr('href',themecss);
} else {
// if (themecss && (themecss.trim()!="") )
$("title").after("
");
}
g_CustomTheme = themecss;
MyLocalStorage.setSettings("Theme",themecss);
}
};
function _initEngine(styles, devicetypes, themecss, serveroptions, cbfunc) {
_initOptions(serveroptions);
_initUIEngine(styles);
_initDB(devicetypes,cbfunc);
_setTheme(themecss);
_initMultiSelect();
_initBlockly();
};
function _initCustomPages( custompages ) {
PageManager.init(custompages);
};
function _clearScripts() {
};
//------------------------------------------------------------
// CUSTOM PAGE MENU
//------------------------------------------------------------
var startpos = null;
var _widgetOnCanvasResizableOptions = function(tool) {
return {
aspectRatio: tool.aspectRatio ||false, // no aspect ratio by default
grid: [ 5,5 ],
containment: "parent",
stop: function( event, ui ) {
var pagename = _getActivePageName();
var page = PageManager.getPageFromName( pagename );
var widgetid = $(ui.helper).prop('id');
(tool.onWidgetResize)(page,widgetid,ui.position,ui.size);
PageManager.updateChildrenInPage( page, widgetid, ui.position, ui.size );
_showSavePageNeeded(true);
}
}
};
// one page if specified, all pages otherwise
var _widgetOnCanvasDraggableOptions = function(page) {
return {
grid: [ 5,5 ],
cancel: false, // prevent draggable to be cancelled on disabled buttons
// helper: "clone",
revert: "invalid",
// snap: true,
// snapMode: "inner",
// snapTolerance: 20,
start: function(event, ui) {
startpos = ui.position;
$(this).toggleClass("ui-selected");
},
drag: function(event, ui) {
// take all selected elements except me and fix their position to make them move.
var canvas = $( _getPageSelector( page ) );
var selected = canvas.find(".altui-widget.ui-selected").not("#"+ui.helper.prop('id'));
selected.each( function(index,elem) {
var elempos = $(elem).position();
$(elem).css ({
top: elempos.top + (ui.position.top-startpos.top),
left: elempos.left + (ui.position.left-startpos.left)
})
});
startpos = ui.position;
// console.log( "selected:"+selected.length+", "+JSON.stringify(startpos) + ":" + JSON.stringify(ui.position) );
},
stop: function(event, ui) {
var canvas = $( _getPageSelector( page ) );
startpos = null;
var selected = canvas.find(".altui-widget.ui-selected").not("#"+ui.helper.prop('id'));
var maxwidth = canvas.width();
var maxheight = canvas.height();
selected.each( function(index,elem) {
var elempos = $(elem).position();
if (elempos.top <= 0)
$(elem).css ('top',0);
if (elempos.top + $(elem).height() >= maxheight)
$(elem).css ('top',maxheight - $(elem).height() );
if (elempos.left <= 0)
$(elem).css ('left',0);
if (elempos.left+$(elem).width() >= maxwidth)
$(elem).css ('left',maxwidth - $(elem).width() );
});
}
};
};
// ------------------------------------------
// Property dialog box for toolbox widgets
// ------------------------------------------
function _replaceElementKeepAttributes( selector, html ) {
var oldobject = $(selector);
var cls = oldobject.attr('class');
var style = oldobject.attr('style');
var newobject = $(html).attr('class',cls).attr('style',style);
oldobject.replaceWith(newobject);
return $(selector);
};
function _replaceWidget(widget) {
var tool = _getToolByClass( widget.cls );
var html = _getWidgetHtml(widget,true);
var page = PageManager.getPageFromName( _getActivePageName() );
var selector = _getWidgetSelector(page,widget);
$(selector).draggable("disable");
_replaceElementKeepAttributes( selector, html );
$(selector).draggable(_widgetOnCanvasDraggableOptions(page));
if ($.isFunction( tool.onWidgetResize) ) {
$(selector).resizable( _widgetOnCanvasResizableOptions(tool) );
}
};
function _showSavePageNeeded(bNeeded) {
$("#altui-page-action-save")
.toggleClass("btn-info",bNeeded)
.closest("li.dropdown").find("a.dropdown-toggle")
.toggleClass("btn-info",bNeeded);
};
function _onPropertyImage(real_widget) {
// clone for temporary storage
var widget = $.extend( true, {}, real_widget );
var pagename = _getActivePageName();
var page = PageManager.getPageFromName( pagename );
var properties = widget.properties;
var propertyline = "";
propertyline += "
";
propertyline += " Image Source ";
propertyline += " ";
propertyline += "
";
var dialog = DialogManager.registerDialog('dialogModal',
defaultDialogModalTemplate.format(
'Image Properties', // title
"
", // body
"modal-lg" // body
));
DialogManager.dlgAddDialogButton($('div#dialogModal'), true, _T("Save Changes"));
// buttons
$('div#dialogModal form').off('submit');
$('div#dialogModal form').on( 'submit', function() {
real_widget.properties.url = $('#altui-widget-imgsource').val();
$('div#dialogModal').modal('hide');
_showSavePageNeeded(true);
$( _getWidgetSelector(page,real_widget) ).find("img").attr("src",real_widget.properties.url);
});
$('div#dialogModal').modal();
};
function _onPropertyVariable(real_widget) {
// clone for temporary storage
var widget = $.extend( true, {}, real_widget );
var dialog = DialogManager.createPropertyDialog(_T('Device Variable Properties'));
DialogManager.dlgAddDevices( dialog , widget.properties.deviceid, function() {
DialogManager.dlgAddVariables(dialog, widget, function() {
DialogManager.dlgAddColorPicker(dialog, "Color", _T("Color"), "", widget.properties.color);
// run the show
$('div#dialogModal').modal();
});
});
// buttons
$('div#dialogs')
.off('submit',"div#dialogModal form")
.on( 'submit',"div#dialogModal form", function() {
// save for real this time
real_widget.properties.deviceid = widget.properties.deviceid;
real_widget.properties.color = $('#altui-widget-Color').val();
var selected = MultiBox.getStateByID( real_widget.properties.deviceid,$("#altui-select-variable").val() );
real_widget.properties.service = selected.service;
real_widget.properties.variable = selected.variable;
$('div#dialogModal').modal('hide');
_showSavePageNeeded(true);
_replaceWidget(real_widget);
});
};
function _onPropertyLabel(widget) {
var dialog = DialogManager.createPropertyDialog('Label Properties');
DialogManager.dlgAddLine(dialog, "Label", _T("Button Label"), widget.properties.label, "");
DialogManager.dlgAddColorPicker(dialog, "Color", _T("Color"), "", widget.properties.color);
// buttons
$('div#dialogs')
.off('submit',"div#dialogModal form")
.on( 'submit',"div#dialogModal form", function() {
widget.properties.label = $('#altui-widget-Label').val();
widget.properties.color = $('#altui-widget-Color').val();
$('div#dialogModal button.btn-primary').off('click');
$('div#dialogModal').modal('hide');
_showSavePageNeeded(true);
_replaceWidget(widget);
});
$('div#dialogModal').modal();
};
function _onPropertyRunscene(real_widget)
{
// clone for temporary storage
var widget = $.extend( true, {}, real_widget );
var dialog = DialogManager.createPropertyDialog('Run Scene Properties');
DialogManager.dlgAddScenes( dialog , widget, function() {
DialogManager.dlgAddLine(dialog, "Label", _T("Button Label"), widget.properties.label, "");
// run the show
$('div#dialogModal').modal();
});
// buttons
$('div#dialogs')
.off('submit',"div#dialogModal form")
.on( 'submit',"div#dialogModal form", function() {
$('div#dialogModal button.btn-primary').off('click');
real_widget.properties.sceneid = $('#altui-widget-sceneid').val();
real_widget.properties.label = $("#altui-widget-Label").val();
$('div#dialogModal').modal('hide');
_showSavePageNeeded(true);
_replaceWidget(real_widget);
});
};
function _onPropertyUpnpAction(real_widget)
{
// clone for temporary storage
var widget = $.extend( true, {}, real_widget );
var dialog = DialogManager.createPropertyDialog('UPnP Action Properties');
DialogManager.dlgAddDevices( dialog , widget.properties.deviceid, function() {
DialogManager.dlgAddActions("altui-widget-action",dialog, widget, widget.properties, _T('Action'), function() {
DialogManager.dlgAddLine(dialog, "Label", _T("Button Label"), widget.properties.label, "");
// run the show
$('div#dialogModal').modal();
});
});
// dialog Save Button
$('div#dialogs')
.off('submit',"div#dialogModal form")
.on( 'submit',"div#dialogModal form", function() {
// save for real this time
real_widget.properties.deviceid = widget.properties.deviceid;
real_widget.properties.service = widget.properties.service;
real_widget.properties.action = widget.properties.action;
real_widget.properties.label = $("#altui-widget-Label").val();
// read params
real_widget.properties.params={};
$("div.altui-widget-action-parameters input").each( function(idx,elem)
{
var value = $(elem).val();
var name = $(elem).prop('id').substring( "altui-widget-action-parameters-".length );
real_widget.properties.params[name]=value;
});
$('div#dialogModal').modal('hide');
_showSavePageNeeded(true);
_replaceWidget(real_widget);
});
};
function _onPropertyOnOffButton(real_widget)
{
// clone for temporary storage
var widget = $.extend( true, {}, real_widget );
var dialog = DialogManager.createPropertyDialog('OnOff Button Properties');
DialogManager.dlgAddDevices( dialog , widget.properties.deviceid, function() {
DialogManager.dlgAddVariables(dialog, widget, function() {
DialogManager.dlgAddLine(dialog,'ValueON', _T('Value ON'),widget.properties.onvalue,"",{placeholder:"Leave empty for 1 or true"},"col-xs-6");
DialogManager.dlgAddLine(dialog,'ValueOFF', _T('Value OFF'),widget.properties.offvalue,"",{placeholder:"Leave empty for 0 or false or null"},"col-xs-6");
DialogManager.dlgAddLine(dialog,'OnLabel', _T('OnLabel'), widget.properties.labels[1],"",null,"col-xs-6");
DialogManager.dlgAddLine(dialog,'OffLabel', _T('OffLabel'),widget.properties.labels[0],"",null,"col-xs-6");
DialogManager.dlgAddCheck(dialog,'Inverted',widget.properties.inverted);
DialogManager.dlgAddActions("altui-widget-action-off",dialog, widget, widget.properties.action_off, _T('Action to switch OFF'), function() {
DialogManager.dlgAddActions("altui-widget-action-on",dialog, widget, widget.properties.action_on, _T('Action to switch ON'), function() {
// run the show
$('div#dialogModal').modal();
});
});
});
});
// dialog Save Button
$('div#dialogs')
.off('submit',"div#dialogModal form")
.on( 'submit',"div#dialogModal form", function() {
// save for real this time
if (widget.properties.deviceid==0)
return; // mandatory data
real_widget.properties.deviceid = widget.properties.deviceid;
real_widget.properties.inverted = $("#altui-widget-Inverted").is(':checked');
var selected = MultiBox.getStateByID( real_widget.properties.deviceid,$("#altui-select-variable").val() );
real_widget.properties.variable = selected.variable;
real_widget.properties.service = selected.service;
real_widget.properties.onvalue = trim($("#altui-widget-ValueON").val().toString());
real_widget.properties.offvalue = trim($("#altui-widget-ValueOFF").val().toString());
real_widget.properties.action_off = DialogManager.getDialogActionValue("altui-widget-action-off");
real_widget.properties.labels[0] = $("#altui-widget-OffLabel").val();
real_widget.properties.action_on = DialogManager.getDialogActionValue("altui-widget-action-on");
real_widget.properties.labels[1] = $("#altui-widget-OnLabel").val();
// read params
real_widget.properties.action_on.params={};
$("div.altui-widget-action-on-parameters input").each( function(idx,elem)
{
var value = $(elem).val();
var name = $(elem).prop('id').substring( "altui-widget-action-on-parameters-".length );
real_widget.properties.action_on.params[name]=value;
});
// read params
real_widget.properties.action_off.params={};
$("div.altui-widget-action-off-parameters input").each( function(idx,elem)
{
var value = $(elem).val();
var name = $(elem).prop('id').substring( "altui-widget-action-off-parameters-".length );
real_widget.properties.action_off.params[name]=value;
});
$('div#dialogModal').modal('hide');
_showSavePageNeeded(true);
_replaceWidget(real_widget);
});
};
function _onPropertyFrame(real_widget)
{
// clone for temporary storage
var widget = $.extend( true, {}, real_widget );
var tool = _getToolByClass( widget.cls );
var dialog = DialogManager.createPropertyDialog(_T('Frame Properties'));
DialogManager.dlgAddLine(dialog, "Label", _T("Frame Label"), widget.properties.label, "");
DialogManager.dlgAddLine(dialog, "CSS", _T("background CSS"), widget.properties.css, "");
DialogManager.dlgAddUrl(dialog, "Url", _T("IFrame Url"), widget.properties.url, _T("Optional, if specified frame will be filled in with this url"), {});
$('div#dialogModal').modal();
// buttons
$('div#dialogs')
.off('submit',"div#dialogModal form")
.on( 'submit',"div#dialogModal form", function() {
real_widget.properties.label = $("#altui-widget-Label").val();
real_widget.properties.css = $("#altui-widget-CSS").val();
real_widget.properties.url = $("#altui-widget-Url").val();
$('div#dialogModal').modal('hide');
_showSavePageNeeded(true);
_replaceWidget(real_widget);
});
};
function _onPropertyIcon(real_widget)
{
// clone for temporary storage
var widget = $.extend( true, {}, real_widget );
var dialog = DialogManager.createPropertyDialog('Device Icon Properties');
DialogManager.dlgAddDevices( dialog , widget.properties.deviceid, function() {
// run the show
$('div#dialogModal').modal();
});
// buttons
$('div#dialogs')
.off('submit',"div#dialogModal form")
.on( 'submit',"div#dialogModal form", function() {
// save for real this time
real_widget.properties.deviceid = $("#altui-select-device").val();
$('div#dialogModal button.btn-primary').off('click');
$('div#dialogModal').modal('hide');
_showSavePageNeeded(true);
_replaceWidget(real_widget);
});
};
function _onResizeStub(page, widgetid, position, size)
{
};
function _onResizeCamera(page, widgetid, position, size)
{
var widget = PageManager.getWidgetByID( page, widgetid );
var tool = _getToolByClass( widget.cls );
widget.size = size;
_replaceWidget(widget);
};
function _onResizeGauge(page, widgetid, position, size)
{
var widget = PageManager.getWidgetByID( page, widgetid );
var tool = _getToolByClass( widget.cls );
widget.size = size;
_onDisplayGauge(page,widgetid,true);
};
function _onPropertyCamera(real_widget)
{
// clone for temporary storage
var widget = $.extend( true, {}, real_widget );
var dialog = DialogManager.createPropertyDialog('Camera Properties');
DialogManager.dlgAddDevices( dialog , widget.properties.deviceid,
function() {
// run the show
$('div#dialogModal').modal();
},
function(device) { // filter function
return (device.device_type=="urn:schemas-upnp-org:device:DigitalSecurityCamera:2");
}
);
// buttons
$('div#dialogs')
.off('submit',"div#dialogModal form")
.on( 'submit',"div#dialogModal form", function() {
// save for real this time
real_widget.properties.deviceid = $("#altui-select-device").val();
real_widget.size = $.extend({ width:Math.floor(300*640/480), height:300},widget.size);
$('div#dialogModal button.btn-primary').off('click');
$('div#dialogModal').modal('hide');
_showSavePageNeeded(true);
var tool = _getToolByClass( real_widget.cls );
_replaceWidget(real_widget);
});
};
function _onPropertyGauge(real_widget) {
// clone for temporary storage
var widget = $.extend( true, {}, real_widget );
var dialog = DialogManager.createPropertyDialog('Gauge Properties');
DialogManager.dlgAddDevices( dialog , widget.properties.deviceid, function() {
DialogManager.dlgAddVariables(dialog, widget, function() {
DialogManager.dlgAddLine(dialog,'Label', _T('Label'), widget.properties.label);
DialogManager.dlgAddLine(dialog,'Min', _T('Min'), widget.properties.min);
DialogManager.dlgAddLine(dialog,'Green', _T('Green'), widget.properties.greenfrom);
DialogManager.dlgAddLine(dialog,'Orange', _T('Orange'), widget.properties.orangefrom);
DialogManager.dlgAddLine(dialog,'Red', _T('Red'), widget.properties.redfrom);
DialogManager.dlgAddLine(dialog,'Max', _T('Max'), widget.properties.max);
DialogManager.dlgAddLine(dialog,'Ticks', _T('Ticks'), widget.properties.majorTicks.join(','),'nn,nn,nn');
// run the show
$('div#dialogModal').modal();
});
});
// buttons
$('div#dialogs')
.off('submit',"div#dialogModal form")
.on( 'submit',"div#dialogModal form", function() {
// save for real this time
if (widget.properties.deviceid==0)
return; // mandatory data
real_widget.properties.deviceid = widget.properties.deviceid;
real_widget.size = $.extend({ width:120, height:120},widget.size);
var states = MultiBox.getStatesByAltuiID( widget.properties.deviceid );
var variable = $("#altui-select-variable").val();
if (variable!=null) {
var selected = MultiBox.getStateByID( real_widget.properties.deviceid,variable );
real_widget.properties.variable = selected.variable;
real_widget.properties.service = selected.service;
real_widget.properties.label = $("#altui-widget-Label").val();
real_widget.properties.min = $("#altui-widget-Min").val();
real_widget.properties.max = $("#altui-widget-Max").val();
real_widget.properties.greenfrom = $("#altui-widget-Green").val();
real_widget.properties.orangefrom = $("#altui-widget-Orange").val();
real_widget.properties.redfrom = $("#altui-widget-Red").val();
var ticks = $("#altui-widget-Ticks").val();
real_widget.properties.majorTicks = ticks.split(',');
_showSavePageNeeded(true);
// refresh widget
var pagename = _getActivePageName();
var page = PageManager.getPageFromName( pagename );
_onDisplayGauge(page,real_widget.id,true);
}
$('div#dialogModal').modal('hide');
});
}
function _onDisplayGauge(page,widgetid,bEdit)
{
var widget=PageManager.getWidgetByID( page, widgetid );
var device = MultiBox.getDeviceByAltuiID(widget.properties.deviceid);
if (device==null)
return "";
var value = parseFloat( MultiBox.getStatus(device, widget.properties.service, widget.properties.variable) || 0 );
var data = google.visualization.arrayToDataTable([
['Label', 'Value'],
[widget.properties.label || '', value],
]);
if (value > widget.properties.max)
widget.properties.max = value;
if (value < widget.properties.min)
widget.properties.min = value;
widget.size = $.extend({ width:120, height:120},widget.size);
var options = {
width: widget.size.width,
height: widget.size.height,
minorTicks: 5,
min: widget.properties.min,
max: widget.properties.max
};
if (widget.properties.majorTicks.length>0)
options = $.extend(options, {
majorTicks: widget.properties.majorTicks
});
if ($.isNumeric(widget.properties.greenfrom))
options = $.extend(options, {
greenFrom: widget.properties.greenfrom,
greenTo: $.isNumeric(widget.properties.orangefrom) ? widget.properties.orangefrom : widget.properties.max
});
if ($.isNumeric(widget.properties.orangefrom))
options = $.extend(options, {
yellowFrom: widget.properties.orangefrom,
yellowTo: $.isNumeric(widget.properties.redfrom) ? widget.properties.redfrom : widget.properties.max
});
if ($.isNumeric(widget.properties.redfrom))
options = $.extend(options, {
redFrom: widget.properties.redfrom,
redTo: widget.properties.max
});
var chart = new google.visualization.Gauge(document.getElementById("altui-gauge-"+widgetid));
chart.draw(data, options);
};
// ------------------------------------------
// Edit Tools
// ------------------------------------------
function onAlignTop(selected)
{
var min = Math.min.apply(null, $.map( $(selected) , function(elem) {return $(elem).position().top;}) );
$(selected).each( function(idx,elem) {
$(elem).css('top',min);
});
_showSavePageNeeded(true);
};
function onAlignHorizontal(selected)
{
var max = Math.max.apply(null, $.map( $(selected) , function(elem) {return $(elem).position().top+$(elem).height()/2;}) );
$(selected).each( function(idx,elem) {
$(elem).css('top',max-$(elem).height()/2);
});
_showSavePageNeeded(true);
};
function onAlignBottom(selected)
{
var max = Math.max.apply(null, $.map( $(selected) , function(elem) {return $(elem).position().top+$(elem).height();}) );
$(selected).each( function(idx,elem) {
$(elem).css('top',max-$(elem).height());
});
_showSavePageNeeded(true);
};
function onAlignLeft(selected)
{
var min = Math.min.apply(null, $.map( $(selected) , function(elem) {return $(elem).position().left;}) );
$(selected).each( function(idx,elem) {
$(elem).css('left',min);
});
_showSavePageNeeded(true);
};
function onAlignVertical(selected)
{
var max = Math.max.apply(null, $.map( $(selected) , function(elem) {return $(elem).position().left+$(elem).width()/2;}) );
$(selected).each( function(idx,elem) {
$(elem).css('left',max-$(elem).width()/2);
});
_showSavePageNeeded(true);
};
function onAlignRight(selected)
{
var max = Math.max.apply(null, $.map( $(selected) , function(elem) {return $(elem).position().left+$(elem).width();}) );
$(selected).each( function(idx,elem) {
$(elem).css('left',max-$(elem).width());
});
_showSavePageNeeded(true);
};
// ------------------------------------------
// public Callback
// ------------------------------------------
function _onoffStatus(device,widget) {
var status = MultiBox.getStatus(device, widget.properties.service, widget.properties.variable);
if ( ( (widget.properties.offvalue=='') && ((status==undefined) || (status==null) ||(status==false) || (status=='0')) ) || (status==widget.properties.offvalue) )
status = 0;
else if ( ((widget.properties.onvalue=='') && ((status=='true') || (status=='1') || (status>=1))) || (status==widget.properties.onvalue) )
status = 1;
if (widget.properties.inverted==true)
status = 1-status;
return status
};
function _onoffOnClick(widgetid) {
// find the widget
var pagename = _getActivePageName();
var page = PageManager.getPageFromName( pagename );
var widget=PageManager.getWidgetByID( page, widgetid );
// find the device
var device= MultiBox.getDeviceByAltuiID(widget.properties.deviceid);
// trigger the right action
var status = _onoffStatus(device,widget);
if (widget.properties.inverted)
status = 1-status;
var actiondescriptor = (status==1) ? widget.properties.action_off : widget.properties.action_on;
MultiBox.runAction( device, actiondescriptor.service, actiondescriptor.action, actiondescriptor.params);
};
// ------------------------------------------
// Master table for toolbox configuration
// ------------------------------------------
function _toolHtml(glyph,label) {
return "
{0} {1} ".format(glyph,label);
};
function _getToolByClass( cls )
{
var result = null;
$.each(tools, function(idx,tool) {
if (tool.cls == cls)
{
result = tool;
return false;
}
});
return result;
};
function _getActivePageName() {
return $("#altui-page-tabs li.active").text();
// return pagename != undefined ? pagename.substring( "altui-page-".length) : '';
};
// one page if specified, all pages otherwise
function _getPageSelector( page ) {
if (page == undefined)
return ".altui-page-content-one";
return "#altui-page-content-{0}".format(page.name.replace(' ','_'));
};
function _getWidgetSelector(page,widget) {
if ((page==undefined) || (widget==undefined))
return "";
return _getPageSelector(page)+" .altui-widget#"+widget.id
};
function _createPageTabsHtml( bEditMode ) {
var actions = "";
var lines = new Array();
PageManager.forEachPage( function( idx, page) {
lines.push( "
{0} ".format(page.name,page.name.replace(' ','_')) ); // no white space in ID
});
if (bEditMode==true) {
actions+="
";
actions+="";
actions+="Actions ";
actions+=" ";
actions+="";
actions+=" ";
}
return "
"+lines.join('')+actions+" ";
};
function _getWidgetHtml( widget , bEditMode )
{
var html="";
if (widget!=null)
{
var tool = _getToolByClass( widget.cls )
widget.properties = $.extend(true,{}, tool.properties, widget.properties);
var style = (widget.size!=undefined)
? 'style="width:{0}px; height:{1}px; z-index:{2};"'.format(widget.size.width, widget.size.height,widget.zindex)
: 'style="z-index:{0};"'.format(widget.zindex);
html += ("
").format(widget.cls,widget.id,style);
html += (tool.widgetdisplay)(widget,bEditMode);
html +="
";
var temp = $(html)
.css({
position:'absolute',
overflow: 'hidden',
top: widget.position.top,
left: widget.position.left
});
html = $(temp).wrap( "
" ).parent().html();
}
return html;
};
function _getPageHtml(page,bEditMode) {
var pageHtml = "
";
if (page.children)
$.each(page.children, function(idx,child) {
pageHtml += _getWidgetHtml( child, bEditMode );
});
pageHtml += "
";
var str = "
{1}
".format(page.name.replace(' ','_'),pageHtml); // no white space in IDs
var elem = $(str).css('background',page.background);
return elem.wrap( "
" ).parent().html();
};
function _updateDynamicDisplayTools( bEdit )
{
// var pagename = _getActivePageName();
PageManager.forEachPage( function( idx, page) {
$.each(tools, function(idx,tool) {
if ($.isFunction( tool.onWidgetDisplay) )
{
var selector = "#altui-page-content-{0} .{1}".format(page.name,tool.cls);
$(selector).each( function(idx,elem) {
var widgetid = $(elem).prop('id');
(tool.onWidgetDisplay)(page,widgetid, bEdit); // edit mode
})
}
});
});
};
function _createControllerSelect(htmlid) {
var html = "";
html += "
";
return html;
};
var bUIReady = false;
var bEngineReady = false;
// explicitly return public methods when this object is instantiated
return {
//---------------------------------------------------------
// PUBLIC functions
//---------------------------------------------------------
initEngine : _initEngine,
initCustomPages : _initCustomPages,
initLocalizedGlobals : _initLocalizedGlobals,
loadScript : _loadScript, //(scriptLocationAndName)
loadD3Script : _loadD3Script,
clearScripts : _clearScripts,
setTheme : _setTheme, //(themecss)
// UI helpers
checkAltuiUpdate : _checkAltuiUpdate,
UI7Check : function() { return _ui7Check; },
RemoteAccessUrl : function() { return _remoteAccessUrl; },
stoprefreshModes : _stoprefreshModes,
refreshModes : _refreshModes,
// custom panel widget callbacks
onoffOnClick : _onoffOnClick,
//drawing functions
jobStatusToColor : _jobStatusToColor,
defaultDeviceDrawWatts: _defaultDeviceDrawWatts, // default HTML for Watts & UserSuppliedWattage variable
deviceDraw : _deviceDraw, // draw the mini device on device page; can be customized by a plugin by ["DeviceDrawFunc"]
deviceDrawVariables : _deviceDrawVariables, // draw the device variables
deviceDrawActions : _deviceDrawActions, // draw the device Upnp Actions
deviceDrawControlPanel : _deviceDrawControlPanel, // draw the full device control panel page; can be customized by a plugin ["ControlPanelFunc"]
deviceCreate : _deviceCreate,
cameraDraw : _cameraDraw,
sceneDraw : _sceneDraw,
refreshUI : _refreshUI, //
refreshUIPerDevice : _refreshUIPerDevice,
refreshFooter : _refreshFooter,
// breadcumb
breadCrumb: function( title , param ) {
var tbl = [
{ id:0, title:_T('Home'), onclick:'UIManager.pageHome()', parent:-1},
{ id:1, title:_T('Rooms'), onclick:'UIManager.pageRooms()', parent:0 },
{ id:2, title:_T('Devices'), onclick:'UIManager.pageDevices()', parent:0 },
{ id:5, title:_T('Control Panel'), onclick:'UIManager.pagexxx()', parent:2 },
{ id:6, title:_T('Scenes'), onclick:'UIManager.pageScenes()', parent:0 },
{ id:7, title:_T('Scene Edit'), onclick:'UIManager.pageSceneEdit()', parent:6 },
{ id:8, title:_T('Plugins'), onclick:'UIManager.pagePlugins()', parent:0 },
{ id:9, title:_T('Custom Pages'), onclick:'UIManager.pageUsePages()', parent:0 },
{ id:10, title:_T('Edit Pages'), onclick:'UIManager.pageEditPages()', parent:0 },
{ id:11, title:_T('Credits'), onclick:'UIManager.pageCredits()', parent:0 },
{ id:12, title:_T('LuaTest'), onclick:'UIManager.pageLuaTest()', parent:0 },
{ id:13, title:_T('LuaStart'), onclick:'UIManager.pageLuaStart()', parent:0 },
{ id:14, title:_T('Options'), onclick:'UIManager.pageOptions()', parent:0 },
{ id:15, title:_T('Editor'), onclick:'UIManager.pageEditor()', parent:8 },
{ id:16, title:_T('ZWave'), onclick:'UIManager.pageZwave()', parent:0 },
{ id:17, title:_T('Localize'), onclick:'UIManager.pageLocalization()', parent:0 },
{ id:18, title:_T('Debug'), onclick:'UIManager.pageDebug()', parent:0 },
{ id:19, title:_T('Power'), onclick:'UIManager.pagePower()', parent:0 },
{ id:20, title:_T('Parent/Child'), onclick:'UIManager.pageChildren()', parent:0 },
{ id:21, title:_T('zWaveRoutes'), onclick:'UIManager.pageRoutes()', parent:0 },
{ id:22, title:_T('Quality'), onclick:'UIManager.pageQuality()', parent:0 },
{ id:23, title:_T('TblDevices'), onclick:'UIManager.pageTblDevices()', parent:0 },
{ id:24, title:_T('OsCommand'), onclick:'UIManager.pageOsCommand()', parent:0 },
{ id:25, title:_T('Triggers'), onclick:'UIManager.pageTriggers()', parent:6 },
{ id:26, title:_T('Themes'), onclick:'UIManager.pageThemes()', parent:0 },
{ id:27, title:_T('TblScenes'), onclick:'UIManager.pageTblScenes()', parent:0 },
{ id:28, title:_T('TblControllers'), onclick:'UIManager.pageTblControllers()', parent:0 },
];
function _parentsOf(child) {
var html = "";
$.each(tbl, function( idx,line) {
if (child.parent==line.id) {
var thisline = "
"+line.title+" ";
var parentlines = (line.parent==-1) ? '' : _parentsOf(line);
html = parentlines + thisline;
return false;
}
});
return html;
};
var html="";
html+="
";
// html+="Home ";
// html+="Device ";
// html+="Data ";
$.each(tbl, function( idx,line) {
if (line.title==title) {
html += _parentsOf(line);
html += "{0} ".format(line.title);
}
});
html+=" ";
return html;
},
// pages
oneColumnLayout: function(title)
{
var body="";
body+="
";
body+="
";
body+="
"+title+" ";
body+="
";
body+="
";
body+="
";
body+="
";
return body;
},
twoColumnLayout: function(title)
{
var body="";
body+="
";
body+="
";
body+="
"+title+" ";
body+="
";
body+="
";
body+="
";
body+="
".format( (MyLocalStorage.getSettings('FixedLeftButtonBar') || "")==1 ? 'affix' : '' );
body+="
";
body+=" ";
body+="
";
body+="
";
body+="
";
return body;
},
clearPage : function(breadcrumb,title,layout)
{
var layoutfunc = layout || UIManager.twoColumnLayout;
UIManager.stoprefreshModes();
$(".navbar-collapse").collapse('hide');
$(".altui-layout").remove();
var body = (layoutfunc)(title || '' );
$("div[role=main]").append(body);
PageMessage.init();
$("#altui-toggle-messages").before ( UIManager.breadCrumb( breadcrumb ) );
// elements outside of the layout
$("#dialogs").off().empty();
$(".altui-scripts").remove();
// remove Blockly
// $(".blocklyWidgetDiv").remove();
// $(".blocklyTooltipDiv").remove();
$(".blocklyToolboxDiv").remove();
$("body").append("
");
},
//window.open("data_request?id=lr_ALTUI_Handler&command=home","_self");
pageHome : function()
{
UIManager.clearPage(_T('Home'),_T("Welcome to ALTUI"),UIManager.oneColumnLayout);
if ( MyLocalStorage.getSettings('ShowWeather')==1 )
// if(0)
{
var language = getQueryStringValue("lang") || window.navigator.userLanguage || window.navigator.language;
var ws = MultiBox.getWeatherSettings();
if ((ws.tempFormat==undefined) || (ws.tempFormat==""))
ws.tempFormat=MyLocalStorage.getSettings('TempUnitOverride');
var html="";
html ="
";
// console.log(html);
$(".altui-mainpanel").append(html);
}
UIManager.drawHouseMode();
$(".altui-mainpanel").append("
");
$(".altui-mainpanel")
.off("click",".altui-favorites-scene-content")
.on("click",".altui-favorites-scene-content",function() {
var altuiid = $(this).data("altuiid");
MultiBox.runSceneByAltuiID(altuiid);
})
.off("click",".altui-favorites-device-content")
.on("click",".altui-favorites-device-content",function() {
var altuiid = $(this).data("altuiid");
var device = MultiBox.getDeviceByAltuiID(altuiid);
switch( device.device_type) {
case "urn:schemas-upnp-org:device:BinaryLight:1":
var status = MultiBox.getStatus( device, 'urn:upnp-org:serviceId:SwitchPower1', 'Status' );
MultiBox.runAction(device,"urn:upnp-org:serviceId:SwitchPower1","SetTarget", {newTargetValue:1-parseInt(status||1)});
break;
case "urn:schemas-micasaverde-com:device:WindowCovering:1" :
case "urn:schemas-upnp-org:device:DimmableLight:1":
var status = parseInt(MultiBox.getStatus(device,"urn:upnp-org:serviceId:Dimming1","LoadLevelStatus") || 1);
MultiBox.runAction( device , "urn:upnp-org:serviceId:Dimming1", "SetLoadLevelTarget", {newLoadlevelTarget: ((status>0) ? 0 : 100) } );
break;
case "urn:schemas-upnp-org:device:VSwitch:1":
MultiBox.runAction( device, "urn:upnp-org:serviceId:VSwitch1","ToggleState", {} );
break;
case "urn:schemas-upnp-org:device:cplus:1":
// var status = MultiBox.getStatus( device, 'urn:upnp-org:serviceId:cplus1', 'Present' );
// status = parseInt(status);
// MultiBox.runAction( device, "urn:upnp-org:serviceId:cplus1","SetPower", {newPowerState: 1-status} );
// break;
default:
UIManager.pageControlPanel(altuiid);
break;
}
});
_redrawFavorites();
},
pageRemoteAccess : function ()
{
window.open( _remoteAccessUrl, '_blank');
},
// ===========================
// Page UI pieces helpers
// ===========================
setLeftnavRoomsActive : function ( selectedRoom ) {
var button = null;
$(".altui-leftbutton").toggleClass("active",false);
if ($.isArray(selectedRoom)) {
$.each(selectedRoom, function(i,room) {
button = $(".altui-leftbutton:contains('"+room+"')");
button.toggleClass("active",true);
});
} else {
button = $(".altui-leftbutton[id="+selectedRoom+"]")
button.toggleClass("active",true);
}
},
leftnavRooms : function ( clickFunction , roomLoadedFunction)
{
var leftnav = $(".altui-leftnav");
$("body").off("click",".altui-leftbutton");
leftnav.empty()
.append( leftNavButtonTemplate.format( -1, "", _T("All")) )
.append( leftNavButtonTemplate.format( -2, "", starGlyph+' '+_T("Favorites")) )
.append( leftNavButtonTemplate.format( 0, "", _T("No Room")) );
// install a click handler on button
if ($.isFunction( clickFunction )) {
$("body").on("click",".altui-leftbutton",function() {
$(this).parent().children().removeClass("active")
$(this).addClass("active");
clickFunction.apply($(this), [$(this).prop('id'), $(this).data('altuiid')]);
});
}
MultiBox.getRooms( null,null,function( rooms ) {
// calculate unique rooms by name
var namearray = $.map(rooms, function(r) { return r.name;} );
var filteredrooms = $.grep(rooms, function(room,idx) {
return $.inArray(room.name ,namearray) == idx;
});
$.each(filteredrooms, function(i,room) {
leftnav.append( leftNavButtonTemplate.format( room.id, room.altuiid, (room!=null) ? room.name : _T("No Room")) );
})
if ($.isFunction(roomLoadedFunction))
(roomLoadedFunction)(rooms);
});
},
// ===========================
// Full Pages update Methods
// ===========================
pageRooms : function ()
{
function _roomSummary(room) {
var rcontroller = MultiBox.controllerOf(room.altuiid).controller;
var devices = $.grep( MultiBox.getDevicesSync(), function(d) {
var dcontroller = MultiBox.controllerOf(d.altuiid).controller;
return (d.room == room.id) && ( dcontroller==rcontroller);
});
return devices.length;
};
UIManager.clearPage(_T('Rooms'),_T("Rooms"),UIManager.oneColumnLayout);
var formHtml="";
formHtml+="
";
// on the left nav
// nothing
// on the main panel
// table of rooms
$(".altui-mainpanel")
.append( _createControllerSelect('altui-controller-select'))
.append($("
"));
$("#altui-controller-select").closest(".form-group").append(formHtml);
var roomListTemplate = "
{0} {1} {2} {3} ";
MultiBox.getRooms( null,null,function( rooms) {
if (rooms) {
$.each(rooms.sort(altuiSortByName), function(idx,room) {
var id = room.altuiid;
var delButtonHtml = smallbuttonTemplate.format( id, 'altui-delroom', deleteGlyph);
var viewButtonHtml = smallbuttonTemplate.format( id, 'altui-viewroom', searchGlyph);
$(".altui-mainpanel tbody").append( roomListTemplate.format(id,(room!=null) ? room.name : _T("No Room"),_roomSummary(room),viewButtonHtml+delButtonHtml) );
});
// install click handler for buttons
$(".altui-mainpanel")
.off("click","span.altui-room-name")
.on("click","span.altui-room-name",function(event) {
var id = $(this).prop('id');
var room = MultiBox.getRoomByAltuiID(id);
$(this).replaceWith("
".format(room.altuiid, room.name.escapeXml()));
})
.off("focusout","input.altui-room-name")
.on("focusout","input.altui-room-name",function(event) {
var id = $(this).prop('id');
var room = MultiBox.getRoomByAltuiID(id);
var value = $(this).val();
room.name = value;
MultiBox.renameRoom(room, room.name );
$(this).replaceWith("
{1} ".format(room.altuiid,room.name));
});
$("button.altui-viewroom").click( function(event) {
var id = $(this).prop('id');
var room = MultiBox.getRoomByAltuiID(id);
UIManager.pageDevices({ room:id });
});
$("button.altui-delroom").click( function(event) {
var id = $(this).prop('id');
var room = MultiBox.getRoomByAltuiID(id);
var tr = $(this).closest("tr");
DialogManager.confirmDialog(_T("Are you sure you want to delete room")+" ("+id+")",function(result) {
if (result==true) {
$(tr).remove();
MultiBox.deleteRoom( room );
}
})
});
}
});
// $(".altui-mainpanel").off("click","button#altui-create-room");
$(".altui-mainpanel").on("click","button#altui-create-room",function()
{
MultiBox.createRoom(parseInt($("#altui-controller-select").val()),$("#altui-create-room-name").val() );
});
},
pageControlPanel: function( altuiid )
{
// var rooms = MultiBox.getRoomsSync();
var device = MultiBox.getDeviceByAltuiID( altuiid );
// var controllerid = MultiBox.controllerOf(altuiid).controller;
var category = MultiBox.getCategoryTitle( device.category_num );
UIManager.clearPage(_T('Control Panel'),"{0} {1}
#{2} ".format( device.name , category ,altuiid),UIManager.oneColumnLayout);
var html = "
";
html += ""+_T("Attributes")+" ";
html += ""+_T("Variables")+" ";
html += ""+_T("Actions")+" ";
html += ""+_T("Configuration")+" ";
html += ""+_T("Used in")+" ";
html += ""+_T("Notification")+" ";
if (AltuiDebug.IsDebug())
html += buttonDebugHtml;
html += "
";
$(".altui-mainpanel").append( html );
//
// Draw device control panel (attributes+panel+debug)
//
$(".altui-mainpanel").append( "
" );
var container = $("#altui-device-controlpanel-container-"+altuiid);
UIManager.deviceDrawControlPanel( device, container ); //altuiid, device, domparent
//
// Manage interactions
//
$("#altui-device-attributes-"+altuiid).toggle(false); // hide them by default;
$("#altui-device-config-"+altuiid).toggle(false); // hide them by default;
$(".altui-device-usedin").toggle(false); // toogle attribute box
$(".altui-device-triggers").toggle(false); // toogle attribute box
// $("#altui-device-usedin-"+altuiid).toggle(false); // hide them by default;
// $("#altui-device-triggers-"+altuiid).toggle(false); // hide them by default;
$(".altui-debug-div").toggle(false); // hide
$(container).off('click','.altui-deldevice')
.on('click','.altui-deldevice', function(e) {
var id = $(this).prop('id');
DialogManager.confirmDialog(_T("Are you sure you want to delete device ({0})").format(id),function(result) {
if (result==true) {
MultiBox.deleteDevice(device);
}
});
});
$("#altui-toggle-attributes").click( function() {
$("#altui-device-attributes-"+altuiid).toggle(); // toogle attribute box
$("#altui-toggle-attributes span.caret").toggleClass( "caret-reversed" );
});
$("#altui-device-usedin").click( function() {
// $("#altui-device-usedin-"+altuiid).toggle(); // toogle attribute box
$(".altui-device-usedin").toggle(); // toogle attribute box
$("#altui-device-usedin span.caret").toggleClass( "caret-reversed" );
});
$("#altui-device-triggers").click( function() {
// $("#altui-device-triggers-"+altuiid).toggle(); // toogle attribute box
$(".altui-device-triggers").toggle(); // toogle attribute box
$("#altui-device-triggers span.caret").toggleClass( "caret-reversed" );
});
$("#altui-device-config").click( function() {
$("#altui-device-config-"+altuiid).toggle(); // toogle attribute box
$("#altui-device-config span.caret").toggleClass( "caret-reversed" );
});
// resgister a handler on tab click to force a disaply & reload of JS tab , even if already loaded
$(container).off('click','.altui-device-controlpanel ul#altui-devtab-tabs a')
.on('click','.altui-device-controlpanel ul#altui-devtab-tabs a', function(e) {
// remove the no refresh class so we force a full redisplay of the
// tab with the latest var values
var targettab = $(e.target).attr("href").slice("#altui-devtab-content-".length);
var domparent = $('div#altui-devtab-content-'+targettab);
$(domparent).toggleClass('altui-norefresh',false);
});
// register a handler on tab changes to update height of domparent ( usefulk when child are in absolute positioning )
$(container).off('shown.bs.tab', 'a[data-toggle="tab"]');
$(container).on('shown.bs.tab', 'a[data-toggle="tab"]', function (e) {
var controlpanel = $(e.target).closest(".altui-device-controlpanel");
var altuiid = $(controlpanel).data("altuiid")
var device = MultiBox.getDeviceByAltuiID( altuiid );
var activeTabIdx = _getActiveDeviceTabIdx();
var domparent = $('div#altui-devtab-content-'+activeTabIdx);
_displayActiveDeviceTab(activeTabIdx, device, domparent);
});
},
onDeviceIconError : function( altuiid ) {
$("div.altui-device[data-altuiid="+altuiid+"] img").attr('src',defaultIconSrc);
},
pageDevices : function ( filter )
{
var _domMainPanel = null;
var _roomID2Name = {};
var _deviceID2RoomName = {};
var _deviceDisplayFilter = $.extend( {
filterformvisible : false,
room : MyLocalStorage.getSettings("DeviceRoomFilter") || -1,
favorites : (MyLocalStorage.getSettings("ShowFavoriteDevice")==true),
invisible : (MyLocalStorage.getSettings("ShowInvisibleDevice")==true),
batterydevice : (MyLocalStorage.getSettings("ShowBatteryDevice")==true),
category : MyLocalStorage.getSettings("CategoryFilter") || 0,
filtername : MyLocalStorage.getSettings("DeviceFilterName") || "",
isRoomFilterValid : function() {
return ($.isArray(this.room)) ? (this.room.length>0) : (this.room<=0);
},
isCategoryFilterValid : function() {return this.category!=0},
}, filter );
// filter function
function deviceFilter(device) {
if ((_deviceID2RoomName[ device.altuiid ]==null) && (parseInt(device.room)!=0)) {
var controller = MultiBox.controllerOf(device.altuiid).controller;
_deviceID2RoomName[ device.altuiid ] = _roomID2Name["{0}-{1}".format(controller,device.room)];
}
//_deviceID2RoomName[device.altuiid] == _roomID2Name[_deviceDisplayFilter.room]
var batteryLevel = MultiBox.getDeviceBatteryLevel(device);
var regexp = new RegExp(RegExp.escape(_deviceDisplayFilter.filtername),"i")
return ( (parseInt(_deviceDisplayFilter.room) <0) ||
($.isArray(_deviceDisplayFilter.room) && ((_deviceDisplayFilter.room.length==0) || _deviceDisplayFilter.room.in_array(_deviceID2RoomName[device.altuiid]))) ||
( (_deviceDisplayFilter.room==0) && (device.room==0) )
)
&& ( (_deviceDisplayFilter.invisible == true) || (device.invisible != "1") )
&& ( (_deviceDisplayFilter.category == 0) || ( _deviceDisplayFilter.category.in_array(device.category_num)) )
&& ( ((_deviceDisplayFilter.favorites == false) && (_deviceDisplayFilter.room!=-2) ) || (device.favorite == true) )
&& ( (_deviceDisplayFilter.filtername.length==0) || (device.name.search( regexp )!=-1) )
&& ( (batteryLevel != null) || (false == _deviceDisplayFilter.batterydevice));
}
function _deviceCreateModalHtml() {
var deviceCreateModalTemplate = "
";
deviceCreateModalTemplate += "
";
deviceCreateModalTemplate += "
";
deviceCreateModalTemplate += " ";
deviceCreateModalTemplate += "
";
deviceCreateModalTemplate += "
";
deviceCreateModalTemplate += "
";
deviceCreateModalTemplate += "
";
deviceCreateModalTemplate += "
";
deviceCreateModalTemplate += " ";
deviceCreateModalTemplate += "
";
deviceCreateModalTemplate += "
";
deviceCreateModalTemplate += "
";
return deviceCreateModalTemplate;
}
function endDrawDevice(devices) {
UIManager.refreshUI(true,false);
};
function drawDeviceEmptyContainer(idx, device) {
_domMainPanel.append(ALTUI_Templates.deviceEmptyContainerTemplate.format(device.id,device.altuiid));
};
function _drawDeviceToolbar() {
var filterHtml="";
// filterHtml+="
";
filterHtml+="
";
filterHtml+="
";
filterHtml+="
";
var toolbarHtml="";
var roomfilterHtml="";
var categoryfilterHtml="";
var dfd = $.Deferred();
$.when( _drawRoomFilterButtonAsync(_deviceDisplayFilter.room) )
.then( function(html) {
roomfilterHtml = html;
categoryfilterHtml+='
';
$.when( MultiBox.getCategories(
function(idx,category) {
categoryfilterHtml+='{1} '.format(
category.id,category.name,
((_deviceDisplayFilter.category!=0) && (_deviceDisplayFilter.category.in_array(category.id))) ? 'selected' : ''
);
},
null,
function(categories) {
categoryfilterHtml+=' ';
categoryfilterHtml+="
";
categoryfilterHtml+= (searchGlyph + ' ' +_T('Filter') + " ");
categoryfilterHtml+=" ";
categoryfilterHtml+="
";
categoryfilterHtml+= (plusGlyph + " " + _T("Create"));
categoryfilterHtml+=" ";
}
))
.then ( function(categories) {
function _onChangeRoomFilter() {
//_roomID2Name[_deviceDisplayFilter.room]
_deviceDisplayFilter.room = $.map($('#altui-device-room-filter :selected'),function(e) { return (e.value); }) // array of room names
UIManager.setLeftnavRoomsActive( _deviceDisplayFilter.room );
MyLocalStorage.setSettings("DeviceRoomFilter",_deviceDisplayFilter.room);
if ( MyLocalStorage.getSettings('SyncLastRoom')==1 )
MyLocalStorage.setSettings("SceneRoomFilter",_deviceDisplayFilter.room);
$("#altui-device-room-filter").next(".btn-group").children("button").toggleClass("btn-info",_deviceDisplayFilter.isRoomFilterValid());
_drawDevices(deviceFilter,false); // do not redraw toolbar
};
function _onChangeCategoryFilter() {
// Get selected options.
_deviceDisplayFilter.category = $.map($('#altui-device-category-filter :selected'),function(e) { return parseInt(e.value); }) // array of ints
if (_deviceDisplayFilter.category.length==0)
_deviceDisplayFilter.category=0;
MyLocalStorage.setSettings("CategoryFilter",_deviceDisplayFilter.category);
$("#altui-device-category-filter").next(".btn-group").children("button").toggleClass("btn-info",_deviceDisplayFilter.isCategoryFilterValid());
_drawDevices(deviceFilter,false); // do not redraw toolbar
};
// Display
$(".altui-device-toolbar").replaceWith( "
"+roomfilterHtml+categoryfilterHtml+filterHtml+"
" );
$('#altui-device-room-filter').multiselect({
disableIfEmpty: true,
enableHTML : true,
includeSelectAllOption: true,
nonSelectedText: homeGlyph + ' ' +_T('Room'), // non selected text on the button
onSelectAll: function() {
_onChangeRoomFilter();
},
onChange: function(element, checked) {
_onChangeRoomFilter();
},
onDropdownShown: function(event) {
$("#altui-device-room-filter").next(".btn-group").find(".caret").toggleClass( "caret-reversed" );
},
onDropdownHidden: function(event) {
$("#altui-device-room-filter").next(".btn-group").find(".caret").toggleClass( "caret-reversed" );
}
});
var nRooms = $('#altui-device-room-filter').next(".btn-group").find("li").length;
if (nRooms+1>=parseInt(MyLocalStorage.getSettings('Menu2ColumnLimit')))
$('#altui-device-room-filter').next(".btn-group").children("ul").attr('style','columns: 2; -webkit-columns: 2; -moz-columns: 2;');
$('#altui-device-category-filter').multiselect({
disableIfEmpty: true,
enableHTML : true,
includeSelectAllOption: true,
nonSelectedText: tagsGlyph + ' ' +_T('Category'), // non selected text on the button
onSelectAll: function() {
_onChangeCategoryFilter();
},
onChange: function(element, checked) {
_onChangeCategoryFilter();
},
onDropdownShown: function(event) {
$("#altui-device-category-filter").next(".btn-group").find(".caret").toggleClass( "caret-reversed" );
},
onDropdownHidden: function(event) {
$("#altui-device-category-filter").next(".btn-group").find(".caret").toggleClass( "caret-reversed" );
}
});
if (categories.length+1>=parseInt(MyLocalStorage.getSettings('Menu2ColumnLimit')))
$('#altui-device-category-filter').next(".btn-group").children("ul").attr('style','columns: 2; -webkit-columns: 2; -moz-columns: 2;');
$(".altui-pagefilter").css("display","inline");
// interactivity
$("#altui-device-remove-btn").off("click touchend").on("click touchend",function() {
$(this).parent().find("input").val("");
_deviceDisplayFilter.filtername = "";
MyLocalStorage.setSettings("DeviceFilterName",_deviceDisplayFilter.filtername);
_drawDevices(deviceFilter);
});
$("#altui-device-search-btn").off("click touchend").on("click touchend",function() { $(this).focus(); });
$("#altui-device-name-filter input").autocomplete({
source: $.map( MultiBox.getDevicesSync() , function( device, i ) { return device.name; } ),
appendTo: "#altui-device-name-filter",
delay: 500,
// minLength: 3,
change: function(event, ui ) {
var v= $(this).val();
_deviceDisplayFilter.filtername = v;
MyLocalStorage.setSettings("DeviceFilterName",_deviceDisplayFilter.filtername);
_drawDevices(deviceFilter);
},
select: function( event, ui ) {
var v= ui.item.label;
_deviceDisplayFilter.filtername = v;
MyLocalStorage.setSettings("DeviceFilterName",_deviceDisplayFilter.filtername);
_drawDevices(deviceFilter);
},
response: function( event, ui ) {
if (ui.content.length>0) {
$("#altui-device-name-filter").removeClass("has-error");
return;
}
$("#altui-device-name-filter").addClass("has-error");
ui.content.push( { label:_T('No Match'), value:'' } );
},
});
$("#altui-device-name-filter input").val(_deviceDisplayFilter.filtername);
var v=$("#altui-device-name-filter input").val();
if (v && v.length>0)
$("#altui-device-name-filter input").focus();
$("#altui-device-filter-form").toggle(_deviceDisplayFilter.filterformvisible);
$("#altui-device-filter").click( function() {
_deviceDisplayFilter.filterformvisible = !_deviceDisplayFilter.filterformvisible;
$("#altui-device-filter-form").toggle();
$("#altui-device-filter span.caret").toggleClass( "caret-reversed" );
});
$("#altui-show-battery").prop('checked',_deviceDisplayFilter.batterydevice);
$("#altui-show-battery").click( function() {
_deviceDisplayFilter.batterydevice = $(this).prop('checked');
MyLocalStorage.setSettings("ShowBatteryDevice",_deviceDisplayFilter.batterydevice);
_drawDevices(deviceFilter);
});
$("#altui-show-invisible").prop('checked',_deviceDisplayFilter.invisible);
$("#altui-show-invisible").click( function() {
_deviceDisplayFilter.invisible = $(this).prop('checked');
MyLocalStorage.setSettings("ShowInvisibleDevice",_deviceDisplayFilter.invisible);
_drawDevices(deviceFilter);
});
$("#altui-show-favorites").prop('checked',_deviceDisplayFilter.favorites);
$("#altui-show-favorites").click( function() {
_deviceDisplayFilter.favorites = $(this).prop('checked');
MyLocalStorage.setSettings("ShowFavoriteDevice",_deviceDisplayFilter.favorites);
_drawDevices(deviceFilter);
});
$("#altui-device-create").click( UIManager.deviceCreate );
$("#altui-device-room-filter a").click( function() {
$(this).closest(".dropdown-menu").find("li.active").removeClass("active");
$(this).parent().addClass("active");
_onClickRoomButton( $(this).prop('id') , $(this).data('altuiid') );
});
$("#altui-device-room-filter").next(".btn-group").children("button").toggleClass("btn-info",_deviceDisplayFilter.isRoomFilterValid());
$("#altui-device-category-filter").next(".btn-group").children("button").toggleClass("btn-info",_deviceDisplayFilter.isCategoryFilterValid());
dfd.resolve();
});
});
return dfd.promise();
};
function _drawDevices(filterfunc,bToolbar)
{
if (bToolbar != false ) {
_drawDeviceToolbar(); /*.done( function() {}); */
}
// Category & Form filter
_domMainPanel = $(".altui-mainpanel").empty();
MultiBox.getDevices( drawDeviceEmptyContainer , filterfunc, endDrawDevice);
};
function _onClickRoomButton(htmlid,altuiid)
{
// var roomid = $(this).prop('id');
_deviceDisplayFilter.room = (altuiid !="") ? [ _roomID2Name[ altuiid ] ] : htmlid;
UIManager.setLeftnavRoomsActive(_deviceDisplayFilter.room);
MyLocalStorage.setSettings("DeviceRoomFilter",_deviceDisplayFilter.room);
if ( MyLocalStorage.getSettings('SyncLastRoom')==1 )
MyLocalStorage.setSettings("SceneRoomFilter",_deviceDisplayFilter.room);
_drawDevices(deviceFilter);
};
// Page Preparation
UIManager.clearPage(_T('Devices'),_T("Devices"));
$("#altui-pagetitle").css("display","inline").after("
");
// Dialogs
DialogManager.registerDialog('deviceCreateModal', _deviceCreateModalHtml() );
// on the left, get the rooms
$(".altui-leftnav").empty();
UIManager.leftnavRooms(
_onClickRoomButton, // click button callback
function(rooms) { // all rooms loaded callback
$.each(rooms, function(idx,room) {
_roomID2Name[ room.altuiid ] = room.name;
});
UIManager.setLeftnavRoomsActive(_deviceDisplayFilter.room);
}
);
_drawDevices(deviceFilter);
// deletegated event for title click / rename for device
$(".altui-mainpanel")
// .on("click",".altui-camera-picture", _onClickCamera )
.on("click",".altui-device-title-name",function() {
if ($(this).find("input.altui-device-title-input").length>=1)
return;
var text = $(this).text();
var altuiid = $(this).parents(".altui-device").data('altuiid');
$(this).closest(".altui-device").addClass("altui-norefresh");
$(this).html("
");
$("input#"+altuiid+".altui-device-title-input").focusout({altuiid:altuiid},function(event){
var device = MultiBox.getDeviceByAltuiID(event.data.altuiid);
var newname = $(this).val();
DialogManager.confirmDialog(_T("Are you sure you want to modify this device to:")+newname,function(result) {
if (result==true)
MultiBox.renameDevice(device, newname );
});
$(this).closest(".altui-device").removeClass("altui-norefresh");
$(this).parent().text(device.name);
});
})
// .off("click",".altui-favorite")
.on("click",".altui-favorite",function(event) {
var altuiid = $(this).parents(".altui-device").data('altuiid');
var device = MultiBox.getDeviceByAltuiID(altuiid);
device.favorite = !device.favorite;
$(this).parents(".altui-device-title").html(_enhancedDeviceTitle(device));
Favorites.set('device', altuiid, device.favorite);
})
// .off("click",".altui-device-controlpanelitem")
.on("click",".altui-device-controlpanelitem",function(){
var altuiid = $(this).parents(".altui-device").data('altuiid');
UIManager.pageControlPanel(altuiid);
})
.on("click",".altui-device-hideshowtoggle",function(){
var altuiid = $(this).parents(".altui-device").data('altuiid');
var device = MultiBox.getDeviceByAltuiID(altuiid);
device.invisible = (device.invisible!="1") ? "1" : ""
MultiBox.setAttr(device, "invisible", device.invisible ,function(result) {
if (result==null) {
PageMessage.message( "Set Attribute action failed!", "warning" );
}
else {
PageMessage.message( "Set Attribute succeeded! a LUUP reload will happen now, be patient", "success" );
_drawDevices(deviceFilter);
}
});
})
// .off("click",".altui-device-icon")
.on("click",".altui-device-icon",function(){
var altuiid = $(this).parents(".altui-device").data('altuiid');
UIManager.pageControlPanel(altuiid);
});
},
pageScenes: function ()
{
var _roomID2Name={};
var _sceneID2RoomName={};
var _sceneFilter={
room: MyLocalStorage.getSettings("SceneRoomFilter") || -1,
isValid: function() { return ($.isArray(this.room)) ? (this.room.length>0) : (this.room<=0); }
};
function _sceneInThisRoom(scene) {
if ((_sceneID2RoomName[scene.altuiid]==null)&&(scene.room>0)) {
var controller = MultiBox.controllerOf(scene.altuiid).controller;
_sceneID2RoomName[scene.altuiid] = _roomID2Name["{0}-{1}".format(controller,scene.room)];
}
return (
( $.isArray(_sceneFilter.room) && ((_sceneFilter.room.length==0) || _sceneFilter.room.in_array(_sceneID2RoomName[scene.altuiid])) ) ||
( (_sceneFilter.room==0) && (scene.room==0) ) ||
(_sceneFilter.room == -1) ||
( (_sceneFilter.room==-2) && (scene.favorite==true) )
&& ( (scene.notification_only==0) || (scene.notification_only==undefined) ) );
}
function _onClickRoomButton(htmlid,altuiid) {
_sceneFilter.room = (altuiid !="") ? [ _roomID2Name[ altuiid ] ] : htmlid;
UIManager.setLeftnavRoomsActive( _sceneFilter.room );
MyLocalStorage.setSettings("SceneRoomFilter",_sceneFilter.room);
if ( MyLocalStorage.getSettings('SyncLastRoom')==1 )
MyLocalStorage.setSettings("DeviceRoomFilter",_sceneFilter.room);
_drawScenes( _sceneInThisRoom );
};
function sceneDraw(idx, scene) {
var html = UIManager.sceneDraw(scene);
var scenecontainerTemplate="
";
scenecontainerTemplate += html;
scenecontainerTemplate += "
";
var domPanel = $(".altui-mainpanel");
domPanel.append(scenecontainerTemplate.format(scene.id));
};
function _onChangeRoomFilter() {
//_roomID2Name[_deviceDisplayFilter.room]
_sceneFilter.room = $.map($('#altui-device-room-filter :selected'),function(e) { return (e.value); }) // array of room names
UIManager.setLeftnavRoomsActive( _sceneFilter.room );
MyLocalStorage.setSettings("SceneRoomFilter",_sceneFilter.room);
if ( MyLocalStorage.getSettings('SyncLastRoom')==1 )
MyLocalStorage.setSettings("DeviceRoomFilter",_sceneFilter.room);
$("#altui-device-room-filter").next(".btn-group").children("button").toggleClass("btn-info",_sceneFilter.isValid());
_drawScenes(_sceneInThisRoom,false); // do not redraw toolbar
};
function _drawSceneToolbar() {
var toolbarHtml="";
$.when( _drawRoomFilterButtonAsync( _sceneFilter.room ) )
.then(function( html) {
toolbarHtml+= html; // room filter
toolbarHtml+="
";
toolbarHtml+=(plusGlyph + " " + _T("Create"));
toolbarHtml+=" ";
$(".altui-scene-toolbar").replaceWith( "
"+toolbarHtml+"
" );
$("#altui-scene-create").click( function() {
UIManager.pageSceneEdit(NULL_SCENE);
});
// multiselect
$('#altui-device-room-filter').multiselect({
disableIfEmpty: true,
enableHTML : true,
includeSelectAllOption: true,
nonSelectedText: homeGlyph + ' ' +_T('Room'), // non selected text on the button
onSelectAll: function() {
_onChangeRoomFilter();
},
onChange: function(element, checked) {
_onChangeRoomFilter();
},
onDropdownShown: function(event) {
$("#altui-device-room-filter").next(".btn-group").find(".caret").toggleClass( "caret-reversed" );
},
onDropdownHidden: function(event) {
$("#altui-device-room-filter").next(".btn-group").find(".caret").toggleClass( "caret-reversed" );
}
});
var nRooms = $('#altui-device-room-filter').next(".btn-group").find("li").length;
if (nRooms+1>=parseInt(MyLocalStorage.getSettings('Menu2ColumnLimit')))
$('#altui-device-room-filter').next(".btn-group").children("ul").attr('style','columns: 2; -webkit-columns: 2; -moz-columns: 2;');
$("#altui-device-room-filter").next(".btn-group").children("button").toggleClass("btn-info",_sceneFilter.isValid());
// $("#altui-device-room-filter a").click( function() {
// $(this).closest(".dropdown-menu").find("li.active").removeClass("active");
// $(this).parent().addClass("active");
// _onClickRoomButton( $(this).prop('id'), $(this).data("altuiid") );
// });
});
};
function afterSceneListDraw(scenes) {
$(".altui-mainpanel")
.off('click')
// .off("click",".altui-delscene")
.on("click",".altui-delscene",function() {
var altuiid = $(this).closest(".altui-scene").data('altuiid');
var scene = MultiBox.getSceneByAltuiID(altuiid);
DialogManager.confirmDialog(_T("Are you sure you want to delete scene ({0})").format(altuiid),function(result) {
if (result==true) {
MultiBox.deleteScene( scene );
}
});
})
// .off("click",".altui-pausescene")
.on("click",".altui-pausescene",function() {
var altuiid = $(this).closest(".altui-scene").data('altuiid');
var scene = MultiBox.getSceneByAltuiID(altuiid);
scene.paused = (scene.paused==1) ? 0 : 1;
MultiBox.editScene( altuiid , scene );
})
// .off("click",".altui-runscene")
.on("click",".altui-runscene",function() {
var altuiid = $(this).closest(".altui-scene").data('altuiid');
var scene = MultiBox.getSceneByAltuiID(altuiid);
$(this).removeClass("btn-primary").addClass("btn-success");
MultiBox.runScene( scene );
})
// .off("click",".altui-editscene")
.on("click",".altui-editscene",function() {
var altuiid = $(this).closest(".altui-scene").data('altuiid');
UIManager.pageSceneEdit( altuiid );
})
.on("click",".altui-scene-history",function() {
var altuiid = $(this).closest(".altui-scene").data('altuiid');
var scene = MultiBox.getSceneByAltuiID(altuiid);
var dialog = DialogManager.registerDialog('dialogModal',
defaultDialogModalTemplate.format(
_T("Scene History"), // title
"", // body
"modal-lg" // size
));
MultiBox.getSceneHistory( scene, function(history) {
var html="";
html += "
";
html +="
".format(altuiid);
html +="";
html += ("{0} {1} ".format(_T("Date"),_T("Name")));
html +=" ";
html +="";
history.lines.reverse();
$.each(history.lines, function(i,e) {
html += ("{0} {1} ".format( e.date, e.name) );
});
html +=" ";
html +="
";
html += "
";
$(dialog).find(".row-fluid").append(html);
$('div#dialogModal').modal();
});
})
.on("click",".altui-favorite",function(event) {
var altuiid = $(this).closest(".altui-scene").data('altuiid');
var scene = MultiBox.getSceneByAltuiID(altuiid);
scene.favorite = !scene.favorite;
Favorites.set('scene', altuiid, scene.favorite );
$(this).replaceWith( (scene.favorite==true) ? starGlyph : staremtpyGlyph );
})
.on("click",".altui-scene-title-name",function(event) {
if ( $(this).find("input").length>=1 )
return;
var scenedom = $(this).closest(".altui-scene");
var altuiid = scenedom.data('altuiid');
var scene = MultiBox.getSceneByAltuiID(altuiid);
scenedom.addClass("altui-norefresh");
$(this).html("
".format(altuiid,scene.name.escapeXml()));
})
.off("focusout")
.on("focusout",".altui-scene-title-input",function(event) {
var newname = $(this).val();
var namedom = $(this).parent();
var scenedom = $(this).closest(".altui-scene");
var altuiid = scenedom.data('altuiid');
var scene = MultiBox.getSceneByAltuiID(altuiid);
namedom.text(newname);
MultiBox.renameScene(scene,newname);
scenedom.removeClass("altui-norefresh");
});
};
function _drawScenes( filterfunc,bToolbar )
{
$(".altui-mainpanel").empty();
if (bToolbar != false ) {
_drawSceneToolbar(); /*.done( function() {}); */
}
MultiBox.getScenes( sceneDraw , filterfunc, afterSceneListDraw )
}
UIManager.clearPage(_T('Scenes'),_T("Scenes"));
$("#altui-pagetitle").css("display","inline").after("
");
// on the left, get the rooms
UIManager.leftnavRooms(
_onClickRoomButton, // click button callback
function(rooms) { // all rooms loaded callback
$.each(rooms, function(idx,room) {
_roomID2Name[ room.altuiid ] = room.name;
});
UIManager.setLeftnavRoomsActive( _sceneFilter.room );
}
);
_drawScenes( _sceneInThisRoom );
},
pageSceneEdit: function (altuiid,newscene_template)
{
// Deep copy so we can edit it
var newid = MultiBox.getNewSceneID( MultiBox.controllerOf(altuiid).controller );
var orgscene = (altuiid!=NULL_SCENE) ? MultiBox.getSceneByAltuiID( altuiid ) : {
name:"New Scene",
id: newid.id,
altuiid: newid.altuiid,
triggers: [],
groups: [{"delay":0,"actions":[]}],
timers: [],
lua:"",
room:0
};
var scene = jQuery.extend(true, {timers:[], triggers:[], groups:[] }, orgscene, newscene_template );
// clear page
UIManager.clearPage(_T('Scene Edit'),altuiid!=NULL_SCENE ? "Edit Scene #"+scene.altuiid : "Create Scene",UIManager.oneColumnLayout);
var editor = SceneEditor( scene );
var html = "
" ;
html += UIManager.sceneDraw( scene, true); // draw scene
html += editor.sceneEditDraw(); // draw editor
html += "
";
$(".altui-mainpanel").append( html );
editor.runActions( );
},
pagePlugins: function ()
{
function _sortBySourceName(a,b)
{
if (a.SourceName < b.SourceName)
return -1;
if (a.SourceName > b.SourceName)
return 1;
return 0;
};
UIManager.clearPage(_T('Plugins'),_T("Plugins"),UIManager.oneColumnLayout);
function _getScriptFileList(controller,devicetype) {
var dtdb = MultiBox.getDeviceTypesDB(controller);
var dt = dtdb[devicetype];
var scripts = {};
$.each(dt,function(idx,ui_static_data){
if ( ui_static_data && ui_static_data.Tabs )
{
$.each( ui_static_data.Tabs, function( idx,tab) {
if (tab.TabType=="javascript" && tab.ScriptName!="shared.js")
{
var script = tab.ScriptName;
var func = tab.Function;
if (scripts[script] == undefined)
scripts[script]=[];
scripts[script].push( func );
}
});
}
});
return scripts;
};
function _getFileButton(plugin) {
var html = "";
html +="
";
html +=" ".format(plugin.id);
html += (_T("Files")+" ");
html +=" ";
html +=" ";
html +="
";
// var filebutton = smallbuttonTemplate.format( plugin.id, 'altui-plugin-icon altui-plugin-files', glyphTemplate.format("file","Files",""));
return html;
};
var pluginTemplate = "
{6} {0} {1}.{2} {7} {3} {4} {5} {8} ";
function drawPlugin(idx, plugin) {
var iconTemplate = "
";
var filebutton = _getFileButton(plugin);
var helpbutton = smallbuttonTemplate.format( plugin.altuiid, 'altui-plugin-icon altui-plugin-question-sign', glyphTemplate.format("question-sign","Help",""), "Help");
var infobutton = smallbuttonTemplate.format( plugin.altuiid, 'altui-plugin-icon altui-plugin-info-sign', glyphTemplate.format("info-sign","Information",""), "Info");
var updatebutton = smallbuttonTemplate.format( plugin.altuiid, 'altui-plugin-icon altui-plugin-update', glyphTemplate.format("retweet","Update Now",""), "Update");
var deletebutton = smallbuttonTemplate.format( plugin.altuiid, 'altui-plugin-icon altui-plugin-uninstall', glyphTemplate.format("remove","Uninstall",""), "Uninstall");
var inputbox = "
".format( plugin.altuiid,_T("Version number or empty for latest official version"));
var pluginTxt = pluginTemplate.format(
plugin.Title,
plugin.VersionMajor,
plugin.VersionMinor,
helpbutton,
infobutton,
inputbox+updatebutton,
iconTemplate.format(plugin.Icon),
filebutton,
deletebutton
);
$(".altui-mainpanel tbody").append(pluginTxt);
$("button#"+plugin.altuiid+".altui-plugin-question-sign").data("url",plugin.Instructions);
};
function endDrawPlugin() {
// adding manually installed plugin
var devices = MultiBox.getDevicesSync();
var manual_plugins={};
// first aggregate to find manually installed plugin
$.each( $.grep(devices,function(d){ return d.id_parent==0 && d.plugin==undefined}) , function(i,d) {
var controller = MultiBox.controllerOf(d.altuiid).controller;
manual_plugins[d.device_file] = {
devtype : d.device_type,
files : [],
devaltuiid : d.altuiid
};
$.each( [d.device_file,d.device_json,d.impl_file], function(i,filename) {
if (filename && filename !="")
manual_plugins[d.device_file].files.push( {SourceName:filename} );
});
if (!d.device_json) {
// try to get it from the .xml file
FileDB.getFileContent(controller,d.device_file , function( str ) {
var re = /
(.*)<\/staticJson>/;
var m;
if ((m = re.exec(str)) !== null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
manual_plugins[d.device_file].files.push( {SourceName:m[1]} );
}
});
}
});
// for each, create a virtual plugin structure so we can display
$.each(manual_plugins, function( key,value) {
// add also the JS files used for the tabs for such device type
var controller = MultiBox.controllerOf(value.devaltuiid).controller;
var scripts = _getScriptFileList( controller,value.devtype );
$.each(scripts, function(key,script) {
value.files.push({SourceName:key});
});
var plugin = {
id:-1,
altuiid: value.devaltuiid, // put the id of the device requesting this file, so that we know the "controller"
Files: value.files
};
var pluginTxt = pluginTemplate.format(
key,
"?",
"",
"",
"",
"",
" ",
_getFileButton(plugin),
""
);
$(".altui-mainpanel tbody").append(pluginTxt);
});
$(".altui-plugin-question-sign").click(function() {
var url = $(this).data("url");
window.open( url, '_blank');
});
$(".altui-plugin-info-sign").click(function() {
var altuiid = $(this).prop("id");
var pluginid = altuiid.split("-")[1];
window.open("http://apps.mios.com/plugin.php?id="+pluginid, '_blank');
});
$(".altui-plugin-file").click(function() {
var altuiid = $(this).data("plugin");
var info = MultiBox.controllerOf(altuiid);
var name = $(this).text();
FileDB.getFileContent(info.controller,name , function( txt ) {
var url = MultiBox.buildUPnPGetFileUrl(altuiid,name);
UIManager.pageEditor(name,txt,"Download",function(txt) {
$(".altui-mainpanel a[download]")[0].click();
});
$(".altui-mainpanel").prepend("");
});
});
$(".altui-plugin-update").click(function() {
var id = $(this).prop("id");
if (id==undefined) return;
DialogManager.confirmDialog(_T("are you sure you want to update plugin #{0}").format(id),function(result) {
if (result==true) {
var val = $("#altui-plugin-version-"+id).val();
if ($.isNumeric(val)==true) {
MultiBox.updatePluginVersion(id,val,function(result) {
PageMessage.message( _T("Update Plugin succeeded, be patient Luup will reload"), "success");
// alert(result);
});
}
else
MultiBox.updatePlugin(id,function(result) {
PageMessage.message( _T("Update Plugin succeeded, be patient Luup will reload"), "success");
// alert(result);
});
}
});
});
$(".altui-plugin-uninstall").click(function() {
var id = $(this).prop("id");
if (id==undefined) return;
DialogManager.confirmDialog(_T("Are you sure you want to uninstall this plugin #{0} and all its created devices").format(id),function(result) {
if (result==true) {
MultiBox.deletePlugin(id,function(result) {
alert(result);
});
}
});
});
};
$(".altui-mainpanel").append($(""+_T("Name")+" "+_T("Version")+" "+_T("Files")+" Actions "+_T("Update")+" "+_T("Uninstall")+"
"));
MultiBox.getPlugins( drawPlugin , endDrawPlugin);
},
pageTriggers: function()
{
UIManager.clearPage(_T('Triggers'),_T('Triggers'),UIManager.oneColumnLayout);
$(".altui-mainpanel").empty();
var bFirst=true;
var bBody=false;
var arr = [];
MultiBox.getScenes( null , function(s) {return s.triggers!=null}, function(scenes) {
$.each(scenes, function(idx,scene) {
var controller = MultiBox.controllerOf(scene.altuiid).controller;
var triggers = $.grep(scene.triggers,function(t) { return t.last_run!=undefined});
$.each(triggers, function(idx,trigger) {
var triggerinfo = _formatTrigger(controller,trigger);
arr.push( {
lastrun: triggerinfo.lastrun,
scene: scene.name,
trigger: triggerinfo.name,
device: triggerinfo.device,
condition: "{0} {1}".format(triggerinfo.descr,triggerinfo.condition),
id: scene.altuiid+"-"+idx,
lua : trigger.lua || ""
})
});
var sceneWatches = WatchManager.getSceneWatches(scene);
if (sceneWatches) {
$.each(sceneWatches,function(idx,w){
var device = MultiBox.getDeviceByAltuiID(w.deviceid);
arr.push( {
lastrun: scene.last_run ? _toIso(new Date(scene.last_run*1000)," ") : "",
scene: scene.name,
trigger: w.service,
device: device.name,
condition: 'watch '+w.variable,
id: scene.altuiid+"-"+idx,
lua : w.luaexpr
})
});
}
});
})
var viscols = MyLocalStorage.getSettings("TriggersVisibleCols") || [];
if (viscols.length==0)
viscols = [ 'lastrun','scene','trigger','device','condition','id','lua'];
var options = (MyLocalStorage.getSettings('ShowAllRows')==1) ? {rowCount:-1 } : {};
$(".altui-mainpanel").append( _array2Table(arr,'id',viscols) );
$("#altui-grid").bootgrid(
$.extend({
caseSensitive: false,
statusMapping: {}
},options)
).bootgrid("sort",{
lastrun:"desc"
})
.on("loaded.rs.jquery.bootgrid", function (e) {
var settings = $("#altui-grid").bootgrid("getColumnSettings");
viscols = $.map($.grep(settings, function (obj) { return obj.visible == true }),function(obj){ return obj.id;});
MyLocalStorage.setSettings("TriggersVisibleCols",viscols);
/* your code goes here */
});
},
pageUsePages: function ()
{
// var pages = g_CustomPages;
// PageManager.init(g_CustomPages);
UIManager.clearPage(_T('Custom Pages'),"",UIManager.oneColumnLayout);
// lean layout if requested
if ( getQueryStringValue("layout") == 'lean') {
$("#altui-pagemessage").remove();
$(".navbar-fixed-top").remove();
$(".container-fluid").css("margin-top","-60px");
$(".container-fluid").find(".col-xs-12").first().removeClass('col-sm-push-1').removeClass('col-sm-10');
}
// $("#altui-pagetitle").text("Your Custom Pages");
var pageTabs = _createPageTabsHtml();
var Html = "";
PageManager.forEachPage( function( idx, page) {
Html += _getPageHtml(page,false) // no edit mode
});
Html += "
";
$(".altui-mainpanel").html( ""+pageTabs + Html +"
");
$('#altui-page-tabs a:first').tab('show');
_updateDynamicDisplayTools( false );
},
pageEditPages: function ()
{
function _pagePageProperty(pagename) {
var propertyline = "";
var page = PageManager.getPageFromName(pagename);
var pageAttributes = [
{ key:'name', label:'Name', placeholder:'enter name' },
{ key:'background', label:'CSS Background', placeholder:'enter css string' , helptext:'any css3 valid background property'}
];
$.each( pageAttributes , function(idx,attributes) {
var htmlid = 'altui-page-'+attributes.key;
propertyline += "";
});
var dialog = DialogManager.registerDialog('dialogModal',
defaultDialogModalTemplate.format(
'Page Properties', // title
"", // body
"modal-lg" // size
));
DialogManager.dlgAddDialogButton($('div#dialogModal'), true, _T("Save Changes"));
// buttons
$('div#dialogModal button.btn-primary').off('click');
$('div#dialogModal button.btn-primary').on( 'click', function() {
$.each( pageAttributes , function(idx,attributes) {
var htmlid = 'altui-page-'+attributes.key;
page[ attributes.key ] = $("#"+htmlid).val();
});
$('div#dialogModal').modal('hide');
_displayPages();
});
$('div#dialogModal').modal();
};
// var pages = g_CustomPages;
// PageManager.init(g_CustomPages);
function _createPageEditorHtml() {
var pageTabs = _createPageTabsHtml( true ); // edit mode
var Html = "";
PageManager.forEachPage( function( idx, page) {
Html += _getPageHtml(page, true) // edit mode
});
Html += "
";
return ""+pageTabs + Html+"
";
};
function _createToolboxHtml() {
function _createToolHtml(tool) {
var html="";
html += ("{2}
").format(tool.cls,tool.id,tool.html);
return html;
};
var lines = new Array();
$.each(tools , function(idx,tool) {
lines.push( ""+_createToolHtml(tool)+"
" );
});
var editBoxTemplate = "";
var editBoxLines = new Array();
$.each(edittools , function(idx,tool) {
var glyph = glyphTemplate.format( tool.glyph, tool.glyph,"" );
editBoxLines.push(""+glyph+"
");
});
lines.push(editBoxTemplate.format( editBoxLines.join('') ) );
lines.push( "" );
return lines.join('');
};
function _displayPages() {
var pageEditorHtml = _createPageEditorHtml();
$(".altui-mainpanel").html( pageEditorHtml );
$('#altui-page-tabs a:first').tab('show');
_updateDynamicDisplayTools( true ); //edit mode
// make all reloaded children draggable
$(".altui-mainpanel .altui-widget")
.draggable( _widgetOnCanvasDraggableOptions() ) // for all pages
// add resizable & gauges
$.each(tools, function(idx,tool){
if ($.isFunction( tool.onWidgetResize) ) {
// if (tool.resizable==true) {
$(".altui-custompage-canvas ."+tool.cls).resizable(
_widgetOnCanvasResizableOptions(tool)
);
}
});
// make all pages droppable
$(".altui-custompage-canvas")
.selectable()
.droppable({
accept: ".altui-widget",
tolerance: "fit",
drop: function(event, ui) {
var pagename = _getActivePageName();
var page = PageManager.getPageFromName( pagename );
var parent = $(this);
var dropped = ui.helper; // clone
var type = ui.helper.data( "type" ); // data-type attr
var tool = _getToolByClass( type );
var position = ui.helper.position();
var size = { width:ui.helper.width(), height:ui.helper.height() };
var widgetid = 0;
if ( $(parent)[0] === $(ui.helper.parent())[0] )
{
// internal drag and drop on the page canvas
widgetid = $(ui.helper).prop('id');
if ($.isFunction( tool.onWidgetResize) ) {
(tool.onWidgetResize)(page, widgetid, position, size);
PageManager.updateChildrenInPage( page, widgetid, position, size );
}
else
PageManager.updateChildrenInPage( page, widgetid, position );
_showSavePageNeeded(true);
// save also all selected items which moved as well as part of the drag and drop
var selected = $(_getPageSelector( page )).find(".altui-widget.ui-selected").not("#"+ui.helper.prop('id'));
$.each(selected, function (idx,elem) {
widgetid = $(elem).prop('id');
PageManager.updateChildrenInPage( page, widgetid, $(elem).position() , $(elem).size() );
_showSavePageNeeded(true);
});
}
else
{
var parentoffset = $(this).offset();
position = {
top: Math.round(ui.offset.top - parentoffset.top),
left: Math.round(ui.offset.left - parentoffset.left)
};
// adding from the toolbox
widgetid = PageManager.insertChildrenInPage( page, tool, position);
_showSavePageNeeded(true);
var widget=PageManager.getWidgetByID( page, widgetid );
var html = _getWidgetHtml( widget , true); // edit mode
var obj = $(html)
.appendTo(parent)
.draggable( _widgetOnCanvasDraggableOptions(page) );
if ($.isFunction( tool.onWidgetResize) )
{
obj.resizable(
_widgetOnCanvasResizableOptions(tool)
);
}
if ($.isFunction( tool.onWidgetDisplay) )
{
(tool.onWidgetDisplay)(page,widgetid, true); // edit mode
}
}
}
})
};
// draw page & toolbox
UIManager.clearPage(_T('Edit Pages'),_T("Custom Pages Editor"),UIManager.twoColumnLayout);
PageMessage.message(_T("Drag and Drop to add/move/delete controls. use Ctrl+Click or lasso to select multiple controls"),"info");
// Get and draw the HTML areas
var toolboxHtml = _createToolboxHtml();
$(".altui-leftnav").append( toolboxHtml );
_displayPages();
// User interactivity
$(".altui-widget-delete").droppable({
accept: ".altui-widget",
tolerance: "pointer",
drop: function(event, ui) {
var pagename = _getActivePageName();
var page = PageManager.getPageFromName( pagename );
var dropped = ui.helper; // clone
if ( $(dropped).parents(".altui-leftnav").length==0 ) { // not from toolbox
var selected = $(_getPageSelector( page )).find(".altui-widget.ui-selected").not("#"+ui.helper.prop('id'));
selected.each( function(idx,elem)
{
PageManager.removeChildrenInPage( page, $(elem).prop('id') );
$(elem).remove();
});
PageManager.removeChildrenInPage( page, dropped.prop('id') );
_showSavePageNeeded(true);
ui.draggable.remove();
}
// var type = ui.helper.data( "type" ); // data-type attr
}
});
$(".altui-leftnav .altui-widget").draggable({
// containment: ".altui-custompage-canvas",
grid: [ 5,5 ],
helper: "clone",
cursorAt: { left: 5 },
// snap: true,
// snapMode: "inner",
// snapTolerance: 20,
revert: "invalid"
});
// call backs
$(".altui-edittools").click( function () {
var id = $(this).prop('id');
$.each(edittools, function(idx,tool){
if (tool.glyph == id) {
// update on HTML page
var page = PageManager.getPageFromName( _getActivePageName() );
var selected = $( _getPageSelector( page ) ).find(".altui-widget.ui-selected");
(tool.onclick)( selected );
// update the children position for each selected children
$.each(selected, function (idx,elem) {
var widgetid = $(elem).prop('id');
PageManager.updateChildrenInPage( page, widgetid, $(elem).position() , $(elem).size() );
_showSavePageNeeded(true);
});
}
})
});
// $(".altui-mainpanel").off("click",".altui-widget");
$(".altui-mainpanel").on("click",".altui-widget",function(event){
if (event.ctrlKey == false ) {
$(".altui-widget").removeClass("ui-selected");
var pagename = _getActivePageName();
var page = PageManager.getPageFromName( pagename );
var cls = $(this).data( "type" );
var tool = _getToolByClass( cls );
var widgetid = $(this).prop('id');
var widget=PageManager.getWidgetByID( page, widgetid );
// apply defaults
widget.properties = $.extend(true,{}, tool.properties, widget.properties);
(tool.property)( widget );
}
else
$(this).toggleClass("ui-selected");
});
// $(".altui-mainpanel").off("click","#altui-page-action-delete");
$(".altui-mainpanel").on("click","#altui-page-action-delete",function(){
// find active page
PageManager.deletePage( _getActivePageName() );
_displayPages();
});
// $(".altui-mainpanel").off("click","#altui-page-action-new");
$(".altui-mainpanel").on("click","#altui-page-action-new",function(){
// find active page
var name = PageManager.addPage( );
_displayPages();
});
// $(".altui-mainpanel").off("click","#altui-page-action-save");
$(".altui-mainpanel").on("click","#altui-page-action-save",function(){
// find active page
PageManager.savePages( );
_showSavePageNeeded(false);
});
// $(".altui-mainpanel").off("click","#altui-page-action-properties");
$(".altui-mainpanel").on("click","#altui-page-action-properties",function(){
// find active page
_pagePageProperty( _getActivePageName() );
});
},
pageWip: function ()
{
UIManager.clearPage(_T('Wip'),_T("Work In Progress"));
$(".altui-mainpanel").append("Sorry this is not yet implemented ");
},
getPayPalButtonHtml: function( bIncludeImg )
{
var html="";
html +="";
return html;
},
pageCredits: function ()
{
UIManager.clearPage(_T('Credits'),_T("Credits"),UIManager.twoColumnLayout);
$("#altui-pagemessage").remove();
var tbl = [
["GetVera","http://getvera.com/","the zWave Getaway and backend platform"],
["Bootstrap","http://getbootstrap.com/","set of css and javascript components for responsive design user interfaces"],
["jQuery","http://jquery.com/","javascript framework and browser differences abstraction layer"],
["jQueryUI","http://jqueryui.com/","jQuery User Interface widgets ( like slider )"],
["Touch Punch","http://touchpunch.furf.com/","jQuery UI fix for touch screen devices"],
["Bootstrap Validator","https://github.com/1000hz/bootstrap-validator","Form validator in Bootstrap 3 style"],
["D3js","http://d3js.org/","D3 Data Driven Documents & Les Miserables tutorial"],
["Bootgrid","http://www.jquery-bootgrid.com/","Jquery Bootstrap Grid"],
["Blockly","https://developers.google.com/blockly/","Blockly Library"],
["Bootswatch","https://bootswatch.com/","Bootstrap Themes"],
["ThingSpeak","https://thingspeak.com/","ThingSpeak Data platform for IoT"],
["jQuery Colorpicker","http://bgrins.github.io/spectrum/","Spectrum Color Picker"],
["proto io","https://proto.io/freebies/onoff/","switch button"],
["Bootstrap Multiselect","http://davidstutz.github.io/bootstrap-multiselect/","Bootstrap based Multiselect control"],
["amg0","http://forum.micasaverde.com/","reachable as amg0 on this forum "]
];
var html = "";
html += ""
html += "";
// Section 1
$.each(tbl, function (idx,line) {
html += "{1} ".format(line[0].replace(' ','_'),line[0])
});
html += " "
html += " "
$(".altui-leftnav").append( html );
html = "";
html += "";
$.each(tbl, function (idx,line) {
html +="{1} ".format(line[0].replace(' ','_'),line[0]);
html +="{0} ({1} ) ".format(line[2],line[1]);
});
html +=" ";
html +="For those who really like this plugin and feel like it, you can donate what you want here on Paypal. It will not buy you more support not any garantee that this can be maintained or evolve in the future but if you want to show you are happy and would like my kids to transform some of the time I steal from them into some concrete returns, please feel very free ( and absolutely not forced to ) to donate whatever you want. thank you !
";
// html += UIManager.getPayPalButtonHtml( true );
html +=" ";
html += UIManager.getPayPalButtonHtml(false);
$(".altui-mainpanel").append(html);
$(".altui-leftnav a").on('click', function(e) {
// prevent default anchor click behavior
e.preventDefault();
// store hash
var hash = $(this).attr("href");
// animate
$('html, body').animate({
scrollTop: $(hash).offset().top - $('.navbar-fixed-top').height()
}, 300, function(){
// when done, add hash to url
// (default click behaviour)
window.location.hash = hash;
});
// Highlight
$("dt").removeClass("bg-warning");
$(hash).addClass("bg-warning");
});
},
pageEditorForm: function (title,txt,outputarea,button,onClickCB) {
var html = "";
html +="";
$(".altui-mainpanel").append(html);
$("#altui-copyresult-clipboard").click( function() {
Altui_SelectText( "altui-editor-result" );
document.execCommand('copy');
});
$("#altui-copyoutput-clipboard").click( function() {
Altui_SelectText( "altui-editor-output" );
document.execCommand('copy');
});
$("#altui-luaform-button").click( function() {
var txt = $("textarea#altui-editor-text").val();
onClickCB(txt,$(this));
});
},
pageEditor: function (filename,txt,button,cbfunc)
{
UIManager.clearPage(_T('Editor'), filename,UIManager.oneColumnLayout);
$(".altui-mainpanel").append("
");
UIManager.pageEditorForm(filename,txt,null,button,function(newtxt) {
if ($.isFunction(cbfunc))
cbfunc(newtxt);
});
},
pageLuaTest: function ()
{
UIManager.clearPage(_T('LuaTest'),_T("LUA Code Test"),UIManager.oneColumnLayout);
$(".altui-mainpanel").append(""+_T("This test code will succeed if it is syntactically correct. It must be the body of a function and can return something. The return object and console output will be displayed)")+"
");
var lastOne = MyLocalStorage.getSettings("LastOne_LuaTest") || "return true";
UIManager.pageEditorForm("Lua Test Code",lastOne,true,_T("Submit"),function(lua) {
MyLocalStorage.setSettings("LastOne_LuaTest",lua);
MultiBox.runLua(0,lua, function(res) {
res = $.extend({success:false, result:"",output:""},res);
$("#altui-editor-result").text(res.result);
$("#altui-editor-output").text(res.output);
if ( res.success ==true )
PageMessage.message( _T("Code execution succeeded"), "success");
else
PageMessage.message( _T("Code execution failed"), "danger");
});
});
},
pageOsCommand: function ()
{
var defaultCommands = [
{label:_T("Disk Usage"), command:'du -h' },
{label:_T("Free Space"), command:'df -h' },
{label:_T("Plugin Files"), command:'ls -l /etc/cmh-ludl' },
{label:_T("Log Sizes"), command:'ls -l /var/log/cmh' },
{label:_T("Search Logs"), command:"cat /var/log/cmh/LuaUPnP.log | grep '{0}'" },
{label:_T("Tail Logs"), command:"tail -n 50 /var/log/cmh/LuaUPnP.log" },
{label:_T("Find Json"), command:"find / -name *json*.lua" }
];
var commands = MyLocalStorage.getSettings("OsCommands") || defaultCommands;
var actions = [
{ name:'delete', glyph:deleteGlyph }
];
function _drawFrequentCommandBar(commands) {
var html="";
html+=" ";
return html;
};
function _drawCommandTable(commands) {
var html="";
html+= "";
html+= " ";
html+= " ";
html+= ""+_T("Actions")+" ";
$.each(defaultCommands[0] ,function(key,val) {
html+= ""+_T(key)+" ";
})
html+= " ";
html+= " ";
html+= " ";
$.each(commands,function(idxcmd,cmd) {
html+= "";
html+= "";
$.each(actions,function(idxaction,action) {
html += smallbuttonTemplate.format( idxcmd, 'altui-oscommand-configtbl-action-'+action.name, action.glyph ,action.name);
});
html+= " ";
$.each(cmd,function(key,val) {
html+= ""+val+" ";
})
html+= " ";
})
html+= "";
html+= "";
html += smallbuttonTemplate.format( commands.length, 'altui-oscommand-configtbl-action-add', plusGlyph ,_T('Add') );
html+= " ";
$.each(defaultCommands[0],function(key,val) {
html+= ""+" "+" ";
})
html+= " ";
html+= "";
html+= "";
html += smallbuttonTemplate.format( commands.length, 'altui-oscommand-configtbl-action-reset', refreshGlyph ,_T('Default') );
html+= " ";
html+= " ";
html+= " ";
html+= "
";
return html;
};
function _replaceANSI(str) {
var re = /\[33;1m(.*)\[0m/g;
var subst = '$1 ';
str = str.replace(re, subst);
re = /\[35;1m(.*)\[0m/g;
subst = '$1 ';
str = str.replace(re, subst);
re = /\[31;1m(.*)\[0m/g;
subst = '$1 ';
str = str.replace(re, subst);
re = /\[36;1m(.*)\[0m/g;
subst = '$1 ';
str = str.replace(re, subst);
return str;
};
UIManager.clearPage(_T('OsCommand'),_T("OS Command"),UIManager.oneColumnLayout);
var editButtonHtml = buttonTemplate.format( 'altui-editoscmd-0', 'altui-editoscmd', editGlyph,'default',"");
var html = "";
html+="";
html+= ""+_T("Enter a Vera OS ( Unix ) command, the stdout will be returned and displayed below")+"
";
html += _drawFrequentCommandBar(commands);
html += _createControllerSelect('altui-controller-select');
html+=" ";
html+=" "+_T("OS Command")+" ";
html+=" ";
html+="
";
html+=" ";
html+="
"+_T("Run")+" ";
html+="
";
html+="
"+_T("Output")+" ";
html+="
";
html+="
";
$(".altui-mainpanel").append( html );
$(".altui-mainpanel").on("click",".altui-oscommand-button",function(e){
// e.stopPropagation();
var val = $(this).data("cmd");
$("#oscommand").val( val );
setTimeout( function() { $("#altui-oscommand-exec-button").click() } ,100 );
});
$(".altui-mainpanel").on("click","#altui-oscommand-exec-button",function(e){
function _execCmd(cmd) {
show_loading();
MultiBox.osCommand( parseInt($("#altui-controller-select").val()), oscmd, function(res) {
hide_loading();
var html = $(" ").text(res.result).html(); // escape html
$('#altui-oscommand-result').html( (res.success==true) ? _replaceANSI(html) : _T("failed to execute"));
});
};
var oscmd = $("#oscommand").val();
if (oscmd.indexOf("{0}") > -1) {
var dialog = DialogManager.registerDialog('dialogModal',
defaultDialogModalTemplate.format(
_T('Command Parameters'), // title
" ", // body
"modal-lg" // size
));
var lastOne = MyLocalStorage.getSettings("LastOne_"+'param0') || "";
DialogManager.dlgAddLine(dialog, 'param0', _T('Parameter'), lastOne,"", {required:''} );
DialogManager.dlgAddDialogButton(dialog, true, _T("Run"));
$('div#dialogModal').modal();
$('div#dialogs')
.off('submit',"div#dialogModal")
.on( 'submit',"div#dialogModal", function() {
$('div#dialogModal').modal('hide');
var val = $("#altui-widget-param0").val();
MyLocalStorage.setSettings("LastOne_"+'param0'+name,val);
oscmd = oscmd.format( val );
$("#oscommand").val( oscmd );
setTimeout(function() {
_execCmd(oscmd);
}, 300 );
});
}
else
_execCmd(oscmd);
});
// SHOW EDIT TABLE
$(".altui-mainpanel").on("click",".altui-editoscmd",function(e){
if ( $(".altui-oscommand-configtbl").length == 0 ) {
$("#altui-frequent-commands-bar").after( _drawCommandTable(commands) );
}
else {
$(".altui-oscommand-configtbl").remove();
}
});
// DELETE
$(".altui-mainpanel").on("click",".altui-oscommand-configtbl-action-delete",function(e){
//delete command
var index = $(this).prop('id');
commands.splice(index,1);
$("div#altui-frequent-commands-bar").replaceWith( _drawFrequentCommandBar(commands) );
$("table.altui-oscommand-configtbl").replaceWith( _drawCommandTable(commands) );
MyLocalStorage.setSettings("OsCommands",commands);
});
// ADD
$(".altui-mainpanel").on("click",".altui-oscommand-configtbl-action-add",function(e){
var tr = $(this).closest("tr");
var label =tr.find("input#label").val();
var command = tr.find("input#command").val();
if ( label && command ) {
commands.push( {label:label, command:command } );
$("div#altui-frequent-commands-bar").replaceWith( _drawFrequentCommandBar(commands) );
$("table.altui-oscommand-configtbl").replaceWith( _drawCommandTable(commands) );
MyLocalStorage.setSettings("OsCommands",commands);
}
});
// RESET
$(".altui-mainpanel").on("click",".altui-oscommand-configtbl-action-reset",function(e){
commands = cloneObject(defaultCommands);
$("div#altui-frequent-commands-bar").replaceWith( _drawFrequentCommandBar(commands) );
$("table.altui-oscommand-configtbl").replaceWith( _drawCommandTable(commands) );
MyLocalStorage.setSettings("OsCommands",commands);
});
},
pageLuaStart: function ()
{
function _prepareUI( ctrlid ) {
var lua = MultiBox.getLuaStartup(ctrlid );
UIManager.pageEditorForm("Lua Startup Code",lua,null,"Submit",function(newlua) {
if (newlua!=lua) {
DialogManager.confirmDialog(_T("do you want to change lua startup code ? if yes, it will generate a LUA reload, be patient..."),function(result) {
if (result==true) {
MultiBox.setStartupCode(ctrlid,newlua)
.done( function(){
PageMessage.message(_T("Lua Startup code has been modified"),"success");
})
.fail(function(){
PageMessage.message(_T("Lua Startup can only be modified on controller 0"),"danger");
});
}
});
}
});
}
UIManager.clearPage(_T('LuaStart'),_T("LUA Startup"),UIManager.oneColumnLayout);
// DOES NOT WORK on other ctrl as the url gets too long
$(".altui-mainpanel").append( _createControllerSelect('altui-controller-select'));
$("#altui-controller-select").change(function(){
$(".altui-editor-form").remove();
_prepareUI( parseInt($("#altui-controller-select").val()) );
});
_prepareUI( 0 );
},
pagePower: function()
{
UIManager.clearPage(_T('Power'),_T("Power Chart"),UIManager.oneColumnLayout);
// prepare and load D3 then draw the chart
$(".altui-mainpanel")
.append(
""
)
.append(" ");
var margin = {top: 10, right: 50, bottom: 10, left: 150},
width = $(".altui-mainpanel").innerWidth() - margin.left - margin.right-30,
barHeight = 20,
height = 0; // calculated later
function _processEnergyData(input)
{
// prepare data
var data = input.trim().split('\n');
$.each(data, function(i,line) {
data[i] = line.split('\t');
});
return data;
};
function _refreshPowerChart() {
if ($(".altui-energy-d3chart").length==0)
return; // stop refreshing
MultiBox.getPower( function(res) {
var data = _processEnergyData(res);
var x = d3.scale.linear()
.range([0, width])
.domain([0, d3.max(data, function(d) { return +d[4]; })]); // d[4] is watts and is text, must convert to int
var xAxis = d3.svg.axis()
.scale(x)
.orient("top");
var chart = d3.select(".altui-energy-d3chart");
chart.selectAll("g.device").data(data);
var t = chart.transition().duration(1000);
t.select(".axis").call(xAxis);
var bar = t.selectAll("g.device");
bar.select("text.wattage")
.attr("x", function(d) { return /*Math.max( x(d[4]) - 3, 10 );*/ x(d[4])-3 })
.attr("y", barHeight / 2)
.attr("dy", ".35em")
.attr("text-anchor","end")
.text(function(d) { return (parseInt(d[4])!=0) ? d[4] : ''; });
bar.select("rect")
.attr("width", function(d) { return x(d[4]); })
.attr("height", barHeight - 1);
setTimeout( _refreshPowerChart , 5000 );
});
};
function _drawPowerChart() {
if ($(".altui-energy-d3chart").length==0)
return; // stop refreshing
MultiBox.getPower( function(res) {
// prepare data
var data = _processEnergyData(res);
// async func to draw the chart
$(".altui-energy-d3chart").replaceWith(" ");
margin = {top: 10, right: 50, bottom: 10, left: 150};
width = $(".altui-mainpanel").innerWidth() - margin.left - margin.right-30;
barHeight = 20;
height = (1+data.length)*(barHeight +1);
var x = d3.scale.linear()
.range([0, width])
.domain([0, d3.max(data, function(d) { return +d[4]; })]); // d[4] is watts and is text, must convert to int
var xAxis = d3.svg.axis()
.scale(x)
.orient("top");
var chart = d3.select(".altui-energy-d3chart")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
chart.append("g")
.attr("class","axis")
.attr("transform", "translate(0,"+(barHeight-1)+")")
.call(xAxis);
chart.append("text")
.attr("x",-10)
.attr("y",barHeight / 2)
.attr("text-anchor","end")
.text("Watts");
var bar = chart.selectAll("g.device")
.data(data)
.enter()
.append("g")
.attr("class","device")
.attr("transform", function(d, i) { return "translate(0," + (i+1) * barHeight + ")"; });
bar.append("rect")
.attr("width", function(d) { return x(d[4]); })
.attr("height", barHeight - 1);
bar.append("text")
.attr("class","wattage")
.attr("x", function(d) { return /*Math.max( x(d[4]) - 3, 10 );*/ x(d[4])-3 })
.attr("y", barHeight / 2)
.attr("dy", ".35em")
.attr("text-anchor","end")
.text(function(d) { return (parseInt(d[4])!=0) ? d[4] : ''; });
bar.append("text")
.attr("class","name")
.attr("x", -5)
.attr("y", barHeight / 2)
.attr("dy", ".35em")
.attr("text-anchor","end")
.text(function(d) { return "{0}, #{1}".format(d[1],d[0]); });
setTimeout( _refreshPowerChart , 5000 );
});
}
UIManager.loadD3Script( _drawPowerChart );
},
pageZwave: function()
{
function _nodename(d) { return "{0}, #{1}".format(d.name, d.altuiid); }
function _commQuality(altuiid) {
//PollOk/(PollOk+PollNoReply)
var device = MultiBox.getDeviceByAltuiID(altuiid);
var service="urn:micasaverde-com:serviceId:ZWaveDevice1"
var PollNoReply = parseInt(MultiBox.getStatus(device,service,"PollNoReply"));
var PollOk = parseInt(MultiBox.getStatus(device,service,"PollOk"));
if (PollOk+PollNoReply>0)
return ( PollOk / (PollOk+PollNoReply) );
return 1;
};
function _countNeighbors(device) {
var n=0;
$.each( device.states, function(i,s) {
if (s.variable=="Neighbors") {
n = s.value.split(',').length;
return false;
}
});
return n;
};
function _NeighborsOf(device) {
var result = [];
var controllerid = MultiBox.controllerOf(device.altuiid).controller;
$.each( device.states, function(i,s) {
if (s.variable=="Neighbors") {
result = s.value.split(',');
$.each(result, function(i,r) {
var device = MultiBox.getDeviceByAltID( controllerid, 1, r ); // 1=zWave controller, r=altid
result[i] = (device) ? device.altuiid : null;
});
return false;
}
})
return result;
};
var width=0, height=0, chart=null, orders=null;
var data = $.grep( MultiBox.getDevicesSync() , function(d) {return /*(MultiBox.controllerOf(d.altuiid).controller==0) &&*/ (d.id_parent==1);} );
orders = {
id:$.map( data.sort(function(a, b){return parseInt(a.id)-parseInt(b.id)}), function(d) { return d.altuiid; }),
name: $.map( data.sort( sortByName ), function(d) { return d.altuiid; }),
mesh:$.map( data.sort(function(a, b){return _countNeighbors(b)-_countNeighbors(a)}), function(d) { return d.altuiid; })
};
UIManager.clearPage(_T('ZWave'),_T("zWave Network"),UIManager.oneColumnLayout);
// $("div#dialogs").append(deviceModalTemplate.format( '', '', 0 ));
DialogManager.registerDialog('deviceModal',deviceModalTemplate.format( '', '', 0 ));
var html = "";
html += "";
html += "";
html += ""+_T("Order By")+": ";
html += "";
html += "ID ";
html += ""+_T("Name")+" ";
html += ""+_T("Mesh")+" ";
html += " ";
html += "
";
html += (""+_T("Reset Poll Counters")+" ");
html += " ";
html += "";
html += " ";
html += "
";
$(".altui-mainpanel")
.append(html)
.append(
""
);
function _drawChart( chart, width, height, orderby ) {
var x = d3.scale.ordinal()
.domain( orders[orderby] )
.rangeBands([0, width]);
var y = d3.scale.ordinal()
.domain( orders[orderby] )
.rangeBands([0, height]);
var c = d3.scale.quantize()
.domain( [0,1] )
.range(["red","orange","yellow","yellowgreen","green"]);
var row = chart.selectAll(".ligne").data(data);
row.enter()
.append("g")
.attr("class","ligne")
.attr("transform",function(d,i) { return "translate(0,"+y(d.altuiid)+")"; } )
.append("text")
.attr("x", -6)
.attr("y", x.rangeBand() / 2)
.attr("dy", ".32em")
.attr("text-anchor", "end")
.text(function(d) { return _nodename(d); })
.on("mouseover", function(p) {
d3.select(this).classed("active", true);
})
.on("mouseout", function(p) {
d3.select(this).classed("active", false);
})
.on('click',function(d,i) {
var device = MultiBox.getDeviceByAltuiID(d.altuiid);
UIManager.deviceDrawVariables(device);
});
row.append("line")
.attr("x2", width);
row.exit()
.remove();
var cell = row.selectAll(".cellule")
.data( function(d) {
return _NeighborsOf(d);
} );
cell.enter()
.append("rect")
.attr("class","cellule")
.attr("x", function(d) {
return x(d);
// return x(d.id);
} )
.attr("width",x.rangeBand())
.attr("height",y.rangeBand())
// .style("fill",c(_commQuality(d)))
.style("fill",function(d) {
return c(_commQuality(d3.select(this.parentNode).datum().altuiid));
})
.on("mouseover", function(p) {
var lignedatum = d3.select(this.parentNode).datum();
d3.selectAll(".ligne text").classed("active", function(d, i) { return d.altuiid == lignedatum.altuiid; });
d3.selectAll(".colonne text").classed("active", function(d, i) { return d.altuiid == p; });
})
.on("mouseout", function(p) {
d3.selectAll("text").classed("active", false);
})
.on('click',function(d,i) {
var lignedatum = d3.select(this.parentNode).datum();
var device = MultiBox.getDeviceByAltuiID(lignedatum.altuiid);
UIManager.deviceDrawVariables(device);
});
cell.exit()
.remove();
var col = chart.selectAll(".colonne").data(data);
col.enter()
.append("g")
.attr("class","colonne")
.attr("transform",function(d,i) { return "translate("+x(d.altuiid)+",0) rotate(-90)"; } )
.append("text")
.attr("x", 6)
.attr("y", x.rangeBand() / 2)
.attr("dy", ".32em")
.attr("text-anchor", "start")
.text(function(d) { return _nodename(d); });
col.append("line")
.attr("x1", -width);
col.exit().remove();
};
function _drawzWavechart()
{
$(".d3chart").replaceWith(" ");
var available_height = $(window).height() - $("#altui-pagemessage").outerHeight() - $("#altui-pagetitle").outerHeight() - $("#altui-zwavechart-order").outerHeight() - $("footer").outerHeight();
var margin = {top: 150, right: 10, bottom: 10, left: 150};
width = $(".altui-zwavechart-container").innerWidth() - margin.left - margin.right-30;
height = Math.min(width,available_height - margin.top - margin.bottom);
if (width \
.altui-route-d3chart-container {\
} \
.node { \
} \
.node circle { \
stroke: #fff; \
stroke-width: 1.5px; \
} \
.node text { \
fill: gray; \
pointer-events: none; \
font-size: 10px; \
} \
.link { \
stroke-opacity: .8; \
fill: none; \
} \
" )
.append("
")
var available_height = $(window).height() - $("#altui-pagemessage").outerHeight() - $("#altui-pagetitle").outerHeight() - $("#altui-zwavechart-order").outerHeight() - $("footer").outerHeight();
width = $(".altui-route-d3chart-container").innerWidth() - margin.left - margin.right;
height = Math.max(300,Math.min(width,available_height - margin.top - margin.bottom));
UIManager.loadD3Script( function() {
MultiBox.getDevices(null,function(d) { return MultiBox.controllerOf(d.altuiid).controller==parseInt($("#altui-controller-select").val()); },function(arr) {
devices = arr;
_drawChart();
})
});
},
pageChildren: function() {
var height = null, width = null;
var data = { root:[], nodes:[] , links:[] };
var devices = null;
// Returns a list of all nodes under the root.
function _flatten(root) {
var nodes = [], i = 0;
function recurse(node) {
if (node.children) node.children.forEach(recurse);
// if (!node.id) node.id = ++i;
nodes.push(node);
}
recurse(root);
return nodes;
};
function _findNode( root, id ) {
var found=null;
if (root.id == id )
return root;
if (root.children)
$.each( root.children, function (i,n) {
found = _findNode( n, id );
return ( found==null );
});
return found;
};
function _addChildrenFromWaitList( node) {
// search in wait list
var children=[]
// console.log("searching wait list for childs of {0}".format(node.id));
for ( var i = data.wait.length-1; i>=0 ; i--) {
if (data.wait[i].id_parent == node.id) {
var child = data.wait.splice(i,1)[0];
// console.log("found node :"+child.id);
node.children.push(child);
children.push(child);
}
}
$.each(children, function(i,child) {
_addChildrenFromWaitList( child);
});
};
function _addNode( node ) {
var parent = _findNode( data.root, node.id_parent );
if (parent==null){
// console.log("could not find parent, putting in wait list");
data.wait.push(node);
return;
}
parent.children.push( node );
_addChildrenFromWaitList(node);
};
function _prepareDataParents( ) {
data = { root:[], nodes:[] , links:[] , wait:[] };
var color = { "ctrl": 0 };
var nColor = 1;
// var devices = $.grep( MultiBox.getDevicesSync() , function(d) {return (MultiBox.controllerOf(d.altuiid).controller==0) } );
data.root={ id:"0-0", name:"Main Controller", color:color["ctrl"], children:[] };
$.each( MultiBox.getControllers(), function (idx,c) {
if (idx>0) {
_addNode({
id:"{0}-{1}".format(idx,0),
name:"Controller "+c.ip,
color:color["ctrl"] ,
id_parent: "0-0",
children: []
});
}
});
if (devices) {
$.each( devices /*.sort(function(a, b){return parseInt(a.id)-parseInt(b.id)})*/, function( idx,device ) {
if (color[device.device_type]==undefined)
color[device.device_type]=nColor++;
var controllerid = MultiBox.controllerOf(device.altuiid).controller;
// console.log("device {0},{1} id_parent:{2}-{3}".format(device.name, device.altuiid,controllerid,device.id_parent));
_addNode({
id:device.altuiid,
name:device.name+", "+device.altuiid,
color:color[device.device_type] ,
id_parent: "{0}-{1}".format(controllerid,device.id_parent || 0),
children: []
});
});
// $.each(data.wait, function(i, node) {
// console.log( node.id );
// });
}
return data;
};
function _drawChartParents() {
function _updateDataParents( ) {
data.nodes = _flatten(data.root);
data.links = d3.layout.tree().links(data.nodes);
};
$(".altui-children-d3chart").replaceWith(" ");
var available_height = $(window).height() - $("#altui-pagemessage").outerHeight() - $("#altui-pagetitle").outerHeight() - $("#altui-zwavechart-order").outerHeight() - $("footer").outerHeight();
var margin = {top: 20, right: 10, bottom: 10, left: 20};
width = $(".altui-children-d3chart-container").innerWidth() - margin.left - margin.right-30;
height = Math.max(300,Math.min(width,available_height - margin.top - margin.bottom));
//Set up the colour scale
var color = d3.scale.category20();
var svg = d3.select(".altui-children-d3chart")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
// .style("margin-left", -margin.left + "px")
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
//Set up the force layout
data = _prepareDataParents( );
var force = d3.layout.force()
.charge(function(d) { return -120 - (d.children ? 2*d.children.length : 0) } )
.gravity(0.05)
.linkDistance(function(d) { return 45+(d.source.children ? 2*d.source.children.length:0 ) })
.size([width, height])
.on("tick", function () {
// avoid asynchronous tick when the user changed the page
// this crashed d3
if ($("#altui-pagetitle").html()==_T("Parent/Child Network"))
{
d3.selectAll(".link")
.attr("x1", function(d) { return d.source.x; })
.attr("y1", function(d) { return d.source.y; })
.attr("x2", function(d) { return d.target.x; })
.attr("y2", function(d) { return d.target.y; });
d3.selectAll("circle")
.attr("cx", function (d) { return d.x; })
.attr("cy", function (d) { return d.y; });
d3.selectAll("text")
.attr("x", function (d) { return d.x; })
.attr("y", function (d) { return d.y; });
}
});
var drag = force.drag().on("dragstart", dragstart);
function sglclick(d) {
if (d3.event.defaultPrevented) return;
// console.log('click');
var selection = d3.select(this);
if (d3.event.shiftKey) {
d.fixed = false;
selection.classed("fixed", false );
}
else {
if (d.children) {
if (d.children.length==0)
return; // non collapsible node
d._children = d.children;
d.children = null;
selection.append("text")
.text("+")
.attr("class", "plussign")
.attr("dx", 0)
.attr("dy", ".35em")
} else {
if (d._children) {
d.children = d._children;
d._children = null;
}
selection.selectAll(".plussign").remove();
}
selection.classed("closed", d._children!=null );
}
_updateChart(data);
};
function dragstart(d) {
// console.log('dragstart');
d3.event.sourceEvent.stopPropagation(); // silence other listeners
d3.select(this).classed("fixed", d.fixed = true);
};
function _updateChart(data) {
function _countChildren(d) {
var s = 0;
if (d && d.children)
$.each(d.children, function(i,child) {
s += ( 1 + _countChildren(child));
})
return s;
};
_updateDataParents();
force
.nodes( data.nodes )
.links( data.links )
.start();
var link = svg.selectAll(".link").data( data.links , function(d) { return d.target.id; } );
var node = svg.selectAll(".node").data( data.nodes , function(d) { return d.id; } );
link.exit().transition().duration(500).style("opacity","0").remove();
link.enter()
.insert("line", ".node") // so that node allways hide links
.attr("class", "link")
.style("stroke", function(d) { return (d.broken==true) ? "red": "" ; } )
.style("stroke-width", 1 )
.attr("x1", function(d) { return d.source.x; })
.attr("y1", function(d) { return d.source.y; })
.attr("x2", function(d) { return d.target.x; })
.attr("y2", function(d) { return d.target.y; });
node.exit().transition().duration(1000).style("opacity","0").remove();
node.classed("fixed", function(d) {
return d.fixed })
.classed("closed", function(d) {
return d._children!=null } );
var groups = node.enter().append("g")
.attr("class", "node")
.classed("fixed", function(d) { return d.fixed } )
.classed("closed", function(d) { return d._children!=null } )
// .on("dblclick", dblclick)
.on("click", sglclick )
.call( drag );
groups.append("circle")
.attr("r", function(d) {
return 8+ ( Math.sqrt(_countChildren(d)) ) ;
// return 8+ (d.children ? d.children.length/2 : 0);
} )
.style("fill", function (d) {
return color(d._children ? "#3182bd" : d.color);
});
groups.append("text")
.attr("dx", 15)
.attr("dy", ".35em")
.text(function (d) { return d.name });
};
_updateChart(data);
};
// prepare and load D3 then draw the chart
UIManager.clearPage(_T('Parent/Child'),_T("Parent/Child Network"),UIManager.oneColumnLayout);
PageMessage.message(_T("Drag and Drop to fix the position of a node. Simple Click to open or collapse a parent node, Shift Click to free a fixed node"),"info");
var html="";
$(".altui-mainpanel")
.append(
"" )
.append(html+"
")
UIManager.loadD3Script( function() {
MultiBox.getDevices(null,null,function(arr) {
// console.log("received {0} devices:".format(arr.length));
devices = arr;
_drawChartParents();
});
});
},
pageRoutes: function() {
var height = null, width = null;
var data = { root:[], nodes:[] , links:[] };
var devices = null;
// Returns a list of all nodes under the root.
function _flatten(root) {
var nodes = [], i = 0;
function recurse(node) {
if (node.children) node.children.forEach(recurse);
// if (!node.id) node.id = ++i;
nodes.push(node);
}
recurse(root);
return nodes;
};
function _findNode( root, id ) {
var found=null;
if (root.id == id )
return root;
if (root.children)
$.each( root.children, function (i,n) {
found = _findNode( n, id );
return ( found==null );
});
return found;
};
function _addNode( node ) {
var parent = _findNode( data.root, node.id_parent );
if (parent==null){
PageMessage.message("Error building node hierarchy","warning");
return;
}
parent.children.push( node );
};
function _drawChartRoutes() {
function _prepareDataRoutes( ) {
data = { root:[], nodes:[] , links:[] };
var color = {};
var nColor = 0;
var devices = $.grep( MultiBox.getDevicesSync() , function(d) {return (MultiBox.controllerOf(d.altuiid).controller==$("#altui-controller-select").val());} );
data.root={ id:0, zwid:0, name:"root", children:[] };
if (devices) {
var zwavenet = MultiBox.getDeviceByType("urn:schemas-micasaverde-com:device:ZWaveNetwork:1");
if (zwavenet) {
color[zwavenet.device_type]=nColor++;
data.nodes.push({
x:width/2,
y:height/2,
id:parseInt(zwavenet.id),
zwid:0,
name:zwavenet.name,
color:color[zwavenet.device_type] ,
id_parent:null,
routes: []
});
$.each( devices, function( idx,device ) {
var ManualRoute = MultiBox.getStatus(device,"urn:micasaverde-com:serviceId:ZWaveDevice1","ManualRoute");
var AutoRoute = MultiBox.getStatus(device,"urn:micasaverde-com:serviceId:ZWaveDevice1","AutoRoute");
if ( ManualRoute || AutoRoute)
{
var route ="";
var bManual = false;
if ( ManualRoute && (ManualRoute!="undefined")) {
route = ManualRoute; bManual = true;
}
else
route = AutoRoute;
if (color[device.device_type]==undefined)
color[device.device_type]=nColor++;
data.nodes.push({
x:Math.random()*width,
y:Math.random()*height,
id:parseInt(device.id),
zwid:parseInt(device.altid),
name:device.name+':'+device.id+'#'+device.altid,
children: [],
color:color[device.device_type] ,
id_parent:device.id_parent || 0,
routes: route.split(","),
manual_route: bManual
});
}
});
}
}
return data;
};
function _updateDataRoutes(data) {
// data.nodes = _flatten(data.root);
// enum devices and create a link per route ManualRoute AutoRoute
// urn:micasaverde-com:serviceId:ZWaveDevice1
// like this: "2-20x,7-59x,2.7-78"
$.each(data.nodes,function( idx, node) {
// insert a link for each route
if (node.routes) {
// console.log("node name:{0} zwid:{1} routes:{2}".format(node.name, node.zwid,node.routes));
$.each(node.routes, function( idx,route) {
var srcnode = node;
var splits = route.split("-");
var linkquality = splits[1] || '0';
if (splits[0]) {
var path = splits[0].split(".");
var nroute = 1;
$.each(path,function(idx,pathnode) {
var targetnode = UIManager._findNodeByZwID(data,pathnode);
if (targetnode) {
// console.log("adding link {0}-{1}".format(srcnode.zwid,targetnode.zwid));
// if ((nroute==1)) {
data.links.push( {
source: srcnode,
target: targetnode,
linkquality: parseInt(linkquality),
nroute: nroute,
broken: (linkquality.slice(-1)=="x"),
manual_route: node.manual_route
});
srcnode = targetnode;
nroute++;
// }
}
});
}
});
}
});
};
$(".altui-children-d3chart").replaceWith(" ");
var available_height = $(window).height() - $("#altui-pagemessage").outerHeight() - $("#altui-pagetitle").outerHeight() - $("#altui-zwavechart-order").outerHeight() - $("footer").outerHeight();
var margin = {top: 20, right: 10, bottom: 10, left: 20};
width = $(".altui-children-d3chart-container").innerWidth() - margin.left - margin.right-30;
height = Math.max(300,Math.min(width,available_height - margin.top - margin.bottom));
//Set up the colour scale
var color = d3.scale.category20();
var linkscale = d3.scale.sqrt().domain([0, 500]).range([80, Math.min(width,height)]);
var svg = d3.select(".altui-children-d3chart")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
// .style("margin-left", -margin.left + "px")
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
//Set up the force layout
data = _prepareDataRoutes( );
var force = d3.layout.force()
force = force
.charge(function(d) { return (d.zwid==0) ? -300 : -100 } )
.gravity(0.015)
.linkDistance(function(d) {
var dist = linkscale( d.linkquality );
return dist; /* 60+d.linkquality*15; */
})
.linkStrength( function(d) {
return 1/(1+d.linkquality/10);
})
.size([width, height])
.on("tick", function () {
// avoid asynchronous tick when the user changed the page
// this crashed d3
d3.selectAll(".link")
.attr("x1", function(d) { return d.source.x; })
.attr("y1", function(d) { return d.source.y; })
.attr("x2", function(d) { return d.target.x; })
.attr("y2", function(d) { return d.target.y; });
d3.selectAll("circle")
.attr("cx", function (d) { return d.x; })
.attr("cy", function (d) { return d.y; });
d3.selectAll("text")
.attr("x", function (d) { return d.x; })
.attr("y", function (d) { return d.y; });
});
var drag = force.drag().on("dragstart", dragstart);
function dragstart(d) {
// console.log('dragstart');
d3.event.sourceEvent.stopPropagation(); // silence other listeners
d3.select(this).classed("fixed", d.fixed = true);
};
function sglclick(d) {
if (d3.event.defaultPrevented) return;
// console.log('click');
var selection = d3.select(this);
if (d3.event.shiftKey) {
d.fixed = false;
selection.classed("fixed", false );
}
else {
}
_updateChart(data);
};
function _updateChart(data) {
_updateDataRoutes(data);
force
.nodes( data.nodes )
.links( data.links )
.start();
var link = svg.selectAll(".link");
var node = svg.selectAll(".node");
link = link.data( data.links , function(d) { return d.source.id+'-'+d.target.id; } );
node = node.data( data.nodes , function(d) { return d.id; } );
link.exit().transition().duration(500).style("opacity","0").remove();
link.enter()
.insert("line", ".node") // so that node allways hide links
.attr("class", "link")
.style("stroke", function(d) { return (d.broken==true) ? "red": ((d.nroute>1)?"yellow":"") ; } )
.style("stroke-dasharray", function(d) { return (d.manual_route) ? "10,10" : null; } )
.style("stroke-width", 1 )
.attr("x1", function(d) { return d.source.x; })
.attr("y1", function(d) { return d.source.y; })
.attr("x2", function(d) { return d.target.x; })
.attr("y2", function(d) { return d.target.y; });
node.exit().transition().duration(1000).style("opacity","0").remove();
node.classed("fixed", function(d) {
return d.fixed })
.classed("closed", function(d) {
return d._children!=null } );
var groups = node.enter().append("g")
.attr("class", "node")
.classed("fixed", function(d) { return d.fixed } )
.classed("closed", function(d) { return d._children!=null } )
// .on("dblclick", dblclick)
.on("click", sglclick )
.call( drag );
groups.append("circle")
.attr("r", function(d) {
return 6+ 2*d.routes.length;
} )
.style("fill", function (d) {
return color(d._children ? "#3182bd" : d.color);
});
groups.append("text")
.attr("dx", 15)
.attr("dy", ".35em")
.text(function (d) { return d.name; });
};
_updateChart(data);
};
// prepare and load D3 then draw the chart
UIManager.clearPage(_T('zWaveRoutes'),_T("zWave Routes"),UIManager.oneColumnLayout);
PageMessage.message(_T("Drag and Drop to fix the position of a node. Simple Click to open or collapse a parent node, Shift Click to free a fixed node"),"info");
$(".altui-mainpanel").append( _createControllerSelect('altui-controller-select'));
$("#altui-controller-select").change(function() {
$(".altui-route-d3chart").html("");
MultiBox.getDevices(
null,
function(d) { return MultiBox.controllerOf(d.altuiid).controller==parseInt($("#altui-controller-select").val()); },
function(arr) {
devices = arr;
_drawChartRoutes();
}
);
});
$(".altui-mainpanel")
.append(
"" )
.append("
")
UIManager.loadD3Script( function() {
MultiBox.getDevices(
null,
function(d) { return MultiBox.controllerOf(d.altuiid).controller==parseInt($("#altui-controller-select").val()); },
function(arr) {
devices = arr;
_drawChartRoutes();
}
);
});
},
drawHouseMode: function ()
{
// http://192.168.1.5/cmh/skins/default/img/other/spritemap_640_480_preset_modes_active.png
// http://192.168.1.5/cmh/skins/default/img/other/spritemap_640_480_preset_modes.png
var html = "";
html +="";
html +="
";
if (_ui7Check==true) {
html += "
";
$.each(_HouseModes, function(idx,mode) {
html += (houseModeButtonTemplate.format(mode.id, mode.text, mode.cls , "preset_unselected"));
});
// html += "
Home
";
// html += "
Away
";
// html += "
Night
";
// html += "
Vacation
";
html += "
";
} else {
// html += "
No Housemode feature on UI5
";
}
html +="
";
html +="
";
$(".altui-mainpanel").append( html );
UIManager.refreshModes();
$("button.altui-housemode").click( function() {
var div = $(this).find(".housemode");
// console.log("set mode="+mode);
var id = $(div).prop('id');
var mode = id.substr("altui-mode".length);
$(div).html( (mode==1) ? 3 : MultiBox.getHouseModeSwitchDelay() );
var interval = setInterval( function(div) {
var val = parseInt( $(div).html() );
if (val==1) {
$(div).html( "" );
clearInterval(interval);
UIManager.refreshModes(); // force a refresh now
} else {
$(div).html( val-1 );
}
}, 1000, div);
MultiBox.setHouseMode(mode);
});
},
pageLocalization: function() {
UIManager.clearPage(_T('Localize'),_T("Localizations"),UIManager.oneColumnLayout);
Localization.dump();
},
pageDebug: function() {
var actions = [
{title:_T("All devices"), id:"altui-debug-alldevices", onclick: onClickAllDevices},
{title:_T("One Device's States"), id:"altui-debug-onedevices", onclick: onClickOneDevice},
{title:_T("Variable search"), id:"altui-debug-searchvariable", onclick: onClickSearchVariable},
{title:_T("Javascript code"), id:"altui-debug-javascript", onclick: onClickJavascript}
];
function _getParameter(name,label,cbfunc) {
var dialog = DialogManager.registerDialog('dialogModal',
defaultDialogModalTemplate.format(
_T('Command Parameters'), // title
" ", // body
"modal-lg" // size
));
var lastOne = MyLocalStorage.getSettings("LastOne_"+name) || "";
DialogManager.dlgAddLine(dialog, name, label, lastOne,"", {required:''} );
DialogManager.dlgAddDialogButton(dialog, true, _T("Run"));
$('div#dialogModal').modal();
$('div#dialogs')
.off('submit',"div#dialogModal")
.on( 'submit',"div#dialogModal", function() {
$('div#dialogModal').modal('hide');
var val = $("#altui-widget-"+name).val();
MyLocalStorage.setSettings("LastOne_"+name,val);
if ($.isFunction(cbfunc))
(cbfunc)( val );
});
};
function onClickJavascript() {
_getParameter('javascriptcode', _T('Javascript code'),function(code){
var result =_T("an error happened during the execution");
try {
result = eval(code);
}
catch(err) { }
$("#altui-oscommand-result").text(JSON.stringify(result,null,2));
});
};
function onClickSearchVariable() {
_getParameter('varnamepattern', _T('Variable Name Pattern'),function(name){
var result=[];
var pattern = new RegExp(name);
var devices = MultiBox.getDevicesSync();
$.each(devices, function(i,device){
var states = $.grep( MultiBox.getStatesByAltuiID(device.altuiid),function(state) {
return pattern.test(state.variable);
});
$.each(states,function(i,state) {
result.push({device:device.altuiid, name:device.name, state:state});
});
});
$("#altui-oscommand-result").text(JSON.stringify(result,null,2));
});
};
function onClickOneDevice() {
_getParameter('devaltuiid', _T('Altui ID'),function(altuiid){
var result = {
altuiid: altuiid,
device_type:MultiBox.getDeviceByAltuiID(altuiid).device_type,
states:MultiBox.getStatesByAltuiID(altuiid),
};
$("#altui-oscommand-result").text(JSON.stringify(result,null,2)); // pretty print
});
};
function onClickAllDevices() {
var devices = MultiBox.getDevicesSync();
$("#altui-oscommand-result").text(JSON.stringify(devices,null,2));
};
UIManager.clearPage(_T('Debug'),_T("Debug Tools"),UIManager.oneColumnLayout);
var html = "";
html += "";
html +="
";
html +="
"+_T("Debug Actions")+"
";
html +="
";
$.each(actions, function(idx,action) {
html +="
";
html += "{0} ".format(action.title,action.id);
html += "
";
});
html += "
";
html +="
";
html +="
";
html += "";
html+="
"+_T("Output");
var glyph = glyphTemplate.format('save',_T("Copy to clipboard"), '');
html += buttonTemplate.format( 'altui-debug-clipboard', 'altui-copy-clipboard', glyph,'default',_T("Copy"));
// html += "{0} ".format(_T("Json Viewer"));
html+=" ";
html+="
";
html +="
";
// append HTML
$(".altui-mainpanel").append(html);
$("#altui-debug-clipboard").click( function() {
Altui_SelectText( "altui-oscommand-result" );
document.execCommand('copy');
});
// register callbacks
$.each(actions, function(idx,action) {
$("."+action.id).click( action.onclick );
});
},
pageTblControllers:function() {
function _displayControllerInfo(box_info) {
return _array2Table(box_info,"PK_AccessPoint",[]);
};
UIManager.clearPage(_T('TblControllers'),_T("Table Controllers"),UIManager.oneColumnLayout);
var html="";
html+="";
html+="
";
var controllers = MultiBox.getControllers();
// var arr = [];
// $.each(controllers, function( idx, controller) {
// var ip = (controller.ip == "" ) ? "Main" : controller.ip ;
// $.each(controller.box_info,function(key,val) {
// if (arr[key]==undefined)
// arr[key]={};
// arr[key][ip]=val;
// });
// });
var bFirst=true;
$.each(controllers, function( idx, controller) {
var name = (controller.ip == "" ) ? "Main" : controller.ip ;
html+=" {1} ".format(
idx,name,
(bFirst==true ? 'active' : ''));
bFirst=false;
});
html+=" ";
html+="
";
bFirst=true;
$.each(controllers, function( idx, controller) {
var name = (controller.ip == "" ) ? "Main" : controller.ip ;
html+="
".format(
idx,
// _displayControllerInfo(controller.box_info),
JSON.stringify(controller.box_info,null,2),
(bFirst==true ? 'active' : ''));
bFirst=false;
});
html+="
";
html+="
";
$(".altui-mainpanel").append( html );
},
pageTblScenes: function() {
UIManager.clearPage(_T('TblScenes'),_T("Table Scenes"),UIManager.oneColumnLayout);
MultiBox.getScenes(null, null, function (scenes) {
var viscols = MyLocalStorage.getSettings("ScenesVisibleCols") || [];
if (viscols.length==0)
viscols = [ 'id','name','last_run'];
var cols = [
{ name:'id', visible: $.inArray('id',viscols)!=-1, type:'numeric', identifier:false, width:50 },
{ name:'altuiid', visible: $.inArray('altuiid',viscols)!=-1, type:'string', identifier:true, width:80 },
{ name:'name', visible: $.inArray('name',viscols)!=-1, type:'string', identifier:false, width:150 }
];
var obj = scenes[0];
if (obj == undefined)
return;
$.each( Object.keys(obj), function (idx,key) {
if ( !$.isArray(obj[key]) && !$.isPlainObject(obj[key]) && (key!='dirty') ) {
if ($.inArray(key, $.map(cols,function(o) { return o.name } ))==-1)
cols.push( { name:key, visible: ($.inArray(key,viscols)!=-1) } );
}
});
var html = "";
html+="";
html+="
";
html+=" ";
html+=" ";
$.each(cols, function(idx,col) {
html += "{0} ".format(
col.name,
col.type,
col.identifier ? "data-identifier='true'" : "",
col.width ? "data-width='{0}'".format(col.width) : "",
"data-visible='{0}'".format(col.visible)
);
});
// add other count
html += "{0} ".format(
"triggers",
"numeric",
"",
50,
"data-visible='{0}'".format($.inArray('triggers',viscols)!=-1)
);
html += "{0} ".format(
"watches",
"numeric",
"",
50,
"data-visible='{0}'".format($.inArray('watches',viscols)!=-1)
);
html += "{0} ".format(
"timers",
"numeric",
"",
50,
"data-visible='{0}'".format($.inArray('timers',viscols)!=-1)
);
html += "Commands ";
html+=" ";
html+=" ";
html+="";
$.each(scenes, function(idx, scene) {
html+=" ";
$.each(cols, function(i,col) {
html += "{0} ".format( _enhanceValue(scene[col.name] || '') );
});
html += "{0} ".format( scene.triggers ? scene.triggers.length : 0 );
html += "{0} ".format( WatchManager.countWatchForScene(scene) );
html += "{0} ".format( scene.timers ? scene.timers.length : 0 );
html += " "; // commands
html+=" ";
});
html+=" ";
html+="
";
html+="
";
$(".altui-mainpanel").append( html );
var options = (MyLocalStorage.getSettings('ShowAllRows')==1) ? {rowCount:-1 } : {};
var grid = $("#altui-grid").bootgrid(
$.extend({
caseSensitive: false,
statusMapping: {},
formatters: {
"commands": function(column, row)
{
return ""+editGlyph+" " +
""+deleteGlyph+" ";
}
}
},options)
).on("loaded.rs.jquery.bootgrid", function (e) {
var settings = $("#altui-grid").bootgrid("getColumnSettings");
viscols = $.map($.grep(settings, function (obj) { return obj.visible == true }),function(obj){ return obj.id;});
MyLocalStorage.setSettings("ScenesVisibleCols",viscols);
/* your code goes here */
grid.find(".altui-command-edit").on('click',function(){
var id = $(this).data("row-id");
UIManager.pageSceneEdit(id);
});
grid.find(".altui-command-delete").on('click',function(){
var altuiid = $(this).data("row-id");
var scene = MultiBox.getSceneByAltuiID(altuiid);
DialogManager.confirmDialog(_T("Are you sure you want to delete scene ({0})").format(altuiid),function(result) {
if (result==true) {
MultiBox.deleteScene( scene );
grid.bootgrid("remove", [scene.altuiid]);
}
});
});
});
// Add CSV export button
var glyph = glyphTemplate.format('save',_T("Copy to clipboard"), '');
var csvButtonHtml = buttonTemplate.format( 'altui-grid-btn', 'altui-tbl2csv', glyph,'default');
$(".actions.btn-group").append(csvButtonHtml);
$("#altui-grid-btn").click( function() {
$('#altui-grid').table2CSV({
delivery : function(data) {
UIManager.pageEditorForm("CSV text",data,null,_T("Copy to clipboard"),function(text,that) {
$(that).prev(".form-group").find("#altui-editor-text").select();
document.execCommand('copy');
$(that).parents("form").remove();
PageMessage.message( _T("Data copied in clipboard"), "info");
});
}
});
});
});
},
pageTblDevices : function() {
UIManager.clearPage(_T('TblDevices'),_T("Table Devices"),UIManager.oneColumnLayout);
MultiBox.getDevices(
null, // per device callback not useful here
null, // no filter
function (devices) { // all devices are enumarated
var viscols = MyLocalStorage.getSettings("DevicesVisibleCols") || [];
if (viscols.length==0)
viscols = [ 'id','name','manufacturer'];
var cols = [
{ name:'id', visible: $.inArray('id',viscols)!=-1, type:'numeric', identifier:true, width:50 },
{ name:'altuiid', visible: $.inArray('altuiid',viscols)!=-1, type:'string', identifier:true, width:80 },
{ name:'altid', visible: $.inArray('altid',viscols)!=-1, type:'string', identifier:true, width:50 },
{ name:'id_parent', visible: $.inArray('id_parent',viscols)!=-1, type:'numeric', identifier:true, width:80 },
{ name:'manufacturer', visible: $.inArray('manufacturer',viscols)!=-1, type:'string', identifier:true, width:120 },
{ name:'model', visible: $.inArray('model',viscols)!=-1, type:'string', identifier:true, width:150 },
{ name:'name', visible: $.inArray('name',viscols)!=-1, type:'string', identifier:true, width:150 }
];
var obj = devices[0];
$.each( Object.keys(obj), function (idx,key) {
if ( !$.isArray(obj[key]) && !$.isPlainObject(obj[key]) && (key!='dirty') ) {
if ($.inArray(key, $.map(cols,function(o) { return o.name } ))==-1)
cols.push( { name:key, visible: ($.inArray(key,viscols)!=-1) } );
}
});
var html = "";
html+="";
html+="
";
html+=" ";
html+=" ";
$.each(cols, function(idx,col) {
html += "{0} ".format(
col.name,
col.type,
col.identifier ? "data-identifier='true'" : "",
col.width ? "data-width='{0}'".format(col.width) : "",
"data-visible='{0}'".format(col.visible)
);
});
html+=" ";
html+=" ";
html+=" ";
$.each(devices, function(idx, device) {
html+=" ";
$.each(cols, function(i,col) {
html += "{0} ".format( _enhanceValue(device[col.name] || '') );
});
html+=" ";
});
html+=" ";
html+="
";
html+="
";
$(".altui-mainpanel").append( html );
var options = (MyLocalStorage.getSettings('ShowAllRows')==1) ? {rowCount:-1 } : {};
$("#altui-grid").bootgrid(
$.extend({
caseSensitive: false,
statusMapping: {}
},options)
).on("loaded.rs.jquery.bootgrid", function (e){
var settings = $("#altui-grid").bootgrid("getColumnSettings");
viscols = $.map($.grep(settings, function (obj) { return obj.visible == true }),function(obj){ return obj.id;});
MyLocalStorage.setSettings("DevicesVisibleCols",viscols);
/* your code goes here */
});
// Add CSV export button
var glyph = glyphTemplate.format('save',_T("Copy to clipboard"), '');
var csvButtonHtml = buttonTemplate.format( 'altui-grid-btn', 'altui-tbl2csv', glyph,'default');
$(".actions.btn-group").append(csvButtonHtml);
$("#altui-grid-btn").click( function() {
$('#altui-grid').table2CSV({
delivery : function(data) {
UIManager.pageEditorForm("CSV text",data,null,_T("Copy to clipboard"),function(text,that) {
$(that).prev(".form-group").find("#altui-editor-text").select();
document.execCommand('copy');
$(that).parents("form").remove();
PageMessage.message( _T("Data copied in clipboard"), "info");
});
}
});
});
}
);
},
pageThemes: function() {
UIManager.clearPage(_T('Themes'),_T("Themes"),UIManager.oneColumnLayout);
PageMessage.message( "Select a theme by clicking on it and refresh your browser", "info");
var resetButton = buttonTemplate.format( "altui-theme-reset", 'btn-default', _T("Reset"),"default",_T('Reset Theme Override'));
var html = "";
html += "";
html +="
";
html +="
"+_T("Themes")+" Bootswatch.com "+resetButton+"
";
html +="
";
html += "
";
html +="
"; //row
html +="
"; //body
html +="
"; //panel
html +="
"; //col-xs-12
$(".altui-mainpanel").append(html);
$.getJSON( "https://bootswatch.com/api/3.json", function( data ) {
$.each(data.themes,function(idx,theme) {
var html ="";
html += "".format(theme.cssCdn,theme.preview);
html += "
{0} {1} ".format(
theme.description,
xsbuttonTemplate.format( '', 'altui-theme-preview', "
",_T('Preview'))
);
html += "
".format(theme.thumbnail);
html +="
"; //col-xs-12
$("#altui-themes").append(html);
});
});
$(".altui-mainpanel").on('click','.altui-theme-thumbnail',function() {
var href = $(this).closest('.altui-theme-thumbnail').data('href');
UIManager.setTheme(href);
}).on('click','.altui-theme-preview',function(e) {
var href = $(this).closest('.altui-theme-thumbnail').data('preview');
window.open(href, '_blank');
return false;
}).on('click','#altui-theme-reset',function(e) {
UIManager.setTheme(null);
});
},
pageOptions: function() {
function _saveOption(name,value) {
MyLocalStorage.setSettings(name, value);
// save a copy of the simple options to Vera
var altuidevice = MultiBox.getDeviceByID( 0, g_MyDeviceID );
var altui_settings = MyLocalStorage.get("ALTUI_Settings");
var tbl={}
$.each(altui_settings,function(key,val) {
if ( (val!=null) && (isObject(val)==false)) {
tbl[key]=btoa(val.toString())
// if (val==false)
// val=0;
// if (val==true)
// val=1;
// tbl.push("{0}={1}".format(key,val));
}
});
MultiBox.setStatus( altuidevice, "urn:upnp-org:serviceId:altui1", "ServerOptions", JSON.stringify(tbl) );
};
UIManager.clearPage(_T('Options'),_T("Options"),UIManager.oneColumnLayout);
var color = IconDB.isDB() ? "text-success" : "text-danger";
var okGlyph = glyphTemplate.format( "ok-sign", "OK" , color );
color = FileDB.isDB() ? "text-success" : "text-danger";
var okGlyph2 = glyphTemplate.format( "ok-sign", "OK" , color );
color = MultiBox.isUserDataCached(0) ? "text-success" : "text-danger";
var okGlyph3 = glyphTemplate.format( "ok-sign", "OK" , color );
color = MyLocalStorage.get("Pages")!=null ? "text-success" : "text-danger";
var okGlyph4 = glyphTemplate.format( "ok-sign", "OK" , color );
var html = "";
html += "";
html +="
";
html +="
"+_T("Options")+"
";
html +="
";
html += "
";
$.each(_checkOptions, function(id,check) {
var init = (MyLocalStorage.getSettings(check.id)!=null) ? MyLocalStorage.getSettings(check.id) : check._default;
html += "
";
var helpbutton = xsbuttonTemplate.format( id, 'altui-help-button', glyphTemplate.format("question-sign","",""), _T(check.help));
switch( check.type ) {
case 'select':
html +=""+_T(check.label)+" : ";
html +="";
$.each(check.choices.split("|"),function(id,unit){
html += "{0} ".format( unit , (unit==init) ? 'selected' : '' );
})
html +=" ";
$(".altui-mainpanel").on("change","#altui-"+check.id,function(){
_saveOption(check.id, $("#altui-"+check.id).val());
});
break;
case 'checkbox':
html +="";
html +=(" "+_T(check.label));
html +=" ";
$(".altui-mainpanel").on("click","#altui-"+check.id,function(){
_saveOption(check.id,$("#altui-"+check.id).is(':checked'));
});
break;
case 'number':
html +=""+_T(check.label)+" :";
html +=(" ");
$(".altui-mainpanel").on("focusout","#altui-"+check.id,function(){
$("#altui-"+check.id).is(':checked')
_saveOption(check.id,parseInt($("#altui-"+check.id).val()));
});
break;
}
html+=helpbutton;
html += "
";
});
html +="
";
html +="
";
html +="
";
html +="
";
html += "";
html +="
";
html +="
"+_T("Cache Control")+"
";
html +="
";
html +="
";
html += ""+saveGlyph+" Save Icon DB ";
html += ""+okGlyph+" Clear Icon DB ";
html += "
";
html += "
";
html += ""+saveGlyph+" Save File DB ";
html += ""+okGlyph2+" Clear File DB ";
html += "
";
html += "
";
html += ""+saveGlyph+"Save UserData ";
html += ""+okGlyph3+" Clear UserData ";
html += "
";
html += "
";
html +="
";
html +="
";
html += "";
html +="
";
html +="
"+_T("Custom Pages Control")+"
";
html +="
";
html += "
";
html += ""+saveGlyph+"Save User Pages ";
html += ""+loadGlyph+"Restore From User Pages Cache ";
html += ""+okGlyph4+" Clear User Pages Cache ";
html += "
";
html += "
";
html +="
";
html +="
";
$(".altui-mainpanel").append(html);
$(".altui-help-button").click( function() {
var id = $(this).prop('id');
var check = _checkOptions[parseInt(id)];
DialogManager.infoDialog(check.id,_T(check.help));
});
$(".altui-save-IconDB").click( function() {
IconDB.saveDB();
UIManager.pageOptions();
});
$(".altui-clear-IconDB").click( function() {
IconDB.resetDB();
UIManager.pageOptions();
});
$(".altui-save-FileDB").click( function() {
FileDB.saveDB();
UIManager.pageOptions();
});
$(".altui-clear-FileDB").click( function() {
FileDB.resetDB();
UIManager.pageOptions();
});
$(".altui-save-userdata").click( function() {
MultiBox.saveEngine();
UIManager.pageOptions();
});
$(".altui-clear-userdata").click( function() {
MultiBox.clearEngine();
UIManager.pageOptions();
});
$(".altui-save-userpage").click( function() {
PageManager.savePages();
});
$(".altui-restore-userpage").click( function() {
PageManager.recoverFromStorage();
UIManager.pageOptions();
});
$(".altui-clear-userpage").click( function() {
PageManager.clearStorage();
UIManager.pageOptions();
});
},
reloadEngine: function() {
MultiBox.reloadEngine(0).done(function(){
PageMessage.message(_T("Reload is done"),"success");
})
},
reboot: function() {
MultiBox.reboot(0)
},
signal: function( eventname ) {
switch (eventname) {
case 'on_ui_initFinished':
bUIReady =true;
break;
case 'on_ui_userDataLoaded':
bEngineReady=true;
break;
}
if ( (bEngineReady==true) && (bUIReady==true) ) {
bUIReady=false;
$(window).on('resize', function () {
/*if (window.innerWidth > tabletSize) */
$(".navbar-collapse").collapse('hide');
UIManager.refreshUI( true ,false ); // full but not first time
UIManager.refreshFooter();
});
$( window ).unload(function() {
// save state to accelerate the launch next time
// UIManager.saveEngine();
MultiBox.saveEngine();
AltuiDebug.debug("exiting");
});
$(".altui-debug-div").toggle(false);
$( document )
.on ("click", ".navbar-nav a", function() { // collapse on click on small screens
// $(".navbar-toggle").click();
if ($(this).data("toggle") != "dropdown") // not for the More... button
$(".navbar-collapse").collapse('hide');
} )
.on ("click touchend", ".imgLogo", UIManager.pageHome )
// .on ("click", ".altui-savechanges-button", MultiBox.saveChangeCaches )
.on ("click", "#menu_room", UIManager.pageRooms )
.on ("click", "#menu_device", UIManager.pageDevices )
.on ("click", "#menu_scene", UIManager.pageScenes )
.on ("click", "#altui-scene-triggers", UIManager.pageTriggers )
.on ("click", "#menu_plugins", UIManager.pagePlugins )
.on ("click", "#altui-pages-see", UIManager.pageUsePages )
.on ("click", "#altui-pages-edit", UIManager.pageEditPages )
.on( "click", "#altui-reload", UIManager.reloadEngine )
.on( "click", "#altui-reboot", UIManager.reboot )
.on( "click", "#altui-remoteaccess", UIManager.pageRemoteAccess )
.on( "click", "#altui-credits", UIManager.pageCredits )
.on( "click", "#altui-oscommand", UIManager.pageOsCommand )
.on( "click", "#altui-luastart", UIManager.pageLuaStart )
.on( "click", "#altui-luatest", UIManager.pageLuaTest )
.on( "click", "#altui-zwavenetwork", UIManager.pageZwave )
.on( "click", "#altui-childrennetwork", UIManager.pageChildren )
.on( "click", "#altui-zwaveroutes", UIManager.pageRoutes )
.on( "click", "#altui-quality", UIManager.pageQuality )
.on( "click", "#altui-energy", UIManager.pagePower )
.on( "click", "#altui-tbl-device", UIManager.pageTblDevices )
.on( "click", "#altui-tbl-scene", UIManager.pageTblScenes )
.on( "click", "#altui-tbl-controllers", UIManager.pageTblControllers )
.on( "click", "#altui-optimize", UIManager.pageOptions )
.on( "click", "#altui-theme-selector", UIManager.pageThemes )
.on( "click", "#altui-localize", UIManager.pageLocalization )
.on( "click", "#altui-debugtools", UIManager.pageDebug )
.on( "click", "#altui-debug-btn", function() {
$(".altui-debug-div").toggle();
$("#altui-debug-btn span.caret").toggleClass( "caret-reversed" );
})
.on("click",".altui-device-variables",function(){
var altuiid = $(this).prop('id');
var device = MultiBox.getDeviceByAltuiID(altuiid);
UIManager.deviceDrawVariables(device);
})
.on("click",".altui-device-actions",function(){
var altuiid = $(this).prop('id');
var device = MultiBox.getDeviceByAltuiID(altuiid);
UIManager.deviceDrawActions(device);
});
AltuiDebug.debug("init done");
// console.log("start UIManager.run()");
_refreshFooter();
UIManager.run();
}
},
run: function( eventname ) {
var homepage = getQueryStringValue("home") || 'pageHome';
// try {
window["UIManager"][homepage](); // call function by its name
// }
// catch (err) {
// PageMessage.message("Exception occurred in "+homepage,"warning");
// AltuiDebug.debug("Exception occurred in "+homepage);
// AltuiDebug.debug("name: "+err.name);
// AltuiDebug.debug("message: "+err.message);
// console.log("Exception occurred in "+homepage);
// console.log("name: "+err.name);// affiche 'Error'
// console.log("message: "+err.message); // affiche 'mon message' ou un message d'erreur JavaScript
// }
}
}; // end of return
})( window );
$(document).ready(function() {
function _initLocalizedGlobals() {
// console.log("_initLocalizedGlobals()");
_HouseModes = [
{id:1, text:_T("Home"), cls:"preset_home"},
{id:2, text:_T("Away"), cls:"preset_away"},
{id:3, text:_T("Night"), cls:"preset_night"},
{id:4, text:_T("Vacation"), cls:"preset_vacation"}
];
// 0: table 1: devicename 2: id
deviceModalTemplate = "";
deviceModalTemplate += "
";
deviceModalTemplate += "
";
deviceModalTemplate += " ";
deviceModalTemplate += "
";
deviceModalTemplate += "
";
deviceModalTemplate += "
";
deviceModalTemplate += "
";
deviceModalTemplate += " ";
deviceModalTemplate += " ";
// deviceModalTemplate += " # ";
deviceModalTemplate += " "+_T("Variable")+" ";
deviceModalTemplate += " ";
deviceModalTemplate += " "+_T("Value")+" ";
deviceModalTemplate += " ";
deviceModalTemplate += " ";
deviceModalTemplate += " ";
deviceModalTemplate += " {0}"; // lines goes here
deviceModalTemplate += " ";
deviceModalTemplate += "
";
deviceModalTemplate += "
"; // col
deviceModalTemplate += "
"; // row
deviceModalTemplate += "
"; // body
deviceModalTemplate += " ";
deviceModalTemplate += "
";
deviceModalTemplate += "
";
deviceModalTemplate += "
";
// 0: table 1: devicename 2: id
deviceActionModalTemplate = "";
deviceActionModalTemplate += "
";
deviceActionModalTemplate += "
";
deviceActionModalTemplate += " ";
deviceActionModalTemplate += "
";
deviceActionModalTemplate += "
";
deviceActionModalTemplate += " ";
deviceActionModalTemplate += " ";
deviceActionModalTemplate += " "+_T("Action")+" ";
deviceActionModalTemplate += " "+_T("Parameters")+" ";
deviceActionModalTemplate += " ";
deviceActionModalTemplate += " ";
deviceActionModalTemplate += " ";
deviceActionModalTemplate += " {0}"; // lines goes here
deviceActionModalTemplate += " ";
deviceActionModalTemplate += "
";
deviceActionModalTemplate += "
";
deviceActionModalTemplate += " ";
deviceActionModalTemplate += "
";
deviceActionModalTemplate += "
";
deviceActionModalTemplate += "
";
// 0: title, 1: body, 2: class size
defaultDialogModalTemplate = "";
defaultDialogModalTemplate += "
";
defaultDialogModalTemplate += "
";
defaultDialogModalTemplate += " ";
defaultDialogModalTemplate += " ";
defaultDialogModalTemplate += "
";
defaultDialogModalTemplate += "
";
defaultDialogModalTemplate += " {1}";
defaultDialogModalTemplate += "
";
defaultDialogModalTemplate += "
";
defaultDialogModalTemplate += " ";
defaultDialogModalTemplate += "
";
defaultDialogModalTemplate += " ";
defaultDialogModalTemplate += "
";
defaultDialogModalTemplate += "
";
//" "
staremtpyGlyph =glyphTemplate.format( "star-empty", _T("Favorite"), "altui-favorite text-muted" );
starGlyph = glyphTemplate.format( "star", _T("Favorite"), "altui-favorite text-warning" );
questionGlyph=glyphTemplate.format( "question-sign", _T("Question"), "text-warning" );
searchGlyph=glyphTemplate.format( "search", _T("Search"), "" );
wrenchGlyph=glyphTemplate.format("wrench", _T("Settings"), "" );
optHorGlyph=glyphTemplate.format( "option-horizontal", _T("Option"), "pull-left" );
signalGlyph=glyphTemplate.format( "signal", _T("Graph"), "" );
calendarGlyph=glyphTemplate.format( "calendar", _T("History"), "" );
refreshGlyph=glyphTemplate.format( "refresh", _T("Refresh"), "text-warning" );
removeGlyph=glyphTemplate.format( "remove", _T("Remove"), "" );
loadGlyph = glyphTemplate.format( "open", _T("Load") , "");
infoGlyph = glyphTemplate.format( "info-sign", _T("Info") , "text-info");
picGlyph = glyphTemplate.format( "picture", _T("Image") , "");
upGlyph = glyphTemplate.format( "arrow-up", _T("More") , "");
downGlyph = glyphTemplate.format( "arrow-down", _T("Less") , "");
uncheckedGlyph= glyphTemplate.format( "unchecked", _T("Frame") , "");
runGlyph = glyphTemplate.format( "play", _T("Run Scene") , "");
editGlyph = glyphTemplate.format( "pencil", _T("Edit") , "");
cameraGlyph = glyphTemplate.format( "facetime-video", _T("Camera") , "");
onoffGlyph = glyphTemplate.format( "off", _T("On Off") , "");
scaleGlyph = glyphTemplate.format( "scale", _T("Gauge") , "");
homeGlyph = glyphTemplate.format( "home", _T("Rooms") , "");
tagsGlyph = glyphTemplate.format( "tags", _T("Category") , "");
helpGlyph = glyphTemplate.format( "question-sign", "" , "");
UIManager.initLocalizedGlobals();
var body = "";
body+="";
body+="
";
body+="";
body+=" ";
body+=" ";
body+="
";
body+="
";
body+="
";
body+=" ";
// body+=" ";
body+=" ";
body+=" ";
body+=" "+_T("More")+" ";
body+=" ";
body+=" ";
body+=" ";
body+=" "+_T("Panels")+" ";
body+=" ";
body+=" ";
body+=" ";
body+=" "+_T("Misc")+" ";
body+=" ";
body+=" ";
body+=" ";
body+="
";
body+="
";
body+=" ";
body+="";
body+="
";
body+="
";
$("#wrap").prepend(body);
// client side override of theme if defined
var clientsideThemecss= MyLocalStorage.getSettings("Theme");
if (clientsideThemecss != null)
g_CustomTheme = clientsideThemecss;
UIManager.initEngine(styles.format(window.location.hostname), g_DeviceTypes, g_CustomTheme, g_Options, function() {
UIManager.initCustomPages(g_CustomPages);
MultiBox.initEngine(g_ExtraController,g_FirstUserData);
EventBus.publishEvent("on_ui_initFinished");
});
};
AltuiDebug.SetDebug( g_DeviceTypes.info["debug"] ) ;
AltuiDebug.debug("starting engines");
AltuiDebug.debug("Configuration: "+JSON.stringify(g_DeviceTypes));
AltuiDebug.debug("Custom Pages: "+JSON.stringify(g_CustomPages));
EventBus.registerEventHandler("on_ui_initFinished",UIManager,UIManager.signal);
EventBus.registerEventHandler("on_ui_userDataLoaded",UIManager,UIManager.signal);
EventBus.registerEventHandler("on_ui_deviceStatusChanged",UIManager,"refreshUIPerDevice");
var language = getQueryStringValue("lang") || window.navigator.userLanguage || window.navigator.language;
AltuiDebug.debug("language:"+language);
// if lang is on the url, the js is already loaded by the LUA module.
if ( (language.substring(0, 2) != 'en') && (getQueryStringValue("lang")=="") ){
// if (false) {
var scriptLocationAndName = 'J_ALTUI_loc_'+ language.substring(0, 2) + '.js' ;
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = scriptLocationAndName;
AltuiDebug.debug("loading script :"+scriptLocationAndName);
// once script is loaded, we can call style function in it
$(script).load( function() {
_initLocalizedGlobals();
} );
head.appendChild(script);
} else {
AltuiDebug.debug("Locale file not needed");
_initLocalizedGlobals();
}
});