2

I am trying to write an Android app that could communicate over WiFi with ESP8266 module and exchange some simple, basic text data. My problem is I can not get any communication to work. I am not sure if my problem is with the Android code or some bad network configuration on the ESP.

On the Android side, I am using a standard TCPclient class code from this thread to transmit data. In this app I can get WiFi to work and to connect with ESP module using SSID and password authorization.

This is how my app looks like. enter image description here


Here is TCPclient.java class code I used.

package com.example.wexfo.wifi_com;

import ...

public class TCPclient {

    private String serverMessage;
    public static final String SERVER_IP = "192.168.0.102";
    public static final int SERVER_PORT = 4444;
    private OnMessageReceived messageListener = null;
    private boolean run = false;

    public static final String LOG_TAG = "TCP";


    PrintWriter out;
    BufferedReader in;


    public TCPclient(OnMessageReceived listener) {

        messageListener = listener;
    }


    public void sendMessage(String message) {

        if (out != null && !out.checkError()) {
            out.println(message);
            out.flush();
        }
    }


    public void stopClient() {

        run = false;

        if (out != null) {
            out.flush();
            out.close();
        }

        messageListener = null;
        in = null;
        out = null;
        serverMessage = null;
    }


    public void run() {

        run = true;

        try {
            InetAddress serverAddress = InetAddress.getByName(SERVER_IP);

            Log.e(LOG_TAG, "C: Connecting...");

            Socket socket = new Socket(serverAddress, SERVER_PORT);

            try {
                out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);

                Log.e(LOG_TAG, "C: Sent.");
                Log.e(LOG_TAG, "C: Done.");

                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

                while (run) {
                    serverMessage = in.readLine();

                    if (serverMessage != null && messageListener != null) {
                        messageListener.messageReceived(serverMessage);
                    }
                    //serverMessage = null;
                }
                Log.e(LOG_TAG, "S: Received message: '" + serverMessage + "'.");
            }
            catch (Exception e) {
                Log.e(LOG_TAG, "S: Error", e);
            }
            finally {
                socket.close();
            }
        }
        catch (Exception e) {
            Log.e(LOG_TAG, "C: Error", e);
        }
    }


    public interface OnMessageReceived {
        void messageReceived(String message);
    }
}


Below is MainActivity.java code.

package com.example.wexfo.wifi_com;

import ...

public class MainActivity extends AppCompatActivity {

    // Labels and edits
    private TextView connectionText;
    private EditText messageText;
    private TextView chatText;

    // Buttons
    private ToggleButton connectButton;
    private Button sendButton;

    // Wifi connection
    private static final String NET_SSID = "AI-THINKER";
    private static final String NET_PASSWD = "aiTHINKERwifi";
    private WifiConfiguration wifiConfig;
    private WifiManager wifiManager;

    // Other
    private TCPclient tcpClient;


    private void printChatLine(String text) {
        chatText.append("\n>> " + text);
    }

    private void printChatLine(String who, String text) {
        chatText.append("\n" + who + ": " + text);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        connectionText = (TextView) findViewById(R.id.connectionText);
        messageText = (EditText) findViewById(R.id.messageText);

        chatText = (TextView) findViewById(R.id.chatText);
        chatText.setMovementMethod(new ScrollingMovementMethod());
        printChatLine("chat test");


        // WiFi setup (authorization hard-coded for now)

        wifiConfig = new WifiConfiguration();
        wifiConfig.SSID = "\"" + NET_SSID + "\"";
        wifiConfig.preSharedKey = "\"" + NET_PASSWD + "\"";

        wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        wifiManager.addNetwork(wifiConfig);


        connectButton = (ToggleButton) findViewById(R.id.connectButton);
        connectButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (connectButton.isChecked()) {

                    connectionText.setText("Disconnect WiFi");

                    if (!wifiManager.isWifiEnabled())
                        wifiManager.setWifiEnabled(true);

                    List<WifiConfiguration> netList = wifiManager.getConfiguredNetworks();
                    for (WifiConfiguration net : netList) {
                        if (net.SSID != null && net.SSID.equals("\"" + NET_SSID + "\"")) {
                            wifiManager.disconnect();
                            wifiManager.enableNetwork(net.networkId, true);
                            wifiManager.reconnect();

                            break;
                        }
                    }

                    // Start server connection thread
                    new ConnectTask().execute("");
                }

                else {

                    connectionText.setText("Connect WiFi");

                    if (wifiManager.isWifiEnabled())
                        wifiManager.setWifiEnabled(false);

                    // Stop server connection thread
                    if (tcpClient != null)
                        tcpClient.stopClient();
                }
            }
        });


        sendButton = (Button) findViewById(R.id.sendButton);
        sendButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String message = messageText.getText().toString();

                printChatLine("ME", message);
                messageText.setText("");

                // Send message to ESP
                if (tcpClient != null)
                    tcpClient.sendMessage(message);

            }
        });
    }


    public class ConnectTask extends AsyncTask<String,String,TCPclient> {

        @Override
        protected TCPclient doInBackground(String... message) {
            tcpClient = new TCPclient(new TCPclient.OnMessageReceived() {
                @Override
                public void messageReceived(String message) {
                    publishProgress(message);
                }
            });

            tcpClient.run();

            return null;
        }

        @Override
        protected void onProgressUpdate(String... values) {
            super.onProgressUpdate(values);

            // Received message from ESP
            printChatLine("ES", values[0]);
        }
    }
}


Now the ESP8266 is set to work as SoftAP

AT+CWMODE?
+CWMODE:3

OK

Then I make a basic setup for multiple connections and start a new server.

AT+CIPSTA="192.168.0.102"

OK
AT+CIPMUX=1

OK
AT+CIPSERVER=1,4444

OK

Here is my IP data.

AT+CIFSR
+CIFSR:APIP,"192.168.4.1"
+CIFSR:APMAC,"1a:fe:34:8e:81:58"
+CIFSR:STAIP,"192.168.0.102"
+CIFSR:STAMAC,"18:fe:34:8e:81:58"

OK

Now when I run my app I can confirm I am connected to ESP's access point.

AT+CWLIF
192.168.4.2,00:27:15:77:82:02

OK

However there is no sign of an opened connection on the ESP and clicking SEND button does not make any data transfer. When I try to connect through ESP, I get an ERROR.

AT+CIPSTART=0,"TCP","192.168.4.2",4444
0,CLOSED

ERROR

My feeling is the app works fine but I do something horribly wrong on the ESP side and I can not figure out what it is. Maybe I have a wrong idea about the entire setup?

Community
  • 1
  • 1

0 Answers0