-->
Page 1 of 1

How to send Temp data into websocket

PostPosted: Wed Nov 09, 2016 5:50 pm
by migbur
HI
I have connected an ESP-12E(NodeMCU), whit arduino nano using I2C protocol, this work fine, inclusive eh ESP is working as a server a I able to turn on a LED, and show titles and so on.
My problem is when I tried to send the Temp data to client, dont know how to do it.
Im using arduino IDE.
Please any sugestion is welcome.
this is de server code:

Code: Select all/*
   ESP8266 Web server with Web Socket

   The web server keeps all clients' LED status up to date and any client may
   turn the LED on or off.

   Ultima modificacion: 6/11/2016
*/

#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include <WebSocketsServer.h>
#include <Hash.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#include<SoftwareSerial.h>
#include <Wire.h>    //declare I2C library function
#define I2C_Arduino 6
unsigned int lectura;
static const char ssid[] = "********";
static const char password[] = "***************";
MDNSResponder mdns;

static void writeLED(bool);
int incomingByte = 0;
ESP8266WiFiMulti WiFiMulti;

ESP8266WebServer server(80);
WebSocketsServer webSocket = WebSocketsServer(81);

static const char PROGMEM INDEX_HTML[] = R"rawliteral(
<!DOCTYPE html>
<html>
<head>
<meta name = "viewport" content = "width = device-width, initial-scale = 1.0, maximum-scale = 1.0, user-scalable=0">
<title>Acuario Control Demo</title>
<style>
body {
       
       font-family: Arial, Helvetica, Sans-Serif;
       background-color: grey;
       margin: 10;
       padding: 10;
       min-width: 90%;
       width: 90%;
       max-width: 90%;
       min-height: 100%;
       height: 100%;
       max-height: 100%;
}
h1    {color: blue;}
#div1 {
       
       text-align: center;
       border-radius: 25px;
       background: #73AD21;
       padding: 20px;
       width: 600px;
       height: 150px;
       
      }
</style>
<script>
var websock;
var output;

//var test = document.getElementById("Arduino");
//    test.innerHTML = "Nuevo Hola Mundo";
   
function start() {
  websock = new WebSocket('ws://' + window.location.hostname + ':81/');
  websock.onopen = function(evt) { console.log('websock open'); };
  websock.onclose = function(evt) { console.log('websock close'); };
  websock.onerror = function(evt) { console.log(evt); };
  websock.onmessage = function(evt) {
    console.log(evt);
   
   //var temp = "TEMP 24";
   // document.form_reloj.reloj.value = temp;
   //var data =document.getElementById("Arduino");
   //data.innerHTML = temp;
   
    //var test = document.getElementById("Arduino");
    //test.innerHTML = c;   
    //var canvas = document.getElementById("canvas").getContext("2d");
    // canvas.fillText(counter,60,60);
    var e = document.getElementById('ledstatus');
    output = document.getElementById("output");
    output_text = document.getElementById("textField1");
       
      if (evt.data === 'ledon') {
      e.style.color = 'red';
      output_text.style.color ='red';
      var state= "LED is ON"
      output_text.value=state;
      //canvas.beginPath();
      //canvas.fillText(state,10,50);
      //canvas.stroke();
      //writeToScreen("Hola Mundo");
       
    }
    else if (evt.data === 'ledoff') {
      e.style.color = 'black';
      //canvas.fillText(state,10,50);
      output_text.style.color ='black';
      var state= "LED is OFF"
      output_text.value=state;
      //output_text.innerHTML = LED is OFF;
      //canvas.beginPath();
      //canvas.fillText(state,10,50);
      //canvas.stroke();
     
    }
    else {
      console.log('unknown event');
      document.getElementById("text").value = "";
    }
   
  };
}
function buttonclick(e) {
  websock.send(e.id);
}
function writeToScreen(message) {
         var pre = document.createElement("p");
         pre.style.wordWrap = "break-word";
         pre.innerHTML = message;
         output.appendChild(pre);
       
      }
     
</script>
</head>
<body onload="javascript:start();">
<div id="div1">
<h1 id="text">AQUARIO CONTROL DEMO</h1>
<h2 id="Arduino">Temp</h2>
<form name="form_reloj">
<input type="text" name="reloj" size="10">
</form>
</div>
<input id="textField1" type="text" value="" align="right" size="13"/><br>
<div id="ledstatus"><b>LED STATE</b></div>
<button id="ledon"  type="button" onclick="buttonclick(this);">On</button>
<button id="ledoff" type="button" onclick="buttonclick(this);">Off</button>
</body>
</html>
)rawliteral";
 
// GPIO#0 is for Adafruit ESP8266 HUZZAH board. Your board LED might be on 13.
const int LEDPIN = 12;
// Current LED status
bool LEDStatus;
//char data= c;
// Commands sent through Web Socket
const char LEDON[] = "ledon";
const char LEDOFF[] = "ledoff";

void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t length)
{
 
  Serial.printf("webSocketEvent(%d, %d, ...)\r\n", num, type);
  switch(type) {
    case WStype_DISCONNECTED:
      Serial.printf("[%u] Disconnected!\r\n", num);
      break;
    case WStype_CONNECTED:
      {
        IPAddress ip = webSocket.remoteIP(num);
        Serial.printf("[%u] Connected from %d.%d.%d.%d url: %s\r\n", num, ip[0], ip[1], ip[2], ip[3], payload);
        // Send the current LED status
        if (LEDStatus) {
          webSocket.sendTXT(num, LEDON, strlen(LEDON));
        }
        else {
          webSocket.sendTXT(num, LEDOFF, strlen(LEDOFF));
        }
      }
      break;
    case WStype_TEXT:
      Serial.printf("[%u] get Text: %s\r\n", num, payload);
      // Para encender el LED
      if (strcmp(LEDON, (const char *)payload) == 0) {
        writeLED(true);
      }
      else if (strcmp(LEDOFF, (const char *)payload) == 0) {
        writeLED(false);
      }
           
      else {
        Serial.println("Unknown command");
      }
      // send data to all connected clients
      webSocket.broadcastTXT(payload, length);
      break;
    case WStype_BIN:
      Serial.printf("[%u] get binary length: %u\r\n", num, length);
      hexdump(payload, length);

      // echo data back to browser
      webSocket.sendBIN(num, payload, length);
      break;
    default:
      Serial.printf("Invalid WStype [%d]\r\n", type);
      break;
  }
     
}

void handleRoot()
{
  server.send(200, "text/html", INDEX_HTML);
}

void handleNotFound()
{
  String message = "File Not Found\n\n";
  message += "URI: ";
  message += server.uri();
  message += "\nMethod: ";
  message += (server.method() == HTTP_GET)?"GET":"POST";
  message += "\nArguments: ";
  message += server.args();
  message += "\n";
  for (uint8_t i=0; i<server.args(); i++){
    message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
  }
  //server.send_P(404, "text/plain", message);
}

static void writeLED(bool LEDon)
{
  LEDStatus = LEDon;
    if (LEDon) {
    digitalWrite(LEDPIN, 1);
  }
  else {
    digitalWrite(LEDPIN, 0);
  }
}

void setup()
{
 
  pinMode(LEDPIN, OUTPUT);
  writeLED(false);

  Serial.begin(115200);
 
 
  Serial.setDebugOutput(true);

  Serial.println();
  Serial.println();
  Serial.println();

  for(uint8_t t = 4; t > 0; t--) {
    Serial.printf("[SETUP] BOOT WAIT %d...\r\n", t);
    Serial.flush();
    delay(1000);
  }

 WiFiMulti.addAP(ssid, password);
//WiFiMulti.addAP("MOVISTAR_0817", "9R9h4tWx2ieW3RH8XXvF");
  while(WiFiMulti.run() != WL_CONNECTED) {
    Serial.print(".");
    delay(100);
   
  }

  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());

  if (mdns.begin("espWebSock", WiFi.localIP())) {
    Serial.println("MDNS responder started");
    mdns.addService("http", "tcp", 80);
    mdns.addService("ws", "tcp", 81);
  }
  else {
    Serial.println("MDNS.begin failed");
  }
  Serial.print("Connect to http://espWebSock.local or http://");
  Serial.println(WiFi.localIP());

  server.on("/", handleRoot);
  server.onNotFound(handleNotFound);

  server.begin();

  webSocket.begin();
  webSocket.onEvent(webSocketEvent);
  Wire.begin(0,2);//pin D3: sda,pin:D4 scl. join the I2C bus as master
  Serial.println("I2C Master READY!");
}
String message;
void loop()
{
  webSocket.loop();
  server.handleClient();
    Wire.requestFrom(I2C_Arduino, 1); 
    while (Wire.available()) { // slave may send less than requested
    //char c = Wire.read(); // receive a byte as character
    lectura = Wire.read(); // receive a byte as character
    //Serial.print(c);         // print the character
   // Serial.print(lectura);
  }
  Serial.print("Room temp:");
  Serial.print(lectura);
  Serial.println("C");
  delay(500);
 
 
}