// First, checks if it isn't implemented yet.
if (!String.prototype.format) {
String.prototype.format = function() {
var args = arguments;
return this.replace(/{(\d+)}/g, function(match, number) {
return typeof args[number] != 'undefined' ?
args[number] :
match;
});
};
}
if (!String.prototype.encodeHTML) {
String.prototype.encodeHTML = function () {
return this.replace(/&/g, '&')
.replace(//g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
};
}
var nvs_type_t = {
NVS_TYPE_U8: 0x01,
/*!< Type uint8_t */
NVS_TYPE_I8: 0x11,
/*!< Type int8_t */
NVS_TYPE_U16: 0x02,
/*!< Type uint16_t */
NVS_TYPE_I16: 0x12,
/*!< Type int16_t */
NVS_TYPE_U32: 0x04,
/*!< Type uint32_t */
NVS_TYPE_I32: 0x14,
/*!< Type int32_t */
NVS_TYPE_U64: 0x08,
/*!< Type uint64_t */
NVS_TYPE_I64: 0x18,
/*!< Type int64_t */
NVS_TYPE_STR: 0x21,
/*!< Type string */
NVS_TYPE_BLOB: 0x42,
/*!< Type blob */
NVS_TYPE_ANY: 0xff /*!< Must be last */
};
pillcolors = {
'MESSAGING_INFO' : 'badge-success',
'MESSAGING_WARNING' : 'badge-warning',
'MESSAGING_ERROR' : 'badge-danger'
}
var task_state_t = {
0: "eRunning",
/*!< A task is querying the state of itself, so must be running. */
1: "eReady",
/*!< The task being queried is in a read or pending ready list. */
2: "eBlocked",
/*!< The task being queried is in the Blocked state. */
3: "eSuspended",
/*!< The task being queried is in the Suspended state, or is in the Blocked state with an infinite time out. */
4: "eDeleted"
}
var escapeHTML = function(unsafe) {
return unsafe.replace(/[&<"']/g, function(m) {
switch (m) {
case '&':
return '&';
case '<':
return '<';
case '"':
return '"';
default:
return ''';
}
});
};
function setNavColor(stylename){
$('[name=secnav]').removeClass('bg-secondary bg-warning');
$("footer.footer").removeClass('bg-secondary bg-warning');
$("#mainnav").removeClass('bg-secondary bg-warning');
if(stylename.length>0){
$('[name=secnav]').addClass(stylename);
$("footer.footer").addClass(stylename);
$("#mainnav").addClass(stylename);
}
}
function handleTemplateTypeRadio(outtype){
if (outtype == 'bt') {
$("#btsinkdiv").parent().show(200);
$("#btsinkdiv").show();
$('#bt').prop('checked',true);
o_bt.setAttribute("display", "inline");
o_spdif.setAttribute("display", "none");
o_i2s.setAttribute("display", "none");
output = 'bt';
} else if (outtype == 'spdif') {
$("#btsinkdiv").parent().hide(200);
$("#btsinkdiv").show();
$('#spdif').prop('checked',true);
o_bt.setAttribute("display", "none");
o_spdif.setAttribute("display", "inline");
o_i2s.setAttribute("display", "none");
output = 'spdif';
} else {
$("#btsinkdiv").parent().hide(200);
$("#btsinkdiv").show();
$('#i2s').prop('checked',true);
o_bt.setAttribute("display", "none");
o_spdif.setAttribute("display", "none");
o_i2s.setAttribute("display", "inline");
output = 'i2s';
}
}
function handleExceptionResponse(xhr, ajaxOptions, thrownError){
console.log(xhr.status);
console.log(thrownError);
enableStatusTimer=true;
if (thrownError != '') showLocalMessage(thrownError, 'MESSAGING_ERROR');
}
function HideCmdMessage(cmdname){
$('#toast_'+cmdname).css('display','none');
$('#toast_'+cmdname).removeClass('table-success').removeClass('table-warning').removeClass('table-danger').addClass('table-success');
$('#msg_'+cmdname).html('');
}
function showCmdMessage(cmdname,msgtype, msgtext,append=false){
color='table-success';
if (msgtype == 'MESSAGING_WARNING') {
color='table-warning';
} else if (msgtype == 'MESSAGING_ERROR') {
color ='table-danger';
}
$('#toast_'+cmdname).css('display','block');
$('#toast_'+cmdname).removeClass('table-success').removeClass('table-warning').removeClass('table-danger').addClass(color);
escapedtext=escapeHTML(msgtext.substring(0, msgtext.length - 1)).replace(/\n/g, '
');
escapedtext=($('#msg_'+cmdname).html().length>0 && append?$('#msg_'+cmdname).html()+'
':'')+escapedtext;
$('#msg_'+cmdname).html(escapedtext);
}
var releaseURL = 'https://api.github.com/repos/sle118/squeezelite-esp32/releases';
var recovery = false;
var enableAPTimer = true;
var enableStatusTimer = true;
var commandHeader = 'squeezelite -b 500:2000 -d all=info -C 30 -W';
var pname, ver, otapct, otadsc;
var blockAjax = false;
var blockFlashButton = false;
var dblclickCounter = 0;
var apList = null;
var selectedSSID = "";
var refreshAPInterval = null;
var checkStatusInterval = null;
var messagecount=0;
var messageseverity="MESSAGING_INFO";
var StatusIntervalActive = false;
var RefreshAPIIntervalActive = false;
var LastRecoveryState = null;
var LastCommandsState = null;
var output = '';
Promise.prototype.delay = function(duration) {
return this.then(function(value) {
return new Promise(function(resolve) {
setTimeout(function() {
resolve(value)
}, duration)
})
}, function(reason) {
return new Promise(function(resolve, reject) {
setTimeout(function() {
reject(reason)
}, duration)
})
})
}
function stopCheckStatusInterval() {
if (checkStatusInterval != null) {
clearTimeout(checkStatusInterval);
checkStatusInterval = null;
}
StatusIntervalActive = false;
}
function stopRefreshAPInterval() {
if (refreshAPInterval != null) {
clearTimeout(refreshAPInterval);
refreshAPInterval = null;
}
RefreshAPIIntervalActive = false;
}
function startCheckStatusInterval() {
StatusIntervalActive = true;
checkStatusInterval = setTimeout(checkStatus, 3000);
}
function startRefreshAPInterval() {
RefreshAPIIntervalActive = true;
refreshAPInterval = setTimeout(refreshAP(false), 4500); // leave enough time for the initial scan
}
function RepeatCheckStatusInterval() {
if (StatusIntervalActive)
startCheckStatusInterval();
}
function RepeatRefreshAPInterval() {
if (RefreshAPIIntervalActive)
startRefreshAPInterval();
}
function getConfigJson(slimMode) {
var config = {};
$("input.nvs").each(function() {
var key = $(this)[0].id;
var val = $(this).val();
if (!slimMode) {
var nvs_type = parseInt($(this)[0].attributes.nvs_type.nodeValue, 10);
if (key != '') {
config[key] = {};
if (nvs_type == nvs_type_t.NVS_TYPE_U8 ||
nvs_type == nvs_type_t.NVS_TYPE_I8 ||
nvs_type == nvs_type_t.NVS_TYPE_U16 ||
nvs_type == nvs_type_t.NVS_TYPE_I16 ||
nvs_type == nvs_type_t.NVS_TYPE_U32 ||
nvs_type == nvs_type_t.NVS_TYPE_I32 ||
nvs_type == nvs_type_t.NVS_TYPE_U64 ||
nvs_type == nvs_type_t.NVS_TYPE_I64) {
config[key].value = parseInt(val);
} else {
config[key].value = val;
}
config[key].type = nvs_type;
}
} else {
config[key] = val;
}
});
var key = $("#nvs-new-key").val();
var val = $("#nvs-new-value").val();
if (key != '') {
if (!slimMode) {
config[key] = {};
config[key].value = val;
config[key].type = 33;
} else {
config[key] = val;
}
}
return config;
}
function onFileLoad(elementId, event) {
var data = {};
try {
data = JSON.parse(elementId.srcElement.result);
} catch (e) {
alert('Parsing failed!\r\n ' + e);
}
$("input.nvs").each(function() {
var key = $(this)[0].id;
var val = $(this).val();
if (data[key]) {
if (data[key] != val) {
console.log("Changed " & key & " " & val & "==>" & data[key]);
$(this).val(data[key]);
}
} else {
console.log("Value " & key & " missing from file");
}
});
}
function onChooseFile(event, onLoadFileHandler) {
if (typeof window.FileReader !== 'function')
throw ("The file API isn't supported on this browser.");
input = event.target;
if (!input)
throw ("The browser does not properly implement the event object");
if (!input.files)
throw ("This browser does not support the `files` property of the file input.");
if (!input.files[0])
return undefined;
file = input.files[0];
fr = new FileReader();
fr.onload = onLoadFileHandler;
fr.readAsText(file);
input.value = "";
}
function delay_reboot(duration,cmdname, ota=false){
url= (ota?'/reboot_ota.json':'/reboot.json');
$("tbody#tasks").empty();
setNavColor('bg-secondary');
enableStatusTimer=false;
$("#tasks_sect").css('visibility','collapse');
Promise.resolve(cmdname).delay(duration).then(function(cmdname) {
if(cmdname?.length >0){
showCmdMessage(cmdname,'MESSAGING_WARNING','Rebooting the ESP32.\n',true);
}
else {
showLocalMessage('Rebooting the ESP32.\n','MESSAGING_WARNING')
}
console.log('now triggering reboot');
$.ajax({
url: this.url,
dataType: 'text',
method: 'POST',
cache: false,
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({
'timestamp': Date.now()
}),
error: handleExceptionResponse,
complete: function(response) {
console.log('reboot call completed');
enableStatusTimer=true;
Promise.resolve(cmdname).delay(6000).then(function(cmdname) {
if(cmdname?.length >0) HideCmdMessage(cmdname);
getCommands();
getConfig();
});
}
});
});
}
function save_autoexec1(apply){
showCmdMessage('cfg-audio-tmpl','MESSAGING_INFO',"Saving.\n",false);
var commandLine = commandHeader + ' -n "' + $("#player").val() + '"';
if (output == 'bt') {
if($("#btsinkdiv").val()?.length!=0){
commandLine += ' -o "BT -n \'' + $("#btsinkdiv").val() + '\'" -Z 192000';
}
else {
showCmdMessage('cfg-audio-tmpl','MESSAGING_ERROR',"BT Sink Name required for output bluetooth.\n",true);
return;
}
} else if (output == 'spdif') {
commandLine += ' -o SPDIF -Z 192000';
} else {
commandLine += ' -o I2S';
}
if ($("#optional").val() != '') {
commandLine += ' ' + $("#optional").val();
}
var data = {
'timestamp': Date.now()
};
autoexec = $("#disable-squeezelite").prop('checked') ? "0" : "1";
data['config'] = {
autoexec1: { value: commandLine, type: 33 },
autoexec: { value: autoexec, type: 33 }
}
$.ajax({
url: '/config.json',
dataType: 'text',
method: 'POST',
cache: false,
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(data),
error: handleExceptionResponse,
complete: function(response) {
if(JSON.parse(response?.responseText)?.result == "OK"){
showCmdMessage('cfg-audio-tmpl','MESSAGING_INFO',"Done.\n",true);
if (apply) {
delay_reboot(1500,"cfg-audio-tmpl");
}
}
else if(response.responseText) {
showCmdMessage('cfg-audio-tmpl','MESSAGING_WARNING',JSON.parse(response.responseText).Result + "\n",true);
}
else {
showCmdMessage('cfg-audio-tmpl','MESSAGING_ERROR',response.responseText+'\n');
}
console.log(response.responseText);
}
});
console.log('sent data:', JSON.stringify(data));
}
$(document).ready(function() {
// $(".dropdown-item").on("click", function(e){
// var linkText = $(e.relatedTarget).text(); // Get the link text
// });
$("input#show-commands")[0].checked = LastCommandsState == 1 ? true : false;
$('a[href^="#tab-commands"]').hide();
$("#load-nvs").click(function() {
$("#nvsfilename").trigger('click');
});
$("#wifi-status").on("click", ".ape", function() {
$("#wifi").slideUp("fast", function() {});
$("#connect-details").slideDown("fast", function() {});
});
$("#clear-syslog").on("click",function(){
messagecount=0;
messageseverity="MESSAGING_INFO";
$('#msgcnt').text('');
$("#syslogTable").html('');
});
$("#manual_add").on("click", ".ape", function() {
selectedSSID = $(this).text();
$("#ssid-pwd").text(selectedSSID);
$("#wifi").slideUp("fast", function() {});
$("#connect_manual").slideDown("fast", function() {});
$("#connect").slideUp("fast", function() {});
//update wait screen
$("#loading").show();
$("#connect-success").hide();
$("#connect-fail").hide();
});
$("#wifi-list").on("click", ".ape", function() {
selectedSSID = $(this).text();
$("#ssid-pwd").text(selectedSSID);
$("#wifi").slideUp("fast", function() {});
$("#connect_manual").slideUp("fast", function() {});
$("#connect").slideDown("fast", function() {});
//update wait screen
$("#loading").show();
$("#connect-success").hide();
$("#connect-fail").hide();
});
$("#cancel").on("click", function() {
selectedSSID = "";
$("#connect").slideUp("fast", function() {});
$("#connect_manual").slideUp("fast", function() {});
$("#wifi").slideDown("fast", function() {});
});
$("#manual_cancel").on("click", function() {
selectedSSID = "";
$("#connect").slideUp("fast", function() {});
$("#connect_manual").slideUp("fast", function() {});
$("#wifi").slideDown("fast", function() {});
});
$("#join").on("click", function() {
performConnect();
});
$("#manual_join").on("click", function() {
performConnect($(this).data('connect'));
});
$("#ok-details").on("click", function() {
$("#connect-details").slideUp("fast", function() {});
$("#wifi").slideDown("fast", function() {});
});
$("#ok-credits").on("click", function() {
$("#credits").slideUp("fast", function() {});
$("#app").slideDown("fast", function() {});
});
$("#acredits").on("click", function(event) {
event.preventDefault();
$("#app").slideUp("fast", function() {});
$("#credits").slideDown("fast", function() {});
});
$("#ok-connect").on("click", function() {
$("#connect-wait").slideUp("fast", function() {});
$("#wifi").slideDown("fast", function() {});
});
$("#disconnect").on("click", function() {
$("#connect-details-wrap").addClass('blur');
$("#diag-disconnect").slideDown("fast", function() {});
});
$("#no-disconnect").on("click", function() {
$("#diag-disconnect").slideUp("fast", function() {});
$("#connect-details-wrap").removeClass('blur');
});
$("#yes-disconnect").on("click", function() {
stopCheckStatusInterval();
selectedSSID = "";
$("#diag-disconnect").slideUp("fast", function() {});
$("#connect-details-wrap").removeClass('blur');
$.ajax({
url: '/connect.json',
dataType: 'text',
method: 'DELETE',
cache: false,
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({
'timestamp': Date.now()
})
});
startCheckStatusInterval();
$("#connect-details").slideUp("fast", function() {});
$("#wifi").slideDown("fast", function() {})
});
$("input#show-commands").on("click", function() {
this.checked = this.checked ? 1 : 0;
if (this.checked) {
$('a[href^="#tab-commands"]').show();
LastCommandsState = 1;
} else {
LastCommandsState = 0;
$('a[href^="#tab-commands"]').hide();
}
});
$("input#show-nvs").on("click", function() {
this.checked = this.checked ? 1 : 0;
if (this.checked) {
$('a[href^="#tab-nvs"]').show();
} else {
$('a[href^="#tab-nvs"]').hide();
}
});
$("#save-as-nvs").on("click", function() {
var data = {
'timestamp': Date.now()
};
var config = getConfigJson(true);
const a = document.createElement("a");
a.href = URL.createObjectURL(
new Blob([JSON.stringify(config, null, 2)], {
type: "text/plain"
}));
a.setAttribute("download", "nvs_config" + Date.now() + "json");
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
console.log('sent config JSON with headers:', JSON.stringify(headers));
console.log('sent config JSON with data:', JSON.stringify(data));
});
$("#save-nvs").on("click", function() {
var headers = {};
var data = {
'timestamp': Date.now()
};
var config = getConfigJson(false);
data['config'] = config;
$.ajax({
url: '/config.json',
dataType: 'text',
method: 'POST',
cache: false,
headers: headers,
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(data),
error: handleExceptionResponse
});
console.log('sent config JSON with headers:', JSON.stringify(headers));
console.log('sent config JSON with data:', JSON.stringify(data));
});
$("#fwUpload").on("click", function() {
var upload_path = "/flash.json";
if(!recovery) $('#flash-status').text('Rebooting to OTA');
var fileInput = document.getElementById("flashfilename").files;
if (fileInput.length == 0) {
alert("No file selected!");
} else {
var file = fileInput[0];
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4) {
if (xhttp.status == 200) {
showLocalMessage(xhttp.responseText, 'MESSAGING_INFO')
} else if (xhttp.status == 0) {
showLocalMessage("Upload connection was closed abruptly!", 'MESSAGING_ERROR');
} else {
showLocalMessage(xhttp.status + " Error!\n" + xhttp.responseText, 'MESSAGING_ERROR');
}
}
};
xhttp.open("POST", upload_path, true);
xhttp.send(file);
}
enableStatusTimer = true;
});
$("#flash").on("click", function() {
var data = {
'timestamp': Date.now()
};
if (blockFlashButton) return;
blockFlashButton = true;
var url = $("#fwurl").val();
data['config'] = {
fwurl: {
value: url,
type: 33
}
};
$.ajax({
url: '/config.json',
dataType: 'text',
method: 'POST',
cache: false,
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(data),
error: handleExceptionResponse
});
enableStatusTimer = true;
});
$('[name=output-tmpl]').on("click", function() {
handleTemplateTypeRadio(this.id);
});
$('#fwcheck').on("click", function() {
$("#releaseTable").html("");
$("#fwbranch").empty();
$.getJSON(releaseURL, function(data) {
var i = 0;
var branches = [];
data.forEach(function(release) {
namecomponents=release.name.split('#');
ver=namecomponents[0];
idf=namecomponents[1];
cfg=namecomponents[2];
branch=namecomponents[3];
if (!branches.includes(branch)) {
branches.push(branch);
}
});
var fwb;
branches.forEach(function(branch) {
fwb += '';
});
$("#fwbranch").append(fwb);
data.forEach(function(release) {
var url = '';
release.assets.forEach(function(asset) {
if (asset.name.match(/\.bin$/)) {
url = asset.browser_download_url;
}
});
namecomponents = release.name.split('#');
ver=namecomponents[0];
idf=namecomponents[1];
cfg=namecomponents[2];
branch=namecomponents[3];
var body = release.body;
body = body.replace(/\'/ig, "\"");
body = body.replace(/[\s\S]+(### Revision Log[\s\S]+)### ESP-IDF Version Used[\s\S]+/, "$1");
body = body.replace(/- \(.+?\) /g, "- ");
var [date, time] = release.created_at.split('T');
var trclass = (i++ > 6) ? ' hide' : '';
$("#releaseTable").append(
"