Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add Httphandler class #1927

Merged
merged 1 commit into from
Aug 19, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions app/src/main/java/io/pslab/communication/HttpAsyncTask.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package io.pslab.communication;

import android.os.AsyncTask;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import io.pslab.interfaces.HttpCallback;

public class HttpAsyncTask extends AsyncTask<byte[], Void, Void> {

private HttpHandler mHttpHandler;
private HttpCallback<JSONObject> mHttpCallback;

public HttpAsyncTask(String baseIP, HttpCallback<JSONObject> httpCallback) {
mHttpHandler = new HttpHandler(baseIP);
mHttpCallback = httpCallback;
}

@Override
protected Void doInBackground(byte[]... data) {
int res = 0;
try {
if (data.length != 0) {
res = mHttpHandler.write(data[0]);

} else {
res = mHttpHandler.read();
}
} catch (IOException | JSONException e) {
mHttpCallback.error(e);
e.printStackTrace();
}
if (res == 1) {
mHttpCallback.success(mHttpHandler.getReceivedData());
} else {
mHttpCallback.error(new Exception());
}
return null;
}
}
87 changes: 87 additions & 0 deletions app/src/main/java/io/pslab/communication/HttpHandler.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
package io.pslab.communication;

import android.util.Log;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.net.URL;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class HttpHandler {

private final String TAG = this.getClass().getSimpleName();
private String baseIP;
private String sendDataEndPoint = "send";
private String getDataEndPoint = "get";
private String dataKeyString = "data";
private OkHttpClient client;
private JSONObject receivedData;

public HttpHandler(String baseIP) {
this.baseIP = baseIP;
this.client = new OkHttpClient();
}

/**
* Method to send data to ESP
*
* @param data data to be sent in byte array
* @return 1 if response code is "200" 0 otherwise;
*/
public int write(byte[] data) throws IOException, JSONException {
int result = 1;
URL baseURL = new URL("http://" + baseIP + "/" + sendDataEndPoint);
int written = 0;
JSONArray responseArray = new JSONArray();
while (written < data.length) {
JSONObject jsonObject = new JSONObject();
jsonObject.put(dataKeyString, data[written]);
RequestBody body = RequestBody.create(jsonObject.toString(), MediaType.get("application/json; charset=utf-8"));
Request request = new Request.Builder()
.url(baseURL)
.post(body)
.build();
Response response = client.newCall(request).execute();
responseArray.put(new JSONObject(response.body().string()));
if (response.code() != 200) {
Log.e(TAG, "Error writing byte:" + written);
return 0;
}
written++;
}
receivedData = new JSONObject(responseArray.toString());
return result;
}

/**
* Method to get data from ESP
* @return 1 if data was received 0 otherwise
*/
public int read() throws IOException, JSONException {
int result = 1;
URL baseURL = new URL("http://" + baseIP + "/" + getDataEndPoint);
Request request = new Request.Builder()
.url(baseURL)
.build();
Response response = client.newCall(request).execute();
if (response.code() != 200) {
Log.e(TAG, "Error reading data");
return 0;
} else {
receivedData = new JSONObject(response.body().string());
}
return result;
}

public JSONObject getReceivedData() {
return receivedData;
}
}
80 changes: 67 additions & 13 deletions app/src/main/java/io/pslab/communication/PacketHandler.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,18 @@

import android.util.Log;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.Charset;
import java.util.Arrays;

import io.pslab.interfaces.HttpCallback;
import io.pslab.others.ScienceLabCommon;

/**
* Created by viveksb007 on 28/3/17.
*/
Expand All @@ -24,18 +30,19 @@ public class PacketHandler {
private CommandsProto mCommandsProto;
private int timeout = 500, VERSION_STRING_LENGTH = 15;
ByteBuffer burstBuffer = ByteBuffer.allocate(2000);
private HttpAsyncTask httpAsyncTask;

public PacketHandler(int timeout, CommunicationHandler communicationHandler) {
this.loadBurst = false;
this.connected = false;
this.timeout = timeout;
this.mCommandsProto = new CommandsProto();
this.mCommunicationHandler = communicationHandler;
connected = mCommunicationHandler.isConnected();
connected = (mCommunicationHandler.isConnected() || ScienceLabCommon.isWifiConnected());
}

public boolean isConnected() {
connected = mCommunicationHandler.isConnected();
connected = (mCommunicationHandler.isConnected() || ScienceLabCommon.isWifiConnected());
return connected;
}

Expand All @@ -44,7 +51,7 @@ public String getVersion() {
sendByte(mCommandsProto.COMMON);
sendByte(mCommandsProto.GET_VERSION);
// Read "<PSLAB Version String>\n"
mCommunicationHandler.read(buffer, VERSION_STRING_LENGTH + 1, timeout);
commonRead(VERSION_STRING_LENGTH + 1);
version = new String(Arrays.copyOfRange(buffer, 0, VERSION_STRING_LENGTH), Charset.forName("UTF-8"));
} catch (IOException e) {
Log.e("Error in Communication", e.toString());
Expand All @@ -58,7 +65,7 @@ public void sendByte(int val) throws IOException {
}
if (!loadBurst) {
try {
mCommunicationHandler.write(new byte[]{(byte) (val & 0xff)}, timeout);
commonWrite(new byte[]{(byte) (val & 0xff)});
} catch (IOException | NullPointerException e) {
Log.e("Error in sending byte", e.toString());
e.printStackTrace();
Expand All @@ -74,7 +81,7 @@ public void sendInt(int val) throws IOException {
}
if (!loadBurst) {
try {
mCommunicationHandler.write(new byte[]{(byte) (val & 0xff), (byte) ((val >> 8) & 0xff)}, timeout);
commonWrite(new byte[]{(byte) (val & 0xff), (byte) ((val >> 8) & 0xff)});
} catch (IOException e) {
Log.e("Error in sending int", e.toString());
e.printStackTrace();
Expand All @@ -97,7 +104,7 @@ public int getAcknowledgement() {
return 1;
} else {
try {
mCommunicationHandler.read(buffer, 1, timeout);
commonRead(1);
return buffer[0];
} catch (IOException | NullPointerException e) {
e.printStackTrace();
Expand All @@ -108,7 +115,7 @@ public int getAcknowledgement() {

public byte getByte() {
try {
int numByteRead = mCommunicationHandler.read(buffer, 1, timeout);
int numByteRead = commonRead(1);
if (numByteRead == 1) {
return buffer[0];
} else {
Expand All @@ -123,7 +130,7 @@ public byte getByte() {
int getVoltageSummation() {
try {
// Note : bytesToBeRead has to be +1 than the requirement
int numByteRead = mCommunicationHandler.read(buffer, 3, timeout);
int numByteRead = commonRead(3);
if (numByteRead == 3) {
return (buffer[0] & 0xff) | ((buffer[1] << 8) & 0xff00);
} else {
Expand All @@ -137,7 +144,7 @@ int getVoltageSummation() {

public int getInt() {
try {
int numByteRead = mCommunicationHandler.read(buffer, 2, timeout);
int numByteRead = commonRead(2);
if (numByteRead == 2) {
// LSB is read first
return (buffer[0] & 0xff) | ((buffer[1] << 8) & 0xff00);
Expand All @@ -152,7 +159,7 @@ public int getInt() {

public long getLong() {
try {
int numByteRead = mCommunicationHandler.read(buffer, 4, timeout);
int numByteRead = commonRead(4);
if (numByteRead == 4) {
// C++ has long of 4-bytes but in Java int has 4-bytes
// refer "https://stackoverflow.com/questions/7619058/convert-a-byte-array-to-integer-in-java-and-vice-versa" for Endian
Expand All @@ -171,7 +178,7 @@ public boolean waitForData() {
}

public int read(byte[] dest, int bytesToRead) throws IOException {
int numBytesRead = mCommunicationHandler.read(buffer, bytesToRead, timeout);
int numBytesRead = commonRead(bytesToRead);
for (int i = 0; i < bytesToRead; i++) {
dest[i] = buffer[i];
}
Expand All @@ -185,10 +192,10 @@ public int read(byte[] dest, int bytesToRead) throws IOException {

public byte[] sendBurst() {
try {
mCommunicationHandler.write(burstBuffer.array(), timeout);
commonWrite(burstBuffer.array());
burstBuffer.clear();
loadBurst = false;
int bytesRead = mCommunicationHandler.read(buffer, inputQueueSize, timeout);
int bytesRead = commonRead(inputQueueSize);
inputQueueSize = 0;
return Arrays.copyOfRange(buffer, 0, bytesRead);
} catch (IOException e) {
Expand All @@ -197,4 +204,51 @@ public byte[] sendBurst() {
return new byte[]{-1};
}

private int commonRead(int bytesToRead) throws IOException {
final int[] bytesRead = {0};
if (mCommunicationHandler.isConnected()) {
bytesRead[0] = mCommunicationHandler.read(buffer, bytesToRead, timeout);
} else if (ScienceLabCommon.isWifiConnected()) {
httpAsyncTask = new HttpAsyncTask(ScienceLabCommon.getEspIP(), new HttpCallback<JSONObject>() {
@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();
}
}

@Override
public void error(Exception e) {
Log.e(TAG, "Error reading data over ESP");
}
});
httpAsyncTask.execute(new byte[]{});
}
return bytesRead[0];
}

private void commonWrite(byte[] data) throws IOException {
if (mCommunicationHandler.isConnected()) {
mCommunicationHandler.write(data, timeout);
} else if (ScienceLabCommon.isWifiConnected()) {
httpAsyncTask = new HttpAsyncTask(ScienceLabCommon.getEspIP(), new HttpCallback<JSONObject>() {
@Override
public void success(JSONObject jsonObject) {
Log.v(TAG, "write response:" + jsonObject.toString());
}

@Override
public void error(Exception e) {
Log.e(TAG, "Error writing data over ESP");
}
});

httpAsyncTask.execute(data);
}

}
}
5 changes: 5 additions & 0 deletions app/src/main/java/io/pslab/fragment/ESPFragment.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
import java.io.IOException;

import io.pslab.R;
import io.pslab.others.ScienceLabCommon;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
Expand Down Expand Up @@ -78,6 +79,10 @@ protected String doInBackground(Void... voids) {
.url("http://" + espIPAddress)
.build();
Response response = client.newCall(request).execute();
if (response.code() == 200) {
ScienceLabCommon.setIsWifiConnected(true);
ScienceLabCommon.setEspBaseIP(espIPAddress);
}
result = response.body().string();
} catch (IOException e) {
e.printStackTrace();
Expand Down
6 changes: 6 additions & 0 deletions app/src/main/java/io/pslab/interfaces/HttpCallback.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package io.pslab.interfaces;

public interface HttpCallback<T> {
void success(T t1);
void error(Exception e);
}
18 changes: 18 additions & 0 deletions app/src/main/java/io/pslab/others/ScienceLabCommon.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ public class ScienceLabCommon {
private static ScienceLabCommon scienceLabCommon = null;
public static ScienceLab scienceLab;
public boolean connected = false;
public static boolean isWifiConnected = false;
private static String espBaseIP = "";

private ScienceLabCommon() {
}
Expand All @@ -35,4 +37,20 @@ public static ScienceLabCommon getInstance() {
}
return scienceLabCommon;
}

public static String getEspIP() {
return espBaseIP;
}

public static void setEspBaseIP(String espBaseIP) {
ScienceLabCommon.espBaseIP = espBaseIP;
}

public static boolean isWifiConnected() {
return isWifiConnected;
}

public static void setIsWifiConnected(boolean wifiConnected) {
isWifiConnected = wifiConnected;
}
}