Browse Source

Ping/pong for websocket added

master
Torsten Stauder 5 years ago
parent
commit
3514607dd5
  1. 47
      html/website.html
  2. 21
      src/main.cpp
  3. 47
      src/websiteMgmt.h

47
html/website.html

@ -87,7 +87,7 @@
</div> </div>
<div class="container my-5" id="rfidModTags"> <div class="container my-5" id="rfidModTags">
<h2>RFID-Modifkationen</h2> <h2>RFID-Modifkationen</h2>
<form class="needs-validation" action="#rfidModTags" method="POST" onsubmit="rfidMods('rfidModTags'); return false" novalidate>
<form class="needs-validation" action="#rfidModTags" method="POST" onsubmit="rfidMods('rfidModTags'); return false">
<div class="form-group col-md-6"> <div class="form-group col-md-6">
<label for="rfidIdMod">RFID-Chip-Nummer</label> <label for="rfidIdMod">RFID-Chip-Nummer</label>
<input type="text" class="form-control" id="rfidIdMod" maxlength="12" pattern="[0-9]{12}" placeholder="%RFID_TAG_ID%" name="rfidIdMod" required> <input type="text" class="form-control" id="rfidIdMod" maxlength="12" pattern="[0-9]{12}" placeholder="%RFID_TAG_ID%" name="rfidIdMod" required>
@ -116,7 +116,7 @@
</div> </div>
<div class="container my-5" id="mqttConfig"> <div class="container my-5" id="mqttConfig">
<h2>MQTT-Konfiguration</h2> <h2>MQTT-Konfiguration</h2>
<form class="needs-validation" action="#mqttConfig" method="POST" onsubmit="mqttSettings('mqttConfig'); return false" novalidate>
<form class="needs-validation" action="#mqttConfig" method="POST" onsubmit="mqttSettings('mqttConfig'); return false">
<div class="form-check col-md-6"> <div class="form-check col-md-6">
<input class="form-check-input" type="checkbox" value="1" id="mqttEnable" name="mqttEnable" %MQTT_ENABLE%> <input class="form-check-input" type="checkbox" value="1" id="mqttEnable" name="mqttEnable" %MQTT_ENABLE%>
<label class="form-check-label" for="mqttEnable"> <label class="form-check-label" for="mqttEnable">
@ -178,25 +178,28 @@
var errorBox = '<div class="alert alert-danger alert-dismissible fade show" role="alert">Es ist ein Fehler aufgetreten!<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button></div>'; var errorBox = '<div class="alert alert-danger alert-dismissible fade show" role="alert">Es ist ein Fehler aufgetreten!<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button></div>';
var okBox = '<div class="alert alert-success alert-dismissible fade show" role="alert">Aktion erfolgreich ausgeführt.<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button></div>'; var okBox = '<div class="alert alert-success alert-dismissible fade show" role="alert">Aktion erfolgreich ausgeführt.<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button></div>';
(function() {
'use strict';
window.addEventListener('load', function() {
/* Fetch all the forms we want to apply custom Bootstrap validation styles to*/
var forms = document.getElementsByClassName('needs-validation');
/* Loop over them and prevent submission*/
var validation = Array.prototype.filter.call(forms, function(form) {
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
var socket = new WebSocket("ws://%IPv4%/ws");
function ping() {
var myObj = {
"ping": {
ping: 'ping'
}
};
var myJSON = JSON.stringify(myObj);
socket.send(myJSON);
tm = setTimeout(function () {
alert("Die Verbindung zum Tonuino ist unterbrochen!\\nBitte Seite neu laden.");
}, 5000);
} }
form.classList.add('was-validated');
}, false);
});
}, false);
});
let socket = new WebSocket("ws://%IPv4%/ws");
function pong() {
clearTimeout(tm);
}
socket.onopen = function () {
setInterval(ping, 15000);
};
socket.onclose = function(e) { socket.onclose = function(e) {
console.log('Socket is closed. Reconnect will be attempted in 1 second.', e.reason); console.log('Socket is closed. Reconnect will be attempted in 1 second.', e.reason);
@ -207,7 +210,7 @@
socket.onerror = function(err) { socket.onerror = function(err) {
console.error('Socket encountered error: ', err.message, 'Closing socket'); console.error('Socket encountered error: ', err.message, 'Closing socket');
ws.close();
socket.close();
}; };
socket.onmessage = function(event) { socket.onmessage = function(event) {
@ -225,6 +228,10 @@
} else { } else {
$("#" + lastIdclicked).find('.messages').html(errorBox); $("#" + lastIdclicked).find('.messages').html(errorBox);
} }
} if (socketMsg.pong != null) {
if (socketMsg.pong == 'pong') {
pong();
}
} }
}; };

21
src/main.cpp

@ -668,6 +668,14 @@ void callback(const char *topic, const byte *payload, uint32_t length) {
} }
// Modify sleep-timer? // Modify sleep-timer?
else if (strcmp_P(topic, topicSleepTimerCmnd) == 0) { else if (strcmp_P(topic, topicSleepTimerCmnd) == 0) {
if (playProperties.playMode == NO_PLAYLIST) { // Don't allow sleep-modications if no playlist is active
loggerNl((char *) FPSTR(modificatorNotallowedWhenIdle), LOGLEVEL_INFO);
publishMqtt((char *) FPSTR(topicSleepState), 0, false);
#ifdef NEOPIXEL_ENABLE
showLedError = true;
#endif
return;
}
if (strcmp(receivedString, "EOP") == 0) { if (strcmp(receivedString, "EOP") == 0) {
playProperties.sleepAfterPlaylist = true; playProperties.sleepAfterPlaylist = true;
loggerNl((char *) FPSTR(sleepTimerEOP), LOGLEVEL_NOTICE); loggerNl((char *) FPSTR(sleepTimerEOP), LOGLEVEL_NOTICE);
@ -2291,9 +2299,7 @@ void doRfidCardModifications(const uint32_t mod) {
#ifdef NEOPIXEL_ENABLE #ifdef NEOPIXEL_ENABLE
ledBrightness = initialLedBrightness; ledBrightness = initialLedBrightness;
#endif #endif
#ifdef MQTT_ENABLE
publishMqtt((char *) FPSTR(topicSleepTimerState), "0", false);
#endif
loggerNl((char *) FPSTR(modificatorSleepd), LOGLEVEL_NOTICE);
} else { } else {
if (playProperties.currentTrackNumber + 5 > playProperties.numberOfTracks) { // If currentTrack + 5 exceeds number of tracks in playlist, sleep after end of playlist if (playProperties.currentTrackNumber + 5 > playProperties.numberOfTracks) { // If currentTrack + 5 exceeds number of tracks in playlist, sleep after end of playlist
playProperties.sleepAfterPlaylist = true; playProperties.sleepAfterPlaylist = true;
@ -2666,6 +2672,8 @@ bool processJsonRequest(char *_serialJson) {
if (sSsid.compareTo(_ssid) || sPwd.compareTo(_pwd)) { if (sSsid.compareTo(_ssid) || sPwd.compareTo(_pwd)) {
return false; return false;
} }
} else if (doc.containsKey("ping")) {
sendWebsocketData(0, 20);
} }
return true; return true;
@ -2684,6 +2692,8 @@ void sendWebsocketData(uint32_t client, uint8_t code) {
object["status"] = "error"; object["status"] = "error";
} else if (code == 10) { } else if (code == 10) {
object["rfidId"] = currentRfidTagId; object["rfidId"] = currentRfidTagId;
} else if (code == 20) {
object["pong"] = "pong";
} }
char jBuf[50]; char jBuf[50];
serializeJson(doc, jBuf, sizeof(jBuf) / sizeof(jBuf[0])); serializeJson(doc, jBuf, sizeof(jBuf) / sizeof(jBuf[0]));
@ -2701,7 +2711,7 @@ void onWebsocketEvent(AsyncWebSocket * server, AsyncWebSocketClient * client, Aw
if (type == WS_EVT_CONNECT){ if (type == WS_EVT_CONNECT){
//client connected //client connected
Serial.printf("ws[%s][%u] connect\n", server->url(), client->id()); Serial.printf("ws[%s][%u] connect\n", server->url(), client->id());
client->printf("Hello Client %u :)", client->id());
//client->printf("Hello Client %u :)", client->id());
client->ping(); client->ping();
} else if (type == WS_EVT_DISCONNECT) { } else if (type == WS_EVT_DISCONNECT) {
//client disconnected //client disconnected
@ -3006,7 +3016,6 @@ void setup() {
encoder.clearCount(); encoder.clearCount();
encoder.setCount(initVolume*2); // Ganzes Raster ist immer +2, daher initiale Lautstärke mit 2 multiplizieren encoder.setCount(initVolume*2); // Ganzes Raster ist immer +2, daher initiale Lautstärke mit 2 multiplizieren
// Only enable MQTT if requested // Only enable MQTT if requested
#ifdef MQTT_ENABLE #ifdef MQTT_ENABLE
if (enableMqtt) { if (enableMqtt) {
@ -3020,7 +3029,7 @@ void setup() {
lastTimeActiveTimestamp = millis(); // initial set after boot lastTimeActiveTimestamp = millis(); // initial set after boot
if (wifiManager() == WL_CONNECTED) { if (wifiManager() == WL_CONNECTED) {
// Websocket
// Websocket for Mgmt-Interface
ws.onEvent(onWebsocketEvent); ws.onEvent(onWebsocketEvent);
wServer.addHandler(&ws); wServer.addHandler(&ws);

47
src/websiteMgmt.h

@ -87,7 +87,7 @@ static const char mgtWebsite[] PROGMEM = "<!DOCTYPE html>\
</div>\ </div>\
<div class=\"container my-5\" id=\"rfidModTags\">\ <div class=\"container my-5\" id=\"rfidModTags\">\
<h2>RFID-Modifkationen</h2>\ <h2>RFID-Modifkationen</h2>\
<form class=\"needs-validation\" action=\"#rfidModTags\" method=\"POST\" onsubmit=\"rfidMods('rfidModTags'); return false\" novalidate>\
<form class=\"needs-validation\" action=\"#rfidModTags\" method=\"POST\" onsubmit=\"rfidMods('rfidModTags'); return false\">\
<div class=\"form-group col-md-6\">\ <div class=\"form-group col-md-6\">\
<label for=\"rfidIdMod\">RFID-Chip-Nummer</label>\ <label for=\"rfidIdMod\">RFID-Chip-Nummer</label>\
<input type=\"text\" class=\"form-control\" id=\"rfidIdMod\" maxlength=\"12\" pattern=\"[0-9]{12}\" placeholder=\"%RFID_TAG_ID%\" name=\"rfidIdMod\" required>\ <input type=\"text\" class=\"form-control\" id=\"rfidIdMod\" maxlength=\"12\" pattern=\"[0-9]{12}\" placeholder=\"%RFID_TAG_ID%\" name=\"rfidIdMod\" required>\
@ -116,7 +116,7 @@ static const char mgtWebsite[] PROGMEM = "<!DOCTYPE html>\
</div>\ </div>\
<div class=\"container my-5\" id=\"mqttConfig\">\ <div class=\"container my-5\" id=\"mqttConfig\">\
<h2>MQTT-Konfiguration</h2>\ <h2>MQTT-Konfiguration</h2>\
<form class=\"needs-validation\" action=\"#mqttConfig\" method=\"POST\" onsubmit=\"mqttSettings('mqttConfig'); return false\" novalidate>\
<form class=\"needs-validation\" action=\"#mqttConfig\" method=\"POST\" onsubmit=\"mqttSettings('mqttConfig'); return false\">\
<div class=\"form-check col-md-6\">\ <div class=\"form-check col-md-6\">\
<input class=\"form-check-input\" type=\"checkbox\" value=\"1\" id=\"mqttEnable\" name=\"mqttEnable\" %MQTT_ENABLE%>\ <input class=\"form-check-input\" type=\"checkbox\" value=\"1\" id=\"mqttEnable\" name=\"mqttEnable\" %MQTT_ENABLE%>\
<label class=\"form-check-label\" for=\"mqttEnable\">\ <label class=\"form-check-label\" for=\"mqttEnable\">\
@ -178,25 +178,28 @@ static const char mgtWebsite[] PROGMEM = "<!DOCTYPE html>\
var errorBox = '<div class=\"alert alert-danger alert-dismissible fade show\" role=\"alert\">Es ist ein Fehler aufgetreten!<button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-label=\"Close\"><span aria-hidden=\"true\">&times;</span></button></div>';\ var errorBox = '<div class=\"alert alert-danger alert-dismissible fade show\" role=\"alert\">Es ist ein Fehler aufgetreten!<button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-label=\"Close\"><span aria-hidden=\"true\">&times;</span></button></div>';\
var okBox = '<div class=\"alert alert-success alert-dismissible fade show\" role=\"alert\">Aktion erfolgreich ausgeführt.<button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-label=\"Close\"><span aria-hidden=\"true\">&times;</span></button></div>';\ var okBox = '<div class=\"alert alert-success alert-dismissible fade show\" role=\"alert\">Aktion erfolgreich ausgeführt.<button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-label=\"Close\"><span aria-hidden=\"true\">&times;</span></button></div>';\
\ \
(function() {\
'use strict';\
window.addEventListener('load', function() {\
/* Fetch all the forms we want to apply custom Bootstrap validation styles to*/\
var forms = document.getElementsByClassName('needs-validation');\
/* Loop over them and prevent submission*/\
var validation = Array.prototype.filter.call(forms, function(form) {\
form.addEventListener('submit', function(event) {\
if (form.checkValidity() === false) {\
event.preventDefault();\
event.stopPropagation();\
var socket = new WebSocket(\"ws://%IPv4%/ws\");\
\
function ping() {\
var myObj = {\
\"ping\": {\
ping: 'ping'\
}\
};\
var myJSON = JSON.stringify(myObj);\
socket.send(myJSON);\
tm = setTimeout(function () {\
alert(\"Die Verbindung zum Tonuino ist unterbrochen!\\nBitte Seite neu laden.\");\
}, 5000);\
}\ }\
form.classList.add('was-validated');\
}, false);\
});\
}, false);\
});\
\ \
let socket = new WebSocket(\"ws://%IPv4%/ws\");\
function pong() {\
clearTimeout(tm);\
}\
\
socket.onopen = function () {\
setInterval(ping, 15000);\
};\
\ \
socket.onclose = function(e) {\ socket.onclose = function(e) {\
console.log('Socket is closed. Reconnect will be attempted in 1 second.', e.reason);\ console.log('Socket is closed. Reconnect will be attempted in 1 second.', e.reason);\
@ -207,7 +210,7 @@ static const char mgtWebsite[] PROGMEM = "<!DOCTYPE html>\
\ \
socket.onerror = function(err) {\ socket.onerror = function(err) {\
console.error('Socket encountered error: ', err.message, 'Closing socket');\ console.error('Socket encountered error: ', err.message, 'Closing socket');\
ws.close();\
socket.close();\
};\ };\
\ \
socket.onmessage = function(event) {\ socket.onmessage = function(event) {\
@ -225,6 +228,10 @@ static const char mgtWebsite[] PROGMEM = "<!DOCTYPE html>\
} else {\ } else {\
$(\"#\" + lastIdclicked).find('.messages').html(errorBox);\ $(\"#\" + lastIdclicked).find('.messages').html(errorBox);\
}\ }\
} if (socketMsg.pong != null) {\
if (socketMsg.pong == 'pong') {\
pong();\
}\
}\ }\
};\ };\
\ \

Loading…
Cancel
Save