PL76
PL76

Reputation: 103

ESP8266 and Android socket won't communicate

I am having issues getting my Android device and an ESP8266 communicate using sockets. Here is the code for the ESP8266:

#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include <WebSocketsServer.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#include <Hash.h>

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

void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t length) {
  switch (type) {
    case WStype_DISCONNECTED:
      Serial.printf("[%u] Disconnected!\n", num);
      break;
    case WStype_CONNECTED: {
        IPAddress ip = webSocket.remoteIP(num);
        Serial.printf("[%u] Connected from %d.%d.%d.%d url: %s\n", num, ip[0], ip[1], ip[2], ip[3], payload);

        // send message to client
        webSocket.sendTXT(num, "Connected");
      }
      break;
    case WStype_TEXT:
      IPAddress ip = webSocket.remoteIP(num);
      Serial.printf("$%s?\n", payload);
      webSocket.sendTXT(num, payload, sizeof(payload), false);
      break;
  }
}

void setup() {
  Serial.begin(115200);
  Serial.println();
  Serial.println();
  Serial.println();
  for (uint8_t t = 4; t > 0; t--) {
    Serial.printf("[SETUP] BOOT WAIT %d...\n", t);
    Serial.flush();
    delay(1000);
  }
  Serial.println("Starting AP");
  WiFi.mode(WIFI_AP);
  WiFi.softAP("Alpine_SIM_CNTRL", "12345678");
  Serial.println("AP Started");

  Serial.println("Starting Socket");
  // start webSocket server
  webSocket.begin();
  webSocket.onEvent(webSocketEvent);
  Serial.println("Socket Started");

  if (MDNS.begin("simcontrol")) {
    Serial.println("MDNS responder started");
  }
  Serial.println("Starting Server");
  //handle index
  server.on(
  "/", []() {
    server.send(200, "text/plain", "You are connected");
  });

  server.begin();
  Serial.println("Server Started");

  //Add service to MDNS
  MDNS.addService("http", "tcp", 80);
  MDNS.addService("ws", "tcp", 81);
}

void loop() {
  webSocket.loop();
  server.handleClient();
}

And below is the Java code for the socket for Android:

public class WriteToServer extends AsyncTask<MyTaskParams, Void, String> {
  Context context;
  Socket socket;

  public WriteToServer(MyTaskParams Params) {
  }

  @Override
  protected String doInBackground(MyTaskParams... params) {
    socket = null;
    DataInputStream in = null;
    DataOutputStream out = null;
    context = params[0].context;
    String command = params[0].cmd;
    String response = null;
    try {
      socket = new Socket("192.168.4.1", 81);
      out = new DataOutputStream(socket.getOutputStream());
      in = new DataInputStream(socket.getInputStream());
      out.writeUTF(command);
      Log.i("Command", "Command sent: " + command);
      while (in.available() > 0) {
        response = in.readUTF();
      }
    } catch (IOException e) {
      e.printStackTrace();
      Log.e("Error", "There was an error writing to the socket. Thrown IO exception");
    } finally {
      if (socket != null) {
        try {
          Log.i("INFO", "closing the socket");
          socket.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
      if (in != null) {
        try {
          in.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
      if (out != null) {
        try {
          out.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
    return response;
  }
}

Can anyone please point out why I am not getting any communication? Using the debugger in Android Studio I can see that the socket is connected to the correct address and port, but when I send something to the ESP it does not print out what I sent or respond back. If I connect to the ESP with my PC and type in 192.168.4.1:81/*** I get a response that states "This is a websocket server only". So I think the socket server should be up and running based on this. Any help would be appreciated.

[EDIT] Thanks to response from Codo I know I was using two different socket technologies on the server and client. I am now using Java WebSockets. I can now see on the ESP that the Android device is trying to connect but the ESP closes the connection right away. Below is from Debug of ESP device:

[WS-Server][0] new client from 192.168.4.2
[WS-Server][0][handleHeader] RX: GET / HTTP/1.1
[WS-Server][0][handleHeader] RX: Connection: Upgrade
[WS-Server][0][handleHeader] RX: Host: 192.168.4.1:81
[WS-Server][0][handleHeader] RX: Sec-WebSocket-Key: LmtO2xH7n9k+KKJNN/4+GA==
[WS-Server][0][handleHeader] RX: Sec-WebSocket-Version: 8
[WS-Server][0][handleHeader] RX: Upgrade: websocket
[WS-Server][0][handleHeader] Header read fin.
[WS-Server][0][handleHeader]  - cURL: /
[WS-Server][0][handleHeader]  - cIsUpgrade: 1
[WS-Server][0][handleHeader]  - cIsWebsocket: 1
[WS-Server][0][handleHeader]  - cKey: LmtO2xH7n9k+KKJNN/4+GA==
[WS-Server][0][handleHeader]  - cProtocol:
[WS-Server][0][handleHeader]  - cExtensions: <null>
[WS-Server][0][handleHeader]  - cVersion: 8
[WS-Server][0][handleHeader]  - base64Authorization:
[WS-Server][0][handleHeader]  - cHttpHeadersValid: 1
[WS-Server][0][handleHeader]  - cMandatoryHeadersCount: 0
[WS-Server][0][handleHeader] no Websocket connection close.
[WS-Server][0] client disconnected.

Can anyone help me figure out why the ESP is closing the connection?

[Update and Fix] I have fixed the issue. When creating the socket on the Android device using org.java.websockets I was using:

mWebSocketClient = new WebSocketClient(uri)

I found that if you don't assign the draft version when creating the socket that it defaults to websockets Version 8 which won't work with the ESP8266(at least not with the arduinowebsockets library. I had to create the socket using the following:

mWebSocketClient = new WebSocketClient(uri, new Draft_17())

After this the websocket is created as version 13 which now works.

The issue is now fixed!

Upvotes: 2

Views: 1824

Answers (1)

PL76
PL76

Reputation: 103

You are mixing two different concepts: In Java, you use the rather low-level Unix sockets and on the ESP you use WebSocket, which are closely related to HTTP. Get a proper WebSocket client library for Java. – Codo Jan 4 at 17:33

Upvotes: 3

Related Questions