Category Archives: arduino-esp8266

send string to esp8266 via android using telnet

Im trying to send a string to ESP8266.I want to send it through Android App and see the result in serial monitor of Arduino environment.

1 Im not able to connect to the server.

2 Also, Im getting nullPointerException as Attempt to invoke virtual method .

Heres the error Im unable to resolve in Android code:- I/OpenGLRenderer: Initialized EGL, version 1.4 D/OpenGLRenderer: Get maximum texture size. GL_MAX_TEXTURE_SIZE is 4096 enter code hereD/OpenGLRenderer: Enabling debug mode 0 I/Timeline: Timeline: Activity_idle id: [email protected] time:898904480 D/ViewRootImpl: ViewPostImeInputStage ACTION_DOWN E/PioneerController: Could not establish connection with server W/System.err: java.net.SocketException: Connection error... W/System.err: at com.example.manveenkaur.optimized.TelnetConnection.connect(TelnetConnection.java:29) W/System.err: at com.example.manveenkaur.optimized.TelnetClient.<init>(TelnetClient.java:27) W/System.err: at com.example.manveenkaur.optimized.PioneerController.<init>(PioneerController.java:24) W/System.err: at com.example.manveenkaur.optimized.MainActivity$1.doInBackground(MainActivity.java:82) W/System.err: at com.example.manveenkaur.optimized.MainActivity$1.doInBackground(MainActivity.java:78) W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:292) W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:237) W/System.err: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) W/System.err: at java.lang.Thread.run(Thread.java:818) E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #3 Process: com.example.manveenkaur.optimized, PID: 31509 java.lang.RuntimeException: An error occured while executing doInBackground() at android.os.AsyncTask$3.done(AsyncTask.java:304) at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355) at java.util.concurrent.FutureTask.setException(FutureTask.java:222) at java.util.concurrent.FutureTask.run(FutureTask.java:242) at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) at java.lang.Thread.run(Thread.java:818) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.InputStreamReader com.example.manveenkaur.optimized.TelnetClient.spawnSpy()' on a null object reference at com.example.manveenkaur.optimized.PioneerController.<init>(PioneerController.java:34) at com.example.manveenkaur.optimized.MainActivity$1.doInBackground(MainActivity.java:82) at com.example.manveenkaur.optimized.MainActivity$1.doInBackground(MainActivity.java:78) at android.os.AsyncTask$2.call(AsyncTask.java:292) at java.util.concurrent.FutureTask.run(FutureTask.java:237) at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)  at java.lang.Thread.run(Thread.java:818)  D/OpenGLRenderer: endAllStagingAnimators on 0xb84bb1f8 (RippleDrawable) with handle 0xb84b3950 I/Process: Sending signal. PID: 31509 SIG: 9 Application terminated. Here is the App code
MainActivity.java

public class MainActivity extends AppCompatActivity {
EditText editText_message;
Button button_send, button_connect, button_disconnect;
private Toast fastToast;
private static String SERVER_IP = "192.168.4.1";
private static int SERVERPORT = 1155;
private PioneerController clientPioneerController = null;
@SuppressLint("ShowToast")

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    editText_message = (EditText) findViewById(R.id.EditTextMessage);
    button_send = (Button) findViewById(R.id.sendButton);
    button_connect = (Button) findViewById(R.id.connectButton);
    button_disconnect = (Button) findViewById(R.id.disconnectButton);
}

public void onClickSend(View view) {
    if (clientPioneerController == null || !clientPioneerController.isConnected()) {
        toastFast("Not connected to a server");
        return;
    }


    clientPioneerController.sendCommand(editText_message.getText().toString());

}


void toastFast(String str) {

    fastToast.setText(str);
    fastToast.show();
}

public void onClickDisconnect(View view){
    if (clientPioneerController!=null && clientPioneerController.isConnected()) {
        if(disconnect()){
            toastFast("Disconnected from server");
        }
        else toastFast("Error disconnecting from server");
    }
    else{
        toastFast("Already disconnected");
    }
}
private boolean disconnect(){
    if(clientPioneerController.disconnect()){
        return true;
    }
    return false;
}

public void onClickConnect(View view){

    if(clientPioneerController!=null && clientPioneerController.isConnected())
        toastFast("Already connected");
    else {
        try{
            new AsyncTask<MainActivity, Void, Void>() {
                @Override
                protected Void doInBackground(MainActivity... act) {
                    try {
                        clientPioneerController = new PioneerController(SERVER_IP, SERVERPORT, act[0]);
                    } catch (IOException | InterruptedException e) {
                        e.printStackTrace();
                    }
                    return null;
                }

                @Override
                protected void onPostExecute(Void aVoid) {
                    toastFast("Hogya connect");

                }
            }.execute(this);
        }catch (Exception ex){
            ex.printStackTrace();
        }

    }
}
public void appendToConsole(String str){
    editText_message.append("\n");
    editText_message.append(str);
}
}

PioneerController.java

public class PioneerController {

private TelnetClient clientTelnetClient;
private MainActivity context;
protected static final String TAG = "PioneerController";


public PioneerController(String ip, int port, MainActivity con) throws     IOException, InterruptedException {
    TelnetClient connection = null;
    try {
        connection = new TelnetClient(ip, port);
    } catch (IOException e) {
        Log.e(TAG, "Could not establish connection with server");
        e.printStackTrace();
    }
    clientTelnetClient = connection;
    context = con;
    final InputStreamReader a = clientTelnetClient.spawnSpy();
    final BufferedReader reader = new BufferedReader(a);
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                while (!Thread.currentThread().isInterrupted()) {
                    final String line = reader.readLine();
                    if (line != null) {
                        context.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                context.appendToConsole(line);
                            }
                        });
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }).start();
}

public boolean isConnected() {
    return clientTelnetClient.isConnected();
}

public boolean disconnect() {
    return clientTelnetClient.disconnect();
}

public void sendCommand(String s) {
    clientTelnetClient.sendCommand(s);
}
}

TelnetClient.java

public class TelnetClient {
private TelnetConnection clientTelnetConnection;
private OutputStream outstream;
private org.apache.commons.net.telnet.TelnetClient rawConnection;
private InputStream instream;
private PipedInputStream spyReader;


public TelnetClient(String ip, int port) throws IOException {
    clientTelnetConnection = new TelnetConnection(ip, port);
    clientTelnetConnection.connect();
    rawConnection = clientTelnetConnection.getConnection();
    outstream = clientTelnetConnection.getOutput();
    instream = clientTelnetConnection.getReader();
}

public InputStreamReader spawnSpy() throws InterruptedException, IOException {
    PipedInputStream in = new PipedInputStream();
    PipedOutputStream out = new PipedOutputStream();
    in.connect(out);
    if (spyReader != null) {
        return spawnSpy(spyReader, out);
    } else {
        spyReader = in;
        return spawnSpy(instream, out);
    }
}

private InputStreamReader spawnSpy(InputStream in, PipedOutputStream   pipeout) throws InterruptedException {
    return new InputStreamReader(new TeeInputStream(in, pipeout));
}

public boolean isConnected() {
    return clientTelnetConnection.isConnected();
}

public boolean disconnect() {
    spyReader = null;
    return clientTelnetConnection.disconnect();
}

public boolean sendCommand(String cmd) {
    if (clientTelnetConnection == null || !clientTelnetConnection.isConnected()) {
        return false;
    }
    StringBuilder stringBuilder = new StringBuilder();

    stringBuilder.append(cmd.toUpperCase(Locale.ENGLISH));
    stringBuilder.append("\n\r");

    byte[] cmdbyte = stringBuilder.toString().getBytes();

    try {
        outstream.write(cmdbyte, 0, cmdbyte.length);
        outstream.flush();
        return true;
    } catch (Exception e1) {
        return false;
    }
}
}

TelnetConnection.java

public class TelnetConnection {
private TelnetClient client = null;
private final String SERVER_IP;
private final int SERVERPORT;

public TelnetConnection(String ip, int port) throws IOException {
    SERVER_IP = ip;
    SERVERPORT = port;
    client = new TelnetClient();
}

public void connect() throws IOException {
    try {
        client.connect(SERVER_IP, SERVERPORT);
    } catch (SocketException ex) {
        throw new SocketException("Connection error...");
    }
}

public TelnetClient getConnection() {
    return client;
}

public OutputStream getOutput() {
    return client.getOutputStream();
}

public BufferedInputStream getReader() {
    return new BufferedInputStream(client.getInputStream());
}

public boolean isConnected() {
    return client.isConnected();
}

public boolean disconnect() {
    try {
        client.disconnect();
    } catch (IOException e) {
        Log.e("Couldn't disconnect", e.getMessage());
        return false;
    }
    return true;
}


}