Browse Source

Replace all ajax requests with websockets

fastled
Xose Pérez 8 years ago
parent
commit
d34a15a9f1
3 changed files with 106 additions and 120 deletions
  1. +18
    -34
      code/html/custom.js
  2. +0
    -84
      code/src/webserver.ino
  3. +88
    -2
      code/src/websockets.ino

+ 18
- 34
code/html/custom.js View File

@ -1,40 +1,28 @@
var websock;
function doUpdate() {
var self = $(this);
self.addClass("loading");
$.ajax({
'method': 'POST',
'url': '/save',
'dataType': 'json',
'data': $("#formSave").serializeArray()
}).done(function(data) {
self.removeClass("loading");
}).fail(function() {
self.removeClass("loading");
});
var data = $("#formSave").serializeArray();
websock.send(JSON.stringify({'config': data}));
return false;
}
function doReset() {
var response = window.confirm("Are you sure you want to reset the device?");
if (response == false) return;
var self = $(this);
self.addClass("loading");
$.ajax({
'method': 'GET',
'url': '/reset'
});
if (response == false) return false;
websock.send(JSON.stringify({'action': 'reset'}));
return false;
}
function doReconnect() {
var response = window.confirm("Are you sure you want to disconnect from the current WIFI network?");
if (response == false) return;
var self = $(this);
self.addClass("loading");
$.ajax({
'method': 'GET',
'url': '/reconnect'
});
if (response == false) return false;
websock.send(JSON.stringify({'action': 'reconnect'}));
return false;
}
function doToggle(element, value) {
websock.send(JSON.stringify({'action': value ? 'on' : 'off'}));
return false;
}
function showPanel() {
@ -66,13 +54,7 @@ function processData(data) {
.iphoneStyle({
checkedLabel: 'ON',
uncheckedLabel: 'OFF',
onChange: function(elem, value) {
$.ajax({
'method': 'GET',
'url': value ? '/relay/on' : '/relay/off',
'dataType': 'json'
});
}
onChange: doToggle
})
.iphoneStyle("refresh");
}
@ -94,7 +76,8 @@ function processData(data) {
var element = $("input[name=" + key + "]");
if (element.length > 0) {
if (element.attr('type') == 'checkbox') {
element.prop("checked", data[key] == 1)
element
.prop("checked", data[key] == 1)
.iphoneStyle({
resizeContainer: false,
resizeHandle: false,
@ -144,6 +127,7 @@ function init() {
$(".pure-menu-link").on('click', showPanel);
var host = window.location.hostname;
//host = "studiolamp.local";
websock = new WebSocket('ws://' + host + ':81/');
websock.onopen = function(evt) {};
websock.onclose = function(evt) {};


+ 0
- 84
code/src/webserver.ino View File

@ -34,28 +34,6 @@ String getContentType(String filename) {
return "text/plain";
}
void handleReconnect() {
DEBUG_MSG("[WEBSERVER] Request: /reconnect\n");
wifiDisconnect();
}
void handleReset() {
DEBUG_MSG("[WEBSERVER] Request: /reset\n");
ESP.reset();
}
void handleRelayOn() {
DEBUG_MSG("[WEBSERVER] Request: /relay/on\n");
switchRelayOn();
server.send(200, "text/plain", "ON");
}
void handleRelayOff() {
DEBUG_MSG("[WEBSERVER] Request: /relay/off\n");
switchRelayOff();
server.send(200, "text/plain", "OFF");
}
bool handleFileRead(String path) {
DEBUG_MSG("[WEBSERVER] Request: %s\n", (char *) path.c_str());
@ -77,70 +55,8 @@ bool handleFileRead(String path) {
}
void handleSave() {
DEBUG_MSG("[WEBSERVER] Request: /save\n");
bool dirty = false;
bool dirtyMQTT = false;
unsigned int network = 0;
for (unsigned int i=0; i<server.args(); i++) {
String key = server.argName(i);
String value = server.arg(i);
if (key == "ssid") {
key = key + String(network);
}
if (key == "pass") {
key = key + String(network);
++network;
}
if (value != getSetting(key)) {
setSetting(key, value);
dirty = true;
if (key.startsWith("mqtt")) dirtyMQTT = true;
}
}
server.send(202, "text/json", "{}");
if (dirty) {
saveSettings();
}
#if ENABLE_RF
rfBuildCodes();
#endif
#if ENABLE_EMON
setCurrentRatio(getSetting("emonRatio").toFloat());
#endif
// Reconfigure networks
wifiConfigure();
// Check if we should reconigure MQTT connection
if (dirtyMQTT) {
mqttDisconnect();
}
}
void webServerSetup() {
//SPIFFS.begin();
// Routes
server.on("/reconnect", HTTP_GET, handleReconnect);
server.on("/reset", HTTP_GET, handleReset);
server.on("/relay/on", HTTP_GET, handleRelayOn);
server.on("/relay/off", HTTP_GET, handleRelayOff);
server.on("/save", HTTP_POST, handleSave);
// Anything else
server.onNotFound([]() {


+ 88
- 2
code/src/websockets.ino View File

@ -27,6 +27,90 @@ bool webSocketSend(uint8_t num, char * payload) {
webSocket.sendTXT(num, payload);
}
void webSocketParse(uint8_t num, uint8_t * payload, size_t length) {
// Parse JSON input
char buffer[length+1];
memcpy(buffer, payload, length);
buffer[length] = 0;
DynamicJsonBuffer jsonBuffer;
JsonObject& root = jsonBuffer.parseObject(buffer);
if (!root.success()) {
DEBUG_MSG("[WEBSOCKET] Error parsing data\n");
return;
}
// Check actions
if (root.containsKey("action")) {
String action = root["action"];
DEBUG_MSG("[WEBSOCKET] Requested action: %s\n", action.c_str());
if (action.equals("reset")) ESP.reset();
if (action.equals("reconnect")) wifiDisconnect();
if (action.equals("on")) switchRelayOn();
if (action.equals("off")) switchRelayOff();
};
// Check config
if (root.containsKey("config") && root["config"].is<JsonArray&>()) {
JsonArray& config = root["config"];
DEBUG_MSG("[WEBSOCKET] Parsing configuration data\n");
bool dirty = false;
bool dirtyMQTT = false;
unsigned int network = 0;
for (unsigned int i=0; i<config.size(); i++) {
String key = config[i]["name"];
String value = config[i]["value"];
if (key == "ssid") {
key = key + String(network);
}
if (key == "pass") {
key = key + String(network);
++network;
}
if (value != getSetting(key)) {
setSetting(key, value);
dirty = true;
if (key.startsWith("mqtt")) dirtyMQTT = true;
}
}
// Save settings
if (dirty) {
saveSettings();
wifiConfigure();
#if ENABLE_RF
rfBuildCodes();
#endif
#if ENABLE_EMON
setCurrentRatio(getSetting("emonRatio").toFloat());
#endif
// Check if we should reconfigure MQTT connection
if (dirtyMQTT) {
mqttDisconnect();
}
}
}
}
void webSocketStart(uint8_t num) {
char app[64];
@ -100,10 +184,12 @@ void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t length
webSocketStart(num);
break;
case WStype_TEXT:
DEBUG_MSG("[WEBSOCKET] #%u sent: %s\n", num, payload);
//DEBUG_MSG("[WEBSOCKET] #%u sent: %s\n", num, payload);
webSocketParse(num, payload, length);
break;
case WStype_BIN:
DEBUG_MSG("[WEBSOCKET] #%u sent binary length: %u\n", num, length);
//DEBUG_MSG("[WEBSOCKET] #%u sent binary length: %u\n", num, length);
webSocketParse(num, payload, length);
break;
}


Loading…
Cancel
Save