Skip to content

Commit

Permalink
Replace all ajax requests with websockets
Browse files Browse the repository at this point in the history
  • Loading branch information
Xose Pérez committed Oct 24, 2016
1 parent 07acfbf commit d34a15a
Show file tree
Hide file tree
Showing 3 changed files with 106 additions and 120 deletions.
52 changes: 18 additions & 34 deletions code/html/custom.js
Original file line number Diff line number Diff line change
@@ -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() {
Expand Down Expand Up @@ -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");
}
Expand All @@ -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,
Expand Down Expand Up @@ -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) {};
Expand Down
84 changes: 0 additions & 84 deletions code/src/webserver.ino
Original file line number Diff line number Diff line change
Expand Up @@ -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());
Expand All @@ -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([]() {

Expand Down
90 changes: 88 additions & 2 deletions code/src/websockets.ino
Original file line number Diff line number Diff line change
Expand Up @@ -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];
Expand Down Expand Up @@ -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;
}

Expand Down

0 comments on commit d34a15a

Please sign in to comment.