From 5993271979b128ec0586ab93af5553c343185dca Mon Sep 17 00:00:00 2001 From: Anashuman Singh Date: Sun, 3 Nov 2024 12:42:05 +0530 Subject: [PATCH] feat: added support for wireless communication using ESP01 --- .../io/pslab/communication/HttpAsyncTask.java | 27 +++--- .../io/pslab/communication/PacketHandler.java | 37 ++++---- .../io/pslab/communication/ScienceLab.java | 25 +++--- .../io/pslab/communication/SocketClient.java | 88 +++++++++++++++++++ .../java/io/pslab/fragment/ESPFragment.java | 29 +++--- 5 files changed, 150 insertions(+), 56 deletions(-) create mode 100644 app/src/main/java/io/pslab/communication/SocketClient.java diff --git a/app/src/main/java/io/pslab/communication/HttpAsyncTask.java b/app/src/main/java/io/pslab/communication/HttpAsyncTask.java index 4aae41545..6be4bd015 100644 --- a/app/src/main/java/io/pslab/communication/HttpAsyncTask.java +++ b/app/src/main/java/io/pslab/communication/HttpAsyncTask.java @@ -1,6 +1,7 @@ package io.pslab.communication; import android.os.AsyncTask; +import android.util.Log; import org.json.JSONException; import org.json.JSONObject; @@ -11,30 +12,34 @@ public class HttpAsyncTask extends AsyncTask { - private HttpHandler mHttpHandler; - private HttpCallback mHttpCallback; + private SocketClient socketClient; + private HttpCallback mHttpCallback; + private int bytesToRead; - public HttpAsyncTask(String baseIP, HttpCallback httpCallback) { - mHttpHandler = new HttpHandler(baseIP); + public HttpAsyncTask(HttpCallback httpCallback, int bytesToRead) { + socketClient = SocketClient.getInstance(); mHttpCallback = httpCallback; + this.bytesToRead = bytesToRead; } @Override protected Void doInBackground(byte[]... data) { - int res = 0; + int bytesRead = 0; try { - if (data.length != 0) { - res = mHttpHandler.write(data[0]); + if (data[0].length != 0) { + socketClient.write(data[0]); } else { - res = mHttpHandler.read(); + bytesRead = socketClient.read(bytesToRead); } - } catch (IOException | JSONException e) { + } catch (IOException e) { mHttpCallback.error(e); e.printStackTrace(); } - if (res == 1) { - mHttpCallback.success(mHttpHandler.getReceivedData()); + if (data[0].length == 0 && bytesRead == bytesToRead) { + mHttpCallback.success(socketClient.getReceivedData()); + } else if (data[0].length != 0) { + mHttpCallback.success(new byte[]{}); } else { mHttpCallback.error(new Exception()); } diff --git a/app/src/main/java/io/pslab/communication/PacketHandler.java b/app/src/main/java/io/pslab/communication/PacketHandler.java index 709b26659..42b8825e0 100644 --- a/app/src/main/java/io/pslab/communication/PacketHandler.java +++ b/app/src/main/java/io/pslab/communication/PacketHandler.java @@ -41,8 +41,10 @@ public PacketHandler(int timeout, CommunicationHandler communicationHandler) { this.connected = false; this.timeout = timeout; this.mCommandsProto = new CommandsProto(); - this.mCommunicationHandler = communicationHandler; - connected = (mCommunicationHandler.isConnected() || ScienceLabCommon.isWifiConnected()); + if (communicationHandler != null) { + this.mCommunicationHandler = communicationHandler; + } + connected = (ScienceLabCommon.isWifiConnected() || mCommunicationHandler.isConnected()); } public boolean isConnected() { @@ -247,49 +249,44 @@ public byte[] sendBurst() { public int commonRead(int bytesToRead) throws IOException { final int[] bytesRead = {0}; - if (mCommunicationHandler.isConnected()) { + if (mCommunicationHandler != null && mCommunicationHandler.isConnected()) { bytesRead[0] = mCommunicationHandler.read(buffer, bytesToRead, timeout); } else if (ScienceLabCommon.isWifiConnected()) { - httpAsyncTask = new HttpAsyncTask(ScienceLabCommon.getEspIP(), new HttpCallback() { + httpAsyncTask = new HttpAsyncTask(new HttpCallback() { @Override - public void success(JSONObject jsonObject) { - try { - //Server will send byte array - buffer = (byte[]) jsonObject.get("data"); - bytesRead[0] = buffer.length; - } catch (JSONException e) { - e.printStackTrace(); - } + public void success(byte[] t1) { + System.arraycopy(t1, 0, buffer, 0, bytesToRead); + bytesRead[0] = bytesToRead; + Log.d(TAG, "Read: " + t1.length); } @Override public void error(Exception e) { Log.e(TAG, "Error reading data over ESP"); } - }); + }, bytesToRead); httpAsyncTask.execute(new byte[]{}); } return bytesRead[0]; } public void commonWrite(byte[] data) throws IOException { - if (mCommunicationHandler.isConnected()) { + if (mCommunicationHandler != null && mCommunicationHandler.isConnected()) { mCommunicationHandler.write(data, timeout); } else if (ScienceLabCommon.isWifiConnected()) { - httpAsyncTask = new HttpAsyncTask(ScienceLabCommon.getEspIP(), new HttpCallback() { + httpAsyncTask = new HttpAsyncTask(new HttpCallback() { @Override - public void success(JSONObject jsonObject) { - Log.v(TAG, "write response:" + jsonObject.toString()); + public void success(byte[] t1) { + Log.d(TAG, "Data written successfully"); } @Override public void error(Exception e) { Log.e(TAG, "Error writing data over ESP"); } - }); - + }, 0); httpAsyncTask.execute(data); } - } + } diff --git a/app/src/main/java/io/pslab/communication/ScienceLab.java b/app/src/main/java/io/pslab/communication/ScienceLab.java index 7b8430d1c..bf49ab468 100644 --- a/app/src/main/java/io/pslab/communication/ScienceLab.java +++ b/app/src/main/java/io/pslab/communication/ScienceLab.java @@ -36,6 +36,7 @@ import io.pslab.communication.peripherals.I2C; import io.pslab.fragment.HomeFragment; import io.pslab.others.InitializationVariable; +import io.pslab.others.ScienceLabCommon; /** * Created by viveksb007 on 28/3/17. @@ -79,15 +80,19 @@ public class ScienceLab { public ScienceLab(CommunicationHandler communicationHandler) { mCommandsProto = new CommandsProto(); mAnalogConstants = new AnalogConstants(); - mCommunicationHandler = communicationHandler; - if (isDeviceFound() && MainActivity.hasPermission) { - try { - mCommunicationHandler.open(1000000); - //Thread.sleep(200); - mPacketHandler = new PacketHandler(50, mCommunicationHandler); - } catch (IOException | NullPointerException e) { - e.printStackTrace(); + if (communicationHandler != null) { + mCommunicationHandler = communicationHandler; + if (isDeviceFound() && MainActivity.hasPermission) { + try { + mCommunicationHandler.open(1000000); + //Thread.sleep(200); + mPacketHandler = new PacketHandler(50, mCommunicationHandler); + } catch (IOException | NullPointerException e) { + e.printStackTrace(); + } } + } else { + mPacketHandler = new PacketHandler(50, null); } if (isConnected()) { initializeVariables(); @@ -745,7 +750,7 @@ public boolean isDeviceFound() { * @return true is device is connected; false otherwise */ public boolean isConnected() { - return mCommunicationHandler.isConnected(); + return (ScienceLabCommon.isWifiConnected || mCommunicationHandler.isConnected()); } /* DIGITAL SECTION */ @@ -2157,7 +2162,7 @@ public void resetDevice() { * @throws IOException * @throws InterruptedException */ - public void enterBootloader() throws IOException, InterruptedException { + public void enterBootloader() throws Exception { mCommunicationHandler.close(); mCommunicationHandler.open(460800); mPacketHandler = new PacketHandler(50, mCommunicationHandler); diff --git a/app/src/main/java/io/pslab/communication/SocketClient.java b/app/src/main/java/io/pslab/communication/SocketClient.java new file mode 100644 index 000000000..bcbc4388f --- /dev/null +++ b/app/src/main/java/io/pslab/communication/SocketClient.java @@ -0,0 +1,88 @@ +package io.pslab.communication; + +import android.util.Log; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.Socket; + +public class SocketClient { + + public static final String TAG = "SocketClient"; + private static SocketClient socketClient = null; + private Socket socket; + private OutputStream outputStream; + private InputStream inputStream; + private boolean isConnected = false; + + public static final int DEFAULT_READ_BUFFER_SIZE = 32 * 1024; + + private byte[] buffer = new byte[DEFAULT_READ_BUFFER_SIZE]; + + private byte[] receivedData; + + private SocketClient() { + } + + public void openConnection(String ip, int port) throws IOException { + socket = new Socket(ip, port); + outputStream = socket.getOutputStream(); + inputStream = socket.getInputStream(); + if (!socket.isConnected()) { + isConnected = false; + return; + } + isConnected = true; + } + + public static SocketClient getInstance() { + if (socketClient == null) { + socketClient = new SocketClient(); + } + return socketClient; + } + + public boolean isConnected() { + return isConnected; + } + + public void write(byte[] data) throws IOException { + if (isConnected && socketClient.isConnected && outputStream != null) { + outputStream.write(data); + } + } + + public int read(int bytesToRead) throws IOException { + int bytesRead = 0; + if (isConnected && socketClient.isConnected && inputStream != null) { + bytesRead = inputStream.read(buffer, 0, bytesToRead); + + if (bytesRead > 0) { + receivedData = new byte[bytesRead]; + System.arraycopy(buffer, 0, receivedData, 0, bytesRead); + } else { + Log.e(TAG, "Read Error: " + bytesToRead); + return bytesRead; + } + } + return bytesRead; + } + + public byte[] getReceivedData() { + return receivedData; + } + + public void closeConnection() { + try { + if (isConnected) { + inputStream.close(); + outputStream.close(); + socket.close(); + isConnected = false; + } + } catch (Exception e) { + e.printStackTrace(); + } + } +} diff --git a/app/src/main/java/io/pslab/fragment/ESPFragment.java b/app/src/main/java/io/pslab/fragment/ESPFragment.java index 3c13b32ae..f3a669ccd 100644 --- a/app/src/main/java/io/pslab/fragment/ESPFragment.java +++ b/app/src/main/java/io/pslab/fragment/ESPFragment.java @@ -23,6 +23,8 @@ import java.io.IOException; import io.pslab.R; +import io.pslab.communication.CommunicationHandler; +import io.pslab.communication.SocketClient; import io.pslab.others.CustomSnackBar; import io.pslab.others.ScienceLabCommon; import okhttp3.OkHttpClient; @@ -84,7 +86,7 @@ public void onResume() { getDialog().getWindow().setAttributes((android.view.WindowManager.LayoutParams) params); } - private class ESPTask extends AsyncTask { + private class ESPTask extends AsyncTask { @Override protected void onPreExecute() { @@ -93,35 +95,32 @@ protected void onPreExecute() { } @Override - protected String doInBackground(Void... voids) { - String result = ""; + protected Boolean doInBackground(Void... voids) { try { - OkHttpClient client = new OkHttpClient(); - Request request = new Request.Builder() - .url("http://" + espIPAddress) - .build(); - Response response = client.newCall(request).execute(); - if (response.code() == 200) { + SocketClient socketClient = SocketClient.getInstance(); + socketClient.openConnection(espIPAddress, 80); + if (socketClient.isConnected()) { ScienceLabCommon.setIsWifiConnected(true); ScienceLabCommon.setEspBaseIP(espIPAddress); + return true; } - result = response.body().string(); - } catch (IOException e) { + } catch (Exception e) { e.printStackTrace(); } - return result; + return false; } @Override - protected void onPostExecute(String result) { + protected void onPostExecute(Boolean result) { espConnectProgressBar.setVisibility(View.GONE); espConnectBtn.setVisibility(View.VISIBLE); Activity activity; - if (result.isEmpty() && ((activity = getActivity()) != null)) { + if (!result && ((activity = getActivity()) != null)) { CustomSnackBar.showSnackBar(activity.findViewById(android.R.id.content), getString(R.string.incorrect_IP_address_message), null, null, Snackbar.LENGTH_SHORT); } else { - Log.v("Response", result); + Log.v("ESPFragment", "ESP Connection Successful"); + ScienceLabCommon.getInstance().openDevice(null); } } }