Commit 20274b69 authored by nextime's avatar nextime

Organize js/css files for debug and optimization

parent 92021e90
<?
$GUIDEBUG=TRUE;
$BASEGUIPATH=str_replace("/index.php","",$_SERVER['PHP_SELF']);
$FSPATH=realpath(dirname(__FILE__)."/..");
$GUIPATH=str_replace($BASEGUIPATH,'',explode('?',$_SERVER['REQUEST_URI'])[0]);
......
......@@ -864,3 +864,277 @@ jQuery.fn.fastClick = function(handler) {
return this;
};
/* end fastclick */
//! annyang
//! version : 1.1.0
//! author : Tal Ater @TalAter
//! license : MIT
//! https://www.TalAter.com/annyang/
(function (undefined) {
"use strict";
// Save a reference to the global object (window in the browser)
var root = this;
// Get the SpeechRecognition object, while handling browser prefixes
var SpeechRecognition = root.SpeechRecognition ||
root.webkitSpeechRecognition ||
root.mozSpeechRecognition ||
root.msSpeechRecognition ||
root.oSpeechRecognition;
// Check browser support
// This is done as early as possible, to make it as fast as possible for unsupported browsers
if (!SpeechRecognition) {
root.annyang = null;
return undefined;
}
var commandsList = [];
var recognition;
var callbacks = { start: [], error: [], end: [], result: [], resultMatch: [], resultNoMatch: [], errorNetwork: [], errorPermissionBlocked: [], errorPermissionDenied: [] };
var autoRestart;
var lastStartedAt = 0;
var debugState = false;
var debugStyle = 'font-weight: bold; color: #00f;';
// The command matching code is a modified version of Backbone.Router by Jeremy Ashkenas, under the MIT license.
var optionalParam = /\s*\((.*?)\)\s*/g;
var optionalRegex = /(\(\?:[^)]+\))\?/g;
var namedParam = /(\(\?)?:\w+/g;
var splatParam = /\*\w+/g;
var escapeRegExp = /[\-{}\[\]+?.,\\\^$|#]/g;
var commandToRegExp = function(command) {
command = command.replace(escapeRegExp, '\\$&')
.replace(optionalParam, '(?:$1)?')
.replace(namedParam, function(match, optional) {
return optional ? match : '([^\\s]+)';
})
.replace(splatParam, '(.*?)')
.replace(optionalRegex, '\\s*$1?\\s*');
return new RegExp('^' + command + '$', 'i');
};
// This method receives an array of callbacks to iterate over, and invokes each of them
var invokeCallbacks = function(callbacks) {
callbacks.forEach(function(callback) {
callback.callback.apply(callback.context);
});
};
var initIfNeeded = function() {
if (recognition === undefined) {
root.annyang.init({}, false);
}
};
root.annyang = {
// Initialize annyang with a list of commands to recognize.
// e.g. annyang.init({'hello :name': helloFunction})
// annyang understands commands with named variables, splats, and optional words.
init: function(commands, resetCommands) {
// resetCommands defaults to true
if (resetCommands === undefined) {
resetCommands = true;
} else {
resetCommands = !!resetCommands;
}
try {
// Abort previous instances of recognition already running
if (recognition && recognition.abort) {
recognition.abort();
}
// initiate SpeechRecognition
recognition = new SpeechRecognition();
// Set the max number of alternative transcripts to try and match with a command
recognition.maxAlternatives = 5;
recognition.continuous = true;
// Sets the language to the default 'en-US'. This can be changed with annyang.setLanguage()
recognition.lang = 'en-US';
} catch(err) {
root.annyang = null;
return undefined;
}
recognition.onstart = function() { invokeCallbacks(callbacks.start); };
recognition.onerror = function(event) {
invokeCallbacks(callbacks.error);
switch (event.error) {
case 'network':
invokeCallbacks(callbacks.errorNetwork);
break;
case 'not-allowed':
case 'service-not-allowed':
// if permission to use the mic is denied, turn off auto-restart
autoRestart = false;
// determine if permission was denied by user or automatically.
if (new Date().getTime()-lastStartedAt < 200) {
invokeCallbacks(callbacks.errorPermissionBlocked);
} else {
invokeCallbacks(callbacks.errorPermissionDenied);
}
break;
}
};
recognition.onend = function() {
invokeCallbacks(callbacks.end);
// annyang will auto restart if it is closed automatically and not by user action.
if (autoRestart) {
// play nicely with the browser, and never restart annyang automatically more than once per second
var timeSinceLastStart = new Date().getTime()-lastStartedAt;
if (timeSinceLastStart < 1000) {
setTimeout(root.annyang.start, 1000-timeSinceLastStart);
} else {
root.annyang.start();
}
}
};
recognition.onresult = function(event) {
invokeCallbacks(callbacks.result);
var results = event.results[event.resultIndex];
var commandText;
// go over each of the 5 results and alternative results received (we've set maxAlternatives to 5 above)
for (var i = 0; i<results.length; i++) {
// the text recognized
commandText = results[i].transcript.trim();
if (debugState) {
root.console.log('Speech recognized: %c'+commandText, debugStyle);
}
// try and match recognized text to one of the commands on the list
for (var j = 0, l = commandsList.length; j < l; j++) {
var result = commandsList[j].command.exec(commandText);
if (result) {
var parameters = result.slice(1);
if (debugState) {
root.console.log('command matched: %c'+commandsList[j].originalPhrase, debugStyle);
if (parameters.length) {
root.console.log('with parameters', parameters);
}
}
// execute the matched command
commandsList[j].callback.apply(this, parameters);
invokeCallbacks(callbacks.resultMatch);
return true;
}
}
}
invokeCallbacks(callbacks.resultNoMatch);
return false;
};
// build commands list
if (resetCommands) {
commandsList = [];
}
if (commands.length) {
this.addCommands(commands);
}
},
// Start listening (asking for permission first, if needed).
// Call this after you've initialized annyang with commands.
// Receives an optional options object:
// { autoRestart: true }
start: function(options) {
initIfNeeded();
options = options || {};
if (options.autoRestart !== undefined) {
autoRestart = !!options.autoRestart;
} else {
autoRestart = true;
}
lastStartedAt = new Date().getTime();
recognition.start();
},
// abort the listening session (aka stop)
abort: function() {
initIfNeeded();
autoRestart = false;
recognition.abort();
},
// Turn on output of debug messages to the console. Ugly, but super-handy!
debug: function(newState) {
if (arguments.length > 0) {
debugState = !!newState;
} else {
debugState = true;
}
},
// Set the language the user will speak in. If not called, defaults to 'en-US'.
// e.g. 'fr-FR' (French-France), 'es-CR' (Español-Costa Rica)
setLanguage: function(language) {
initIfNeeded();
recognition.lang = language;
},
setContinuous: function(cont) {
initIfNeeded();
recognition.continuous=cont;
},
// Add additional commands that annyang will respond to. Similar in syntax to annyang.init()
addCommands: function(commands) {
var cb,
command;
initIfNeeded();
for (var phrase in commands) {
if (commands.hasOwnProperty(phrase)) {
cb = root[commands[phrase]] || commands[phrase];
if (typeof cb !== 'function') {
continue;
}
//convert command to regex
command = commandToRegExp(phrase);
commandsList.push({ command: command, callback: cb, originalPhrase: phrase });
}
}
if (debugState) {
root.console.log('Commands successfully loaded: %c'+commandsList.length, debugStyle);
}
},
// Remove existing commands. Called with a single phrase or an array of phrases
removeCommands: function(commandsToRemove) {
commandsToRemove = Array.isArray(commandsToRemove) ? commandsToRemove : [commandsToRemove];
commandsList = commandsList.filter(function(command) {
for (var i = 0; i<commandsToRemove.length; i++) {
if (commandsToRemove[i] === command.originalPhrase) {
return false;
}
}
return true;
});
},
// Lets the user add a callback of one of 9 types:
// start, error, end, result, resultMatch, resultNoMatch, errorNetwork, errorPermissionBlocked, errorPermissionDenied
// Can also optionally receive a context for the callback function as the third argument
addCallback: function(type, callback, context) {
if (callbacks[type] === undefined) {
return;
}
var cb = root[callback] || callback;
if (typeof cb !== 'function') {
return;
}
callbacks[type].push({callback: cb, context: context || this});
}
};
}).call(this);
<? @include_once("../includes/common.php");?>
//document.documentElement.requestFullscreen();
var ttsEnabled=<?=$_DOMOTIKA['tts']?>;
var slideEnabled=<?=$_DOMOTIKA['slide']?>;
var speechEnabled='<?=$_DOMOTIKA['webspeech']?>';
//var scroller = new AppScroll({
// toolbar: $('#topbar')[0],
// scroller: $('#content')[0]
//})
var audioTagSupport = !!(document.createElement('audio').canPlayType);
function tmpPopover(el, cont, placement, timeout)
{
console.debug(cont);
//el.popover("destroy");
el.popover({
placement: placement,
content: cont,
delay: {show: 100, hide: timeout},
container: el,
trigger: "manual"});
console.debug(el.popover);
el.popover("show");
el.find(".popover-content").html(cont);
setTimeout(function(){el.popover("destroy")}, timeout);
}
function playTTS(text, lang, force)
{
if(typeof(force)==='undefined') force=false;
if(typeof(lang)==='undefined') lang = "it";
if (!audioTagSupport) return false;
if (text=='') return false;
if (ttsEnabled!=1 && force===false) return false;
var audio = document.createElement('audio');
// XXX BUG: webkit based browsers seems to not work with https:// in <audio>, so, we fix this to http
audio.setAttribute('src', 'http://translate.google.com/translate_tts?tl='+lang+'&q=' + encodeURIComponent(text));
audio.load();
audio.play();
}
function speechResult(data) {
if(data.result=='succeed')
{
var resp=data.data[0];
if(resp=='NOACT')
resp="Nessuna corrispondenza";
tmpPopover($("#speech"), resp, 'top', 1500);
playTTS(resp);
}
}
function sendSpeech(spobj)
{
$.post("/rest/v1.2/actions/speech_text/json", spobj.serialize(), speechResult );
}
// Test SpeechAPI
var speechStartWord='*terms';
if((speechEnabled=='touch' && document.createElement('input').webkitSpeech==undefined) || speechEnabled=='continuous')
{
if(speechEnabled!='continuous')
{
if(window.annyang)
{
$("#speechbutton").show(); // it isn't chrome with webkit-speech attribute, but it support WEB Speech API
}
else
{
$("#speechbutton").hide();
speechEnabled=='no';
}
} else {
$("#speechbutton").hide();
speechStartWord='ok domotica *terms';
}
} else {
speechEnabled='touch-chrome';
}
function setSpeechText(terms)
{
$("#speech [name=text]").val(terms);
$("#speechsm [name=text]").val(terms);
console.debug("SpeechRecognized: "+terms)
sendSpeech($("#speech"));
}
var commands = {
speechStartWord: setSpeechText
};
if(speechEnabled=='touch' || speechEnabled=='continuous')
{
try {
annyang.init(commands);
} catch(err) {
annyang=null;
}
if(annyang) {
annyang.setLanguage('<?=$_DOMOTIKA['speechlang']?>');
if(speechEnabled=='continuous')
annyang.start();
else if(speechEnabled=='touch')
annyang.setContinuous(false);
} else {
$("#speechbutton").hide();
speechEnabled='no';
}
}
var popupFader = function(ftype, title, message, timeout){
if(typeof(timeout)==='undefined') timeout = 1500;
$("#alertTitle").text(title);
r("#alertMessage").text(" "+message);
$("#alertPopup").removeClass();
$("#alertPopup").addClass("alert alert-"+ftype);
$("#alertContainer").fadeIn(100);
$("#alertContainer").fadeOut({duration:timeout, easing:'easeInQuint'});
};
<? if($left || $right) { ?>
var snapper = new Snap({
resistance: 0,
easing: 'linear',
transitionSpeed: 0.1,
tapToClose: false,
element: $('#content')[0],
dragger: $('#content')[0],
//dragger: $('[data-domotika-dragger="true"]')[0],
minDragDistance: 20,
slideIntent: 30,
touchToDrag: slideEnabled
});
<? } ?>
<? if($left || $right) { ?>
snapper.on('animating',
function(e) {
if($(window).width()>768)
mval=Math.min(Math.ceil((75/100)*$(window).width()), 800);
else
mval=Math.max(Math.ceil((75/100)*$(window).width()), 266);
<? if($left) { ?>
if(snapper.state().info.opening=='left' && snapper.state().state!='left' && $(".left-drawer").css("width")!=mval+"px")
{
$(".left-drawer").css("width", mval);
snapper.settings({maxPosition: mval,easing:'ease',transitionSpeed:0.3});
snapper.on('animated', function(e){
snapper.off('animated');
snapper.open('left');
});
}
<? } ?>
<? if($left && $right) { ?> else <? } ?><? if($right) { ?>if(snapper.state().info.opening=='right' && snapper.state().state!='right' && $(".right-drawer").css("width")!=mval+"px")
{
$(".right-drawer").css("width", mval)
snapper.settings({minPosition: -mval,easing:'ease',transitionSpeed:0.3});
snapper.on('animated', function(e){
snapper.off('animated');
snapper.open('right');
});
}
<? } ?>
});
<? } ?>
<? if($left) { ?>
//$('#open-left').on('click',
$('#open-left').fastClick(
function(e) {
if(snapper.state().state=='left')
snapper.close('left');
else {
snapper.open('left');
}
});
<? } ?>
<? if($right) { ?>
//$('#open-right').on('click',
$('#open-right').fastClick(
function(e) {
if(snapper.state().state=='right')
snapper.close('right');
else {
snapper.open('right');
}
});
<? } ?>
function notifylistitem(text, source, nid, ndate)
{
var nd = new Date(parseInt(ndate*1000));
var ndate=nd.toLocaleString();
var nli='<?=notifyListItem();?>';
nli=nli.replace('[TXT]', text);
nli=nli.replace('[NDATE]', ndate);
nli=nli.replace('[NSOURCE]', source);
nli=nli.replace('[NID]', nid);
return nli;
}
//$("#notifybutton").on('click',
$("#notifybutton").fastClick(
function(e) {
if($("#notifypanel").is(":hidden")) {
var hval=Math.ceil((75/100)*$(window).height());
var wval=Math.min(Math.ceil((75/100)*$(window).width()), 500);
$("#notifypanel").css("height", hval);
$("#notifypanel").css("width", wval);
$(".notifylist").css("height", hval-78);
$("#notifications").empty();
$.get("/rest/v1.2/notifications/json", function(r){
for(i=0;i<r.data.length;i++)
{
$("#notifications").prepend(notifylistitem(r.data[i].message, r.data[i].source, r.data[i].id, r.data[i].added));
}
});
}
$.get("/rest/v1.2/notifications/count/json", function(r){ $("#notifybadge").text(r.data);});
$("#notifypanel").slideToggle(200);
});
$('#speech').bind('webkitspeechchange',function(event) {
event.preventDefault();
sendSpeech($("#speech"));
});
$('#speechsm').bind('webkitspeechchange',function(event) {
event.preventDefault();
sendSpeech($("#speech"));
});
$("#speech").keypress(function(event) {
var keycode = (event.keyCode ? event.keyCode : event.which);
if(keycode == 13) {
event.preventDefault();
sendSpeech($("#speech"));
}
});
$("#speechsm").keypress(function(event) {
var keycode = (event.keyCode ? event.keyCode : event.which);
if(keycode == 13) {
event.preventDefault();
sendSpeech($("#speechsm"));
}
});
var es = new EventSource("/sse");
var syncReceived = function(event) {
var res=$.parseJSON(event.data);
$.each(res.data.statuses, function(idx, val){
console.debug(val);
switch(val[3])
{
case 'relay':
var sel="data-domotika-relid";
$("[data-domotika-ampid="+val[0]+"]").each(
function() {
$(this).text(val[2]/10);
}
);
$("[data-domotika-ampcol="+val[0]+"]").each(
function() {
var ampere=val[2]/10;
if(ampere>0 && ampere<8) {
var badgecolor="badge-success";
}else if(ampere>=8 && ampere<11) {
var badgecolor="badge-info";
}else if(ampere>=11 && ampere<14) {
var badgecolor="badge-warning";
}else if(ampere>=14) {
var badgecolor="badge-danger";
} else {
var badgecolor="";
}
$(this).alterClass("badge-*", badgecolor);
}
);
break;
case 'input':
var sel="data-domotika-inpid";
$("[data-domotika-inpled="+val[0]+"]").each(
function() {
if(val[1]>0) {
$(this).alterClass($(this).attr('data-dmcolor-off'), $(this).attr('data-dmcolor-on'));
} else {
$(this).alterClass($(this).attr('data-dmcolor-on'), $(this).attr('data-dmcolor-off'));
}
}
);
break;
case 'analog':
$("[data-domotika-analed="+val[0]+"]").each(
function() {
console.debug("analed");
}
);
$("[data-domotika-anaid="+val[0]+"]").each(
function() {
console.debug("anaid");
}
);
break;
case 'action':
var sel="data-domotika-actid";
$("[data-domotika-act2textid="+val[0]+"]").each(
function() {
if(val[2]>0) {
$(this).text($(this).attr('data-dmtext-on'));
} else {
$(this).text($(this).attr('data-dmtext-off'));
}
}
);
$("[data-domotika-act2col="+val[0]+"]").each(
function() {
if(val[2]>0) {
$(this).alterClass($(this).attr('data-dmcolor-off'), $(this).attr('data-dmcolor-on'));
} else {
$(this).alterClass($(this).attr('data-dmcolor-on'), $(this).attr('data-dmcolor-off'));
}
}
);
break;
}
if(val[3]!="analog") {
$("["+sel+"="+val[0]+"]").each(
function() {
if($(this).prop("nodeName")=="BUTTON") {
if(val[1]>0) {
$(this).alterClass($(this).attr('data-dmcolor-off'), $(this).attr('data-dmcolor-on'));
$(this).text($(this).attr('data-dmtext-on'));
} else {
$(this).alterClass($(this).attr('data-dmcolor-on'), $(this).attr('data-dmcolor-off'));
$(this).text($(this).attr('data-dmtext-off'));
}
} else if($(this).prop("nodeName")=="DIV" && $(this).hasClass('has-switch')) {
$(this).bootstrapSwitch('setState', val[1], true);
}
}
);
} // if !=analog
});
};
var notificationReceived = function(event) {
var data=$.parseJSON(event.data);
var nt=data.data;
var ts=data.ts
$.get("/rest/v1.2/notifications/count/json", function(r){ $("#notifybadge").text(r.data);});
tmpPopover($("#notifybutton"), "New Notify: "+nt.msg, 'left', 1000);
if($("#notifypanel").is(":visible"))
{
$("#notifications").prepend(notifylistitem(nt.msg, nt.source, nt.nid, ts));
$("#notifyid-"+nt.nid).animate({backgroundColor: "#0080ff"},200);
$("#notifyid-"+nt.nid).animate({backgroundColor: "#fff"},3500);
}
playTTS("nuova notifica,"+nt.msg);
};
var deleteNotification = function(el)
{
el.fadeOut(500, function(){el.remove();});
$.ajax({url: "/rest/v1.2/notifications/"+el.attr('id').split("-")[1]+"/json", type:"DELETE", success: function(res){
$.get("/rest/v1.2/notifications/count/json", function(r){
$("#notifybadge").text(r.data);
});
}
});
}
$("#notifications").hammer().on("swipeleft", ".notify-swipe-deletable",
function() {
deleteNotification($(this));
});
$("#notifications").on("click", 'i.notify-deletable',
function() {
deleteNotification($(this).parent().parent());
});
$("#notify-removeall").on("click",
function(){
$.ajax({url: "/rest/v1.2/notifications/", type:"DELETE", success:function(res){
$("#notifypanel").slideToggle(200);
$.get("/rest/v1.2/notifications/count/json",function(r){
$("#notifybadge").text(r.data);
});
}});
});
var setDaemonStatus = function(event) {
var data=$.parseJSON(event.data);
if(data.data=='boardsdetection')
{
$("#modal_fixed").load('/resources/modals/autodetection_run.html');
$("#modal_fixed").modal('show');
} else if(data.data=='normal') {
$("#modal_fixed").modal('hide');
$("#modal_fixed").empty();
location.reload();
}
}
es.addEventListener("daemonstatus", setDaemonStatus);
es.addEventListener("notify", notificationReceived);
es.addEventListener("sync", syncReceived);
es.onerror = function(event){
if(es.readystate=='CLOSED')
es = new EventSource("/sse");
}
$.get("/rest/v1.2/daemonstatus/json",
function(r){
if(r.data=='boardsdetection')
{
$("#modal_fixed").load('/resources/modals/autodetection_run.html');
$("#modal_fixed").modal('show');
}
}
);
setInterval(function(i){
console.debug("setinterval");
$.get("/rest/v1.2/keepalive/json",
function(r){
console.debug(r);
console.debug("getok");
//if('vibrate' in navigator) {
// // ... vibrate for a second
// navigator.vibrate(1000);
//}
if(r.data=='SLOGGEDOUT')
{
location.reload();
}
if($("#modal_offline").attr('aria-hidden')=='false')
$("#modal_offline").modal('hide');
}).fail(function(r){
console.debug("getfail");
console.debug(r);
$("#modal_offline").modal('show');
}
);
},5000);
$.get("/rest/v1.2/notifications/count/json", function(r){ $("#notifybadge").text(r.data);});
/* Fastclick Hammer + jquery */
jQuery.fn.fastClick = function(handler) {
this.click(function(ev) { ev.preventDefault(); });
Hammer(this[0]).on("tap doubletap", handler);
return this;
};
/* end fastclick */
//! annyang
//! version : 1.1.0
//! author : Tal Ater @TalAter
//! license : MIT
//! https://www.TalAter.com/annyang/
(function (undefined) {
"use strict";
// Save a reference to the global object (window in the browser)
var root = this;
// Get the SpeechRecognition object, while handling browser prefixes
var SpeechRecognition = root.SpeechRecognition ||
root.webkitSpeechRecognition ||
root.mozSpeechRecognition ||
root.msSpeechRecognition ||
root.oSpeechRecognition;
// Check browser support
// This is done as early as possible, to make it as fast as possible for unsupported browsers
if (!SpeechRecognition) {
root.annyang = null;
return undefined;
}
var commandsList = [];
var recognition;
var callbacks = { start: [], error: [], end: [], result: [], resultMatch: [], resultNoMatch: [], errorNetwork: [], errorPermissionBlocked: [], errorPermissionDenied: [] };
var autoRestart;
var lastStartedAt = 0;
var debugState = false;
var debugStyle = 'font-weight: bold; color: #00f;';
// The command matching code is a modified version of Backbone.Router by Jeremy Ashkenas, under the MIT license.
var optionalParam = /\s*\((.*?)\)\s*/g;
var optionalRegex = /(\(\?:[^)]+\))\?/g;
var namedParam = /(\(\?)?:\w+/g;
var splatParam = /\*\w+/g;
var escapeRegExp = /[\-{}\[\]+?.,\\\^$|#]/g;
var commandToRegExp = function(command) {
command = command.replace(escapeRegExp, '\\$&')
.replace(optionalParam, '(?:$1)?')
.replace(namedParam, function(match, optional) {
return optional ? match : '([^\\s]+)';
})
.replace(splatParam, '(.*?)')
.replace(optionalRegex, '\\s*$1?\\s*');
return new RegExp('^' + command + '$', 'i');
};
// This method receives an array of callbacks to iterate over, and invokes each of them
var invokeCallbacks = function(callbacks) {
callbacks.forEach(function(callback) {
callback.callback.apply(callback.context);
});
};
var initIfNeeded = function() {
if (recognition === undefined) {
root.annyang.init({}, false);
}
};
root.annyang = {
// Initialize annyang with a list of commands to recognize.
// e.g. annyang.init({'hello :name': helloFunction})
// annyang understands commands with named variables, splats, and optional words.
init: function(commands, resetCommands) {
// resetCommands defaults to true
if (resetCommands === undefined) {
resetCommands = true;
} else {
resetCommands = !!resetCommands;
}
try {
// Abort previous instances of recognition already running
if (recognition && recognition.abort) {
recognition.abort();
}
// initiate SpeechRecognition
recognition = new SpeechRecognition();
// Set the max number of alternative transcripts to try and match with a command
recognition.maxAlternatives = 5;
recognition.continuous = true;
// Sets the language to the default 'en-US'. This can be changed with annyang.setLanguage()
recognition.lang = 'en-US';
} catch(err) {
root.annyang = null;
return undefined;
}
recognition.onstart = function() { invokeCallbacks(callbacks.start); };
recognition.onerror = function(event) {
invokeCallbacks(callbacks.error);
switch (event.error) {
case 'network':
invokeCallbacks(callbacks.errorNetwork);
break;
case 'not-allowed':
case 'service-not-allowed':
// if permission to use the mic is denied, turn off auto-restart
autoRestart = false;
// determine if permission was denied by user or automatically.
if (new Date().getTime()-lastStartedAt < 200) {
invokeCallbacks(callbacks.errorPermissionBlocked);
} else {
invokeCallbacks(callbacks.errorPermissionDenied);
}
break;
}
};
recognition.onend = function() {
invokeCallbacks(callbacks.end);
// annyang will auto restart if it is closed automatically and not by user action.
if (autoRestart) {
// play nicely with the browser, and never restart annyang automatically more than once per second
var timeSinceLastStart = new Date().getTime()-lastStartedAt;
if (timeSinceLastStart < 1000) {
setTimeout(root.annyang.start, 1000-timeSinceLastStart);
} else {
root.annyang.start();
}
}
};
recognition.onresult = function(event) {
invokeCallbacks(callbacks.result);
var results = event.results[event.resultIndex];
var commandText;
// go over each of the 5 results and alternative results received (we've set maxAlternatives to 5 above)
for (var i = 0; i<results.length; i++) {
// the text recognized
commandText = results[i].transcript.trim();
if (debugState) {
root.console.log('Speech recognized: %c'+commandText, debugStyle);
}
// try and match recognized text to one of the commands on the list
for (var j = 0, l = commandsList.length; j < l; j++) {
var result = commandsList[j].command.exec(commandText);
if (result) {
var parameters = result.slice(1);
if (debugState) {
root.console.log('command matched: %c'+commandsList[j].originalPhrase, debugStyle);
if (parameters.length) {
root.console.log('with parameters', parameters);
}
}
// execute the matched command
commandsList[j].callback.apply(this, parameters);
invokeCallbacks(callbacks.resultMatch);
return true;
}
}
}
invokeCallbacks(callbacks.resultNoMatch);
return false;
};
// build commands list
if (resetCommands) {
commandsList = [];
}
if (commands.length) {
this.addCommands(commands);
}
},
// Start listening (asking for permission first, if needed).
// Call this after you've initialized annyang with commands.
// Receives an optional options object:
// { autoRestart: true }
start: function(options) {
initIfNeeded();
options = options || {};
if (options.autoRestart !== undefined) {
autoRestart = !!options.autoRestart;
} else {
autoRestart = true;
}
lastStartedAt = new Date().getTime();
recognition.start();
},
// abort the listening session (aka stop)
abort: function() {
initIfNeeded();
autoRestart = false;
recognition.abort();
},
// Turn on output of debug messages to the console. Ugly, but super-handy!
debug: function(newState) {
if (arguments.length > 0) {
debugState = !!newState;
} else {
debugState = true;
}
},
// Set the language the user will speak in. If not called, defaults to 'en-US'.
// e.g. 'fr-FR' (French-France), 'es-CR' (Español-Costa Rica)
setLanguage: function(language) {
initIfNeeded();
recognition.lang = language;
},
setContinuous: function(cont) {
initIfNeeded();
recognition.continuous=cont;
},
// Add additional commands that annyang will respond to. Similar in syntax to annyang.init()
addCommands: function(commands) {
var cb,
command;
initIfNeeded();
for (var phrase in commands) {
if (commands.hasOwnProperty(phrase)) {
cb = root[commands[phrase]] || commands[phrase];
if (typeof cb !== 'function') {
continue;
}
//convert command to regex
command = commandToRegExp(phrase);
commandsList.push({ command: command, callback: cb, originalPhrase: phrase });
}
}
if (debugState) {
root.console.log('Commands successfully loaded: %c'+commandsList.length, debugStyle);
}
},
// Remove existing commands. Called with a single phrase or an array of phrases
removeCommands: function(commandsToRemove) {
commandsToRemove = Array.isArray(commandsToRemove) ? commandsToRemove : [commandsToRemove];
commandsList = commandsList.filter(function(command) {
for (var i = 0; i<commandsToRemove.length; i++) {
if (commandsToRemove[i] === command.originalPhrase) {
return false;
}
}
return true;
});
},
// Lets the user add a callback of one of 9 types:
// start, error, end, result, resultMatch, resultNoMatch, errorNetwork, errorPermissionBlocked, errorPermissionDenied
// Can also optionally receive a context for the callback function as the third argument
addCallback: function(type, callback, context) {
if (callbacks[type] === undefined) {
return;
}
var cb = root[callback] || callback;
if (typeof cb !== 'function') {
return;
}
callbacks[type].push({callback: cb, context: context || this});
}
};
}).call(this);
Hammer.plugins.fakeMultitouch();
<? @include_once("../includes/common.php");?>
<? /*
<? if($GUIDEBUG) { ?>
<!-- JavaScript plugins (requires jQuery) -->
<script src="/resources/js/jquery-1.9.0.min.js"></script>
<script src="/resources/jquery-color/jquery.color.min.js"></script>
<script src="/resources/hammer.js/dist/hammer.min.js"></script>
<script src="/resources/hammer.js/plugins/hammer.fakemultitouch.js"></script>
<!--[if !IE]> -->
<script>
Hammer.plugins.fakeMultitouch();
</script>
<script src="/resources/js/starthammer.js"></script>
<!-- <![endif]-->
<script src="/resources/hammer.js/dist/jquery.hammer.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
......@@ -23,468 +21,13 @@
<script src="/resources/AppScroll.js/AppScroll.min.js"></script>
<!-- EventSource (aka Server-Sent Events) -->
<script src="/resources/EventSource/eventsource.js"></script>
*/ ?>
<!-- jquery easing plugin -->
<script src="/resources/js/jquery.easing.1.3.min.js"></script>
<script src="/resources/js/jquery.alterclass.js"></script>
<script src="<?=$BASEGUIPATH;?>/js/fastclick.js"></script>
<script src="<?=$BASEGUIPATH;?>/js/speech.js"></script>
<script src="<?=$BASEGUIPATH;?>/js/domotika.js"></script>
<? } else { ?>
<script src="<?=$BASEGUIPATH;?>/js/combined.min.js"></script>
<?
//if($_DOMOTIKA['webspeech']!="no")
if(FALSE)
{?>
<script src="/resources/speech/annyang.min.js"></script>
<?}?>
<script>
//document.documentElement.requestFullscreen();
var ttsEnabled=<?=$_DOMOTIKA['tts']?>;
var slideEnabled=<?=$_DOMOTIKA['slide']?>;
var speechEnabled='<?=$_DOMOTIKA['webspeech']?>';
if(speechEnabled=='touch' && document.createElement('input').webkitSpeech==undefined)
{
testSpeech=window.webkitSpeechRecognition ||
window.mozSpeechRecognition ||
window.msSpeechRecognition ||
window.oSpeechRecognition ||
window.SpeechRecognition;
if(testSpeech)
{
$("#speechbutton").show(); // it isn't chrome with webkit-speech attribute, but it support WEB Speech API
}
else
{
$("#speechbutton").hide();
speechEnabled=='no';
}
} else {
speechEnabled='touch-chrome';
}
speechStartWord='*terms';
if(speechEnabled=='continuous')
speechStartWord='ok domotica *terms';
//var scroller = new AppScroll({
// toolbar: $('#topbar')[0],
// scroller: $('#content')[0]
//})
var audioTagSupport = !!(document.createElement('audio').canPlayType);
function tmpPopover(el, cont, placement, timeout)
{
console.debug(cont);
//el.popover("destroy");
el.popover({
placement: placement,
content: cont,
delay: {show: 100, hide: timeout},
container: el,
trigger: "manual"});
console.debug(el.popover);
el.popover("show");
el.find(".popover-content").html(cont);
setTimeout(function(){el.popover("destroy")}, timeout);
}
function playTTS(text, lang, force)
{
if(typeof(force)==='undefined') force=false;
if(typeof(lang)==='undefined') lang = "it";
if (!audioTagSupport) return false;
if (text=='') return false;
if (ttsEnabled!=1 && force===false) return false;
var audio = document.createElement('audio');
// XXX BUG: webkit based browsers seems to not work with https:// in <audio>, so, we fix this to http
audio.setAttribute('src', 'http://translate.google.com/translate_tts?tl='+lang+'&q=' + encodeURIComponent(text));
audio.load();
audio.play();
}
function speechResult(data) {
if(data.result=='succeed')
{
var resp=data.data[0];
if(resp=='NOACT')
resp="Nessuna corrispondenza";
tmpPopover($("#speech"), resp, 'top', 1500);
playTTS(resp);
}
}
function sendSpeech(spobj)
{
$.post("/rest/v1.2/actions/speech_text/json", spobj.serialize(), speechResult );
}
// Test SpeechAPI
function setSpeechText(terms)
{
$("#speech [name=text]").val(terms);
$("#speechsm [name=text]").val(terms);
console.debug("SpeechRecognized: "+terms)
sendSpeech($("#speech"));
}
var commands = {
speechStartWord: setSpeechText
};
/*
if(speechEnabled=='touch' || speechEnabled=='continuous')
{
annyang.init(commands);
annyang.setLanguage('<?=$_DOMOTIKA['speechlang']?>');
}
if(speechEnabled=='continuous')
annyang.start();
else if(speechEnabled=='touch')
annyang.recognition.continuous=false;
*/
var popupFader = function(ftype, title, message, timeout){
if(typeof(timeout)==='undefined') timeout = 1500;
$("#alertTitle").text(title);
r("#alertMessage").text(" "+message);
$("#alertPopup").removeClass();
$("#alertPopup").addClass("alert alert-"+ftype);
$("#alertContainer").fadeIn(100);
$("#alertContainer").fadeOut({duration:timeout, easing:'easeInQuint'});
};
<? if($left || $right) { ?>
var snapper = new Snap({
resistance: 0,
easing: 'linear',
transitionSpeed: 0.1,
tapToClose: false,
element: $('#content')[0],
//dragger: $('#content')[0],
dragger: $('[data-domotika-dragger="true"]')[0],
minDragDistance: 20,
slideIntent: 30,
//touchToDrag: slideEnabled
});
<? } ?>
<? if($left || $right) { ?>
snapper.on('animating',
function(e) {
if($(window).width()>768)
mval=Math.min(Math.ceil((75/100)*$(window).width()), 800);
else
mval=Math.max(Math.ceil((75/100)*$(window).width()), 266);
<? if($left) { ?>
if(snapper.state().info.opening=='left' && snapper.state().state!='left' && $(".left-drawer").css("width")!=mval+"px")
{
$(".left-drawer").css("width", mval);
snapper.settings({maxPosition: mval,easing:'ease',transitionSpeed:0.3});
snapper.on('animated', function(e){
snapper.off('animated');
snapper.open('left');
});
}
<? } ?>
<? if($left && $right) { ?> else <? } ?><? if($right) { ?>if(snapper.state().info.opening=='right' && snapper.state().state!='right' && $(".right-drawer").css("width")!=mval+"px")
{
$(".right-drawer").css("width", mval)
snapper.settings({minPosition: -mval,easing:'ease',transitionSpeed:0.3});
snapper.on('animated', function(e){
snapper.off('animated');
snapper.open('right');
});
}
<? } ?>
});
<script src="<?=$BASEGUIPATH;?>/js/domotika.js"></script>
<? } ?>
<? if($left) { ?>
//$('#open-left').on('click',
$('#open-left').fastClick(
function(e) {
if(snapper.state().state=='left')
snapper.close('left');
else {
snapper.open('left');
}
});
<? } ?>
<? if($right) { ?>
//$('#open-right').on('click',
$('#open-right').fastClick(
function(e) {
if(snapper.state().state=='right')
snapper.close('right');
else {
snapper.open('right');
}
});
<? } ?>
function notifylistitem(text, source, nid, ndate)
{
var nd = new Date(parseInt(ndate*1000));
var ndate=nd.toLocaleString();
var nli='<?=notifyListItem();?>';
nli=nli.replace('[TXT]', text);
nli=nli.replace('[NDATE]', ndate);
nli=nli.replace('[NSOURCE]', source);
nli=nli.replace('[NID]', nid);
return nli;
}
//$("#notifybutton").on('click',
$("#notifybutton").fastClick(
function(e) {
if($("#notifypanel").is(":hidden")) {
var hval=Math.ceil((75/100)*$(window).height());
var wval=Math.min(Math.ceil((75/100)*$(window).width()), 500);
$("#notifypanel").css("height", hval);
$("#notifypanel").css("width", wval);
$(".notifylist").css("height", hval-78);
$("#notifications").empty();
$.get("/rest/v1.2/notifications/json", function(r){
for(i=0;i<r.data.length;i++)
{
$("#notifications").prepend(notifylistitem(r.data[i].message, r.data[i].source, r.data[i].id, r.data[i].added));
}
});
}
$.get("/rest/v1.2/notifications/count/json", function(r){ $("#notifybadge").text(r.data);});
$("#notifypanel").slideToggle(200);
});
$('#speech').bind('webkitspeechchange',function(event) {
event.preventDefault();
sendSpeech($("#speech"));
});
$('#speechsm').bind('webkitspeechchange',function(event) {
event.preventDefault();
sendSpeech($("#speech"));
});
$("#speech").keypress(function(event) {
var keycode = (event.keyCode ? event.keyCode : event.which);
if(keycode == 13) {
event.preventDefault();
sendSpeech($("#speech"));
}
});
$("#speechsm").keypress(function(event) {
var keycode = (event.keyCode ? event.keyCode : event.which);
if(keycode == 13) {
event.preventDefault();
sendSpeech($("#speechsm"));
}
});
var es = new EventSource("/sse");
var syncReceived = function(event) {
var res=$.parseJSON(event.data);
$.each(res.data.statuses, function(idx, val){
console.debug(val);
switch(val[3])
{
case 'relay':
var sel="data-domotika-relid";
$("[data-domotika-ampid="+val[0]+"]").each(
function() {
$(this).text(val[2]/10);
}
);
$("[data-domotika-ampcol="+val[0]+"]").each(
function() {
var ampere=val[2]/10;
if(ampere>0 && ampere<8) {
var badgecolor="badge-success";
}else if(ampere>=8 && ampere<11) {
var badgecolor="badge-info";
}else if(ampere>=11 && ampere<14) {
var badgecolor="badge-warning";
}else if(ampere>=14) {
var badgecolor="badge-danger";
} else {
var badgecolor="";
}
$(this).alterClass("badge-*", badgecolor);
}
);
break;
case 'input':
var sel="data-domotika-inpid";
$("[data-domotika-inpled="+val[0]+"]").each(
function() {
if(val[1]>0) {
$(this).alterClass($(this).attr('data-dmcolor-off'), $(this).attr('data-dmcolor-on'));
} else {
$(this).alterClass($(this).attr('data-dmcolor-on'), $(this).attr('data-dmcolor-off'));
}
}
);
break;
case 'analog':
$("[data-domotika-analed="+val[0]+"]").each(
function() {
console.debug("analed");
}
);
$("[data-domotika-anaid="+val[0]+"]").each(
function() {
console.debug("anaid");
}
);
break;
case 'action':
var sel="data-domotika-actid";
$("[data-domotika-act2textid="+val[0]+"]").each(
function() {
if(val[2]>0) {
$(this).text($(this).attr('data-dmtext-on'));
} else {
$(this).text($(this).attr('data-dmtext-off'));
}
}
);
$("[data-domotika-act2col="+val[0]+"]").each(
function() {
if(val[2]>0) {
$(this).alterClass($(this).attr('data-dmcolor-off'), $(this).attr('data-dmcolor-on'));
} else {
$(this).alterClass($(this).attr('data-dmcolor-on'), $(this).attr('data-dmcolor-off'));
}
}
);
break;
}
if(val[3]!="analog") {
$("["+sel+"="+val[0]+"]").each(
function() {
if($(this).prop("nodeName")=="BUTTON") {
if(val[1]>0) {
$(this).alterClass($(this).attr('data-dmcolor-off'), $(this).attr('data-dmcolor-on'));
$(this).text($(this).attr('data-dmtext-on'));
} else {
$(this).alterClass($(this).attr('data-dmcolor-on'), $(this).attr('data-dmcolor-off'));
$(this).text($(this).attr('data-dmtext-off'));
}
} else if($(this).prop("nodeName")=="DIV" && $(this).hasClass('has-switch')) {
$(this).bootstrapSwitch('setState', val[1], true);
}
}
);
} // if !=analog
});
};
var notificationReceived = function(event) {
var data=$.parseJSON(event.data);
var nt=data.data;
var ts=data.ts
$.get("/rest/v1.2/notifications/count/json", function(r){ $("#notifybadge").text(r.data);});
tmpPopover($("#notifybutton"), "New Notify: "+nt.msg, 'left', 1000);
if($("#notifypanel").is(":visible"))
{
$("#notifications").prepend(notifylistitem(nt.msg, nt.source, nt.nid, ts));
$("#notifyid-"+nt.nid).animate({backgroundColor: "#0080ff"},200);
$("#notifyid-"+nt.nid).animate({backgroundColor: "#fff"},3500);
}
playTTS("nuova notifica,"+nt.msg);
};
var deleteNotification = function(el)
{
el.fadeOut(500, function(){el.remove();});
$.ajax({url: "/rest/v1.2/notifications/"+el.attr('id').split("-")[1]+"/json", type:"DELETE", success: function(res){
$.get("/rest/v1.2/notifications/count/json", function(r){
$("#notifybadge").text(r.data);
});
}
});
}
$("#notifications").hammer().on("swipeleft", ".notify-swipe-deletable",
function() {
deleteNotification($(this));
});
$("#notifications").on("click", 'i.notify-deletable',
function() {
deleteNotification($(this).parent().parent());
});
$("#notify-removeall").on("click",
function(){
$.ajax({url: "/rest/v1.2/notifications/", type:"DELETE", success:function(res){
$("#notifypanel").slideToggle(200);
$.get("/rest/v1.2/notifications/count/json",function(r){
$("#notifybadge").text(r.data);
});
}});
});
var setDaemonStatus = function(event) {
var data=$.parseJSON(event.data);
if(data.data=='boardsdetection')
{
$("#modal_fixed").load('/resources/modals/autodetection_run.html');
$("#modal_fixed").modal('show');
} else if(data.data=='normal') {
$("#modal_fixed").modal('hide');
$("#modal_fixed").empty();
location.reload();
}
}
es.addEventListener("daemonstatus", setDaemonStatus);
es.addEventListener("notify", notificationReceived);
es.addEventListener("sync", syncReceived);
es.onerror = function(event){
if(es.readystate=='CLOSED')
es = new EventSource("/sse");
}
$.get("/rest/v1.2/daemonstatus/json",
function(r){
if(r.data=='boardsdetection')
{
$("#modal_fixed").load('/resources/modals/autodetection_run.html');
$("#modal_fixed").modal('show');
}
}
);
setInterval(function(i){
console.debug("setinterval");
$.get("/rest/v1.2/keepalive/json",
function(r){
console.debug(r);
console.debug("getok");
//if('vibrate' in navigator) {
// // ... vibrate for a second
// navigator.vibrate(1000);
//}
if(r.data=='SLOGGEDOUT')
{
location.reload();
}
if($("#modal_offline").attr('aria-hidden')=='false')
$("#modal_offline").modal('hide');
}).fail(function(r){
console.debug("getfail");
console.debug(r);
$("#modal_offline").modal('show');
}
);
},5000);
$.get("/rest/v1.2/notifications/count/json", function(r){ $("#notifybadge").text(r.data);});
</script>
......@@ -14,12 +14,14 @@
<!-- Chrome for Android web app tags -->
<meta name="mobile-web-app-capable" content="yes">
<link rel="shortcut icon" sizes="256x256" href="/resources/img/logo_icon.png" />
<? /*
<? if($GUIDEBUG) { ?>
<!-- Bootstrap -->
<link href="/resources/bootstrap/css/bootstrap.min.css" rel="stylesheet" media="screen">
<link href="/resources/glyphicons/css/bootstrap-glyphicons.css" rel="stylesheet" media="screen">
<link href="/resources/full-glyphicons/css/glyphicons.css" rel="stylesheet" media="screen">
<link href="/resources/bootstrap-switch/static/stylesheets/bootstrap-switch.css" rel="stylesheet" media="screen">
*/?>
<link href="<?=$BASEGUIPATH;?>/css/style.css" rel="stylesheet" media="screen" />
<? } else { ?>
<link href="<?=$BASEGUIPATH;?>/css/combined.min.css" rel="stylesheet" media="screen" />
<link href="<?=$BASEGUIPATH;?>/css/style.css" rel="stylesheet" media="screen" />
<? } ?>
/* Fastclick Hammer + jquery */
jQuery.fn.fastClick = function(handler) {
this.click(function(ev) { ev.preventDefault(); });
Hammer(this[0]).on("tap doubletap", handler);
return this;
};
/* end fastclick */
/**
* jQuery alterClass plugin
*
* Remove element classes with wildcard matching. Optionally add classes:
* $( '#foo' ).alterClass( 'foo-* bar-*', 'foobar' )
*
* Copyright (c) 2011 Pete Boere (the-echoplex.net)
* Free under terms of the MIT license: http://www.opensource.org/licenses/mit-license.php
*
*/
(function ( $ ) {
$.fn.alterClass = function ( removals, additions ) {
var self = this;
if ( removals.indexOf( '*' ) === -1 ) {
// Use native jQuery methods if there is no wildcard matching
self.removeClass( removals );
return !additions ? self : self.addClass( additions );
}
var patt = new RegExp( '\\s' +
removals.
replace( /\*/g, '[A-Za-z0-9-_]+' ).
split( ' ' ).
join( '\\s|\\s' ) +
'\\s', 'g' );
self.each( function ( i, it ) {
var cn = ' ' + it.className + ' ';
while ( patt.test( cn ) ) {
cn = cn.replace( patt, ' ' );
}
it.className = $.trim( cn );
});
return !additions ? self : self.addClass( additions );
};
})( jQuery );
/* end of alterclass plugin */
......@@ -29,7 +29,7 @@ AddType application/x-web-app-manifest+json .webapp
<Directory /home/domotika/Web/htdocs>
Options FollowSymLinks
AllowOverride All
AllowOverride All
DirectoryIndex index.php index.html index.htm
<IfModule mod_php5.c>
......@@ -70,5 +70,10 @@ AddType application/x-web-app-manifest+json .webapp
</Directory>
<Directory /home/domotika/Web/htdocs/admin>
Options FollowSymLinks Indexes
AllowOverride All
DirectoryIndex index.php index.html index.htm
Deny from All
Allow from 127.0.0.1
Require ip 127.0.0.1
</Directory>
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment