0
\$\begingroup\$

I have a NodeMCU which is connected to 4 LEDs. If i hit a URL like 192.168.1.2/relay1on then my relay 1 gets switched on and the LED connected to it lightens up. What i want to do is i want to know from my android application that is relay1 ON or OFF For ex. When i will start my Android App in the background it will hit a url and in return NodeMCU will send a response to my Android App that the Relay 1 is on and i will get that information on my Android App so that i can process it further. Any help will be appreciated. Thank you.

\$\endgroup\$
1
\$\begingroup\$

There are lots of examples in the internet. Look it up on goolge with something like ESP8266 LED webserver or ESP8266 Blynk. There they are mostly showing how to build this and access to your NodeMcu over e.g. Google Chrome. If you want to do it with your own Android Application it is a little more tricky. Look it up here or here.

For sending data from the server to the client you should consider using javascript. here is a example code from my ESP8266 Relais control. I took the code from here and modified it to my preferences. main:

 #include <ESP8266WiFi.h>
    #include <ESP8266WebServer.h>
    const char* ssid = "SSID";
    const char* password = "PASSWORD";

boolean LEDstate = false;

#include "functions.h"
int LED = 2;
int OUT = 5;

IPAddress ip(10, 0, 0, 99);
IPAddress gateway(10, 0, 0, 1);
IPAddress subnet(255, 255, 255, 0);

void setup() {
    pinMode(LED, OUTPUT);
    Serial.begin(115200); delay(100);
    Serial.print("... Attempting to log into router... \r\n");

    WiFi.begin(ssid, password);

    WiFi.config(ip, gateway, subnet);

    while (WiFi.status() != WL_CONNECTED) delay(500);
    WiFi.mode(WIFI_STA);

    Serial.println("\n\nBOOTING ESP8266 ...");
    Serial.print("Connected to ");
    Serial.println(ssid);
    Serial.println("Station IP address: ");
    Serial.println(WiFi.localIP());

    server.on("/", handleWebsite);
    server.on("/setESPval", handleESPval);
  server.on("/xml", handleXML);
    server.begin();
}

void loop() {
    server.handleClient();
 buildXML();
    delay(100);
    if (LEDstate) {
        digitalWrite(LED, HIGH);
    }
    else {
        digitalWrite(LED, LOW);
    }
}

functions.h

ESP8266WebServer server(80);
String webSite;
String javaScript;
String XML;
void buildJavascript() {
  javaScript = "<SCRIPT>\n";
  javaScript += "xmlHttp=createXmlHttpObject();\n";

  javaScript += "function createXmlHttpObject(){\n";
  javaScript += "  if(window.XMLHttpRequest){\n";
  javaScript += "    xmlHttp=new XMLHttpRequest();\n";
  javaScript += "  }else{\n";
  javaScript += "    xmlHttp=new ActiveXObject('Microsoft.XMLHTTP');\n";
  javaScript += "  }\n";
  javaScript += "  return xmlHttp;\n";
  javaScript += "}\n";

  javaScript += "function process(){\n";
  javaScript += "  if(xmlHttp.readyState==0||xmlHttp.readyState==4){\n";
  javaScript += "    xmlHttp.onreadystatechange=function(){\n";
  javaScript += "      if(xmlHttp.readyState==4&&xmlHttp.status==200){\n";
  javaScript += "        xmlDoc=xmlHttp.responseXML;\n";
  javaScript += "         console.log(xmlDoc.getElementsByTagName('mt')[0]);\n";

  javaScript += "        xmlmsg=xmlDoc.getElementsByTagName('mt')[0].firstChild.nodeValue;\n";
  javaScript += "        document.getElementById('runtime').innerHTML=xmlmsg;\n";
  javaScript += "        xmlmsg=xmlDoc.getElementsByTagName('state')[0].firstChild.nodeValue;\n";
  javaScript += "        document.getElementById('ledstate').innerHTML=xmlmsg;\n";
  javaScript += "      }\n";
  javaScript += "    }\n";
  javaScript += "    xmlHttp.open('PUT','xml',true);\n";
  javaScript += "    xmlHttp.send(null);\n";
  javaScript += "  }\n";
  javaScript += "  setTimeout('process()',1000);\n";
  javaScript += "}\n";

  javaScript += " function sendRequest(nr) {\n";

  //javaScript += "alert(nr);";
  javaScript += "if (xmlHttp.readyState == 0 || xmlHttp.readyState == 4) {\n";
   javaScript += "        xmlDoc=xmlHttp.responseXML;\n";
  javaScript += "        xmlmsg=xmlDoc.getElementsByTagName('mt')[0].firstChild.nodeValue;\n";
  javaScript += "        document.getElementById('runtime').innerHTML=xmlmsg;\n";
  javaScript += "     xmlHttp.open('PUT', 'setESPval?fnc=' + nr, true);\n";
  javaScript += "     xmlHttp.send(null);\n";
  javaScript += "}\n}";
  javaScript += "</SCRIPT>\n";

  Serial.println("JavaScript built");
}

void buildWebsite() {
  buildJavascript();
  webSite = "<!DOCTYPE HTML>\n";
  webSite += "<META name='viewport' content='width=device-width, initial-scale=1'>\n";
  webSite += javaScript;
    webSite += "<BODY onload='process()'>\n";
  webSite += "Runtime = <A ID='runtime'></A>\n";
  webSite += "LEDstate = <A ID='ledstate'></A>\n";
  webSite += "<br><button onclick='sendRequest(0)'>Funktion 1</button>\n";
  webSite += "<button onclick='sendRequest(1)'>Funktion 2</button>\n";
  webSite += "</HTML>\n";

//  webSite += "<!DOCTYPE html><html><head>    <title>JavaScript View</title>    <script type="text/javascript">        function showToast(){            var message = document.getElementById("message").value;           var lengthLong = document.getElementById("length").checked;           app.makeToast(message, lengthLong);            return false;        }       /*             Call the 'showToast' method when the form gets             submitted (by pressing button or return key on keyboard).          */        window.onload = function(){          var form = document.getElementById("form");            form.onsubmit = showToast;       }   </script></head><body><form id="form">    Message: <input id="message" name="message" type="text"/><br />    Long: <input id="length" name="length" type="checkbox" /><br />    <input type="submit" value="Make Toast" /></form></body></html>"
  Serial.println("HTML built");
}

String millis2time() {
  String Time = "";
  unsigned long ss;
  byte mm, hh;
  ss = millis() / 1000;
  hh = ss / 3600;
  mm = (ss - hh * 3600) / 60;
  ss = (ss - hh * 3600) - mm * 60;
  if (hh < 10)Time += "0";
  Time += (String)hh + ":";
  if (mm < 10)Time += "0";
  Time += (String)mm + ":";
  if (ss < 10)Time += "0";
  Time += (String)ss;
  return Time;
}

int i = 0;
void buildXML() {
  XML = "<?xml version='1.0'?>";
  XML += "<xml>";
  XML += "<mt>";
  XML += millis2time();
  XML += "</mt>";
  XML += "<state>";
  XML += LEDstate;
  XML += "</state>";
  XML += "</xml>";
  //Serial.println(XML);
}

void handleWebsite() {
  buildWebsite();
  server.send(200, "text/html", webSite);
}

void handleXML() {
  buildXML();
  server.send(200, "text/xml", XML);
  Serial.println("Website handeled");
}


void handleESPval() {
  //Serial.println("HANDLE");
  if (server.arg("fnc").toInt() == 0) {
    Serial.println("BTN1 pressed");
    delay(100);
    LEDstate = false;
  }
  else if (server.arg("fnc").toInt() == 1) {
    Serial.println("BTN2 pressed");
    delay(100);
    LEDstate = true;
  }
  Serial.println(LEDstate);
  server.send(200, "text/xml", XML);
}
\$\endgroup\$
3
  • \$\begingroup\$ But how to send data from NodeMcu to my android App ? Can you give some Code Snippets. \$\endgroup\$ – Akshay Avhad May 11 '18 at 17:47
  • \$\begingroup\$ I editet my answer above. Altough this is rather a question for Arduino StackExchange than Electronics... \$\endgroup\$ – Ribisl May 11 '18 at 20:04
  • \$\begingroup\$ This fits here better than arduino. \$\endgroup\$ – Passerby May 11 '18 at 20:13

Not the answer you're looking for? Browse other questions tagged or ask your own question.