Network data source now working, but needs testing still.

This commit is contained in:
Graham Jones
2015-11-28 22:54:06 +00:00
parent 95c9cde8a3
commit 9a49794428
5 changed files with 262 additions and 4 deletions

View File

@@ -71,7 +71,7 @@ public class PrefActivity extends PreferenceActivity {
}
if (h.title.toString().equals("Network Datasource")) {
Log.v(TAG, "found Network Datasource Header");
if (!dataSourceStr.equals("network")) {
if (!dataSourceStr.equals("Network")) {
Log.v(TAG, "Removing network settings header");
target.remove(i);
i = i -1;

View File

@@ -95,6 +95,8 @@ public class SdData implements Parcelable {
pebbleAppRunning = jo.optBoolean("pebbleAppRunning");
alarmState = jo.optInt("alarmState");
alarmPhrase = jo.optString("alarmPhrase");
alarmThresh = jo.optInt("alarmThresh");
alarmRatioThresh = jo.optInt("alarmRatioThresh");
JSONArray specArr = jo.optJSONArray("simpleSpec");
for (int i=0;i<specArr.length();i++) {
simpleSpec[i] = specArr.optInt(i);
@@ -133,8 +135,11 @@ public class SdData implements Parcelable {
jsonObj.put("batteryPc",batteryPc);
jsonObj.put("pebbleConnected",pebbleConnected);
jsonObj.put("pebbleAppRunning",pebbleAppRunning);
jsonObj.put("haveSettings",haveSettings);
jsonObj.put("alarmState",alarmState);
jsonObj.put("alarmPhrase",alarmPhrase);
jsonObj.put("alarmThresh",alarmThresh);
jsonObj.put("alarmRatioThresh",alarmRatioThresh);
JSONArray arr = new JSONArray();
for (int i=0;i<simpleSpec.length;i++) {
arr.put(simpleSpec[i]);

View File

@@ -25,6 +25,7 @@ package uk.org.openseizuredetector;
import android.content.Context;
import android.util.Log;
import android.widget.Toast;
interface SdDataReceiver {
public void onSdDataReceived(SdData sdData);
@@ -72,4 +73,14 @@ public abstract class SdDataSource {
Log.v(TAG, "stop()");
}
/**
* Display a Toast message on screen.
* @param msg - message to display.
*/
public void showToast(String msg) {
Toast.makeText(mContext, msg,
Toast.LENGTH_LONG).show();
}
}

View File

@@ -1,14 +1,199 @@
package uk.org.openseizuredetector;
import android.content.Context;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.text.format.Time;
import android.util.Log;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Timer;
import java.util.TimerTask;
/**
* Created by graham on 22/11/15.
*/
public class SdDataSourceNetwork extends SdDataSource {
private String TAG = "SdDataSourceNetwork";
private Time mStatusTime;
private Timer mDataUpdateTimer;
private int mDataUpdatePeriod = 2000;
private String mServerIP = "unknown";
public SdDataSourceNetwork(Context context, SdDataReceiver sdDataReceiver) {
super(context,sdDataReceiver);
mName = "Network";
}
@Override public void start() {
// Update preferences.
Log.v(TAG,"start(): calling updatePrefs()");
updatePrefs();
// Start timer to retrieve seizure detector data regularly.
mStatusTime = new Time(Time.getCurrentTimezone());
mStatusTime.setToNow();
if (mDataUpdateTimer ==null) {
Log.v(TAG,"start(): starting data update timer");
mDataUpdateTimer = new Timer();
mDataUpdateTimer.schedule(new TimerTask() {
@Override
public void run() {
downloadSdData();
}
}, 0, mDataUpdatePeriod);
} else {
Log.v(TAG,"start(): data update timer already running.");
}
}
@Override public void stop() {
// Stop the data update timer
if (mDataUpdateTimer !=null) {
Log.v(TAG,"stop(): cancelling status timer");
mDataUpdateTimer.cancel();
mDataUpdateTimer.purge();
mDataUpdateTimer = null;
}
}
/**
* updatePrefs() - update basic settings from the SharedPreferences
* - defined in res/xml/prefs.xml
*/
public void updatePrefs() {
Log.v(TAG, "updatePrefs()");
SharedPreferences SP = PreferenceManager
.getDefaultSharedPreferences(mContext);
mServerIP = SP.getString("ServerIP","192.168.1.175");
Log.v(TAG,"updatePrefs() - mServerIP = "+mServerIP);
try {
String dataUpdatePeriodStr = SP.getString("DataUpdatePeriod","2000");
mDataUpdatePeriod = Integer.parseInt(dataUpdatePeriodStr);
Log.v(TAG,"updatePrefs() - mDataUpdatePeriod = "+mDataUpdatePeriod);
} catch (Exception ex) {
Log.v(TAG,"updatePrefs() - Problem parsing preferences!");
showToast("Problem Parsing Preferences - Something won't work");
}
}
/**
* Retrive the current Seizure Detector Data from the server.
* Uses teh DownloadSdDataTask class to download the data in the
* background. The data is processed in DownloadSdDataTask.onPostExecute().
*/
public void downloadSdData() {
Log.v(TAG, "downloadSdData()");
new DownloadSdDataTask().execute("http://" + mServerIP + ":8080/data");
}
private class DownloadSdDataTask extends AsyncTask<String, Void, SdData> {
private SdData sdData;
@Override
protected SdData doInBackground(String... urls) {
// params comes from the execute() call: params[0] is the url.
sdData = new SdData();
try {
String result = downloadUrl(urls[0]);
if (result.startsWith("Unable to retrieve web page")) {
Log.v(TAG,"doInBackground() - Unable to retrieve data");
sdData.serverOK = false;
sdData.pebbleConnected = false;
sdData.pebbleAppRunning = false;
sdData.alarmState = 0;
sdData.alarmPhrase = "Warning - No Connection to Server";
Log.v(TAG,"doInBackground(): No Connection to Server - sdData = "+sdData.toString());
} else {
sdData.fromJSON(result);
// Populate mSdData using the received data.
sdData.serverOK = true;
if (sdData.batteryPc>0) {
sdData.haveSettings = true;
}
mStatusTime.setToNow();
Log.v(TAG,"doInBackground(): sdData = "+sdData.toString());
}
return (sdData);
} catch (IOException e) {
sdData.serverOK = false;
sdData.pebbleConnected = false;
sdData.pebbleAppRunning = false;
sdData.alarmState = 0;
sdData.alarmPhrase = "Warning - No Connection to Server";
Log.v(TAG,"doInBackground(): IOException - "+e.toString());
return sdData;
}
}
// onPostExecute displays the results of the AsyncTask.
@Override
protected void onPostExecute(SdData sdData) {
Log.v(TAG,"onPostExecute() - sdData = "+sdData.toString());
mSdDataReceiver.onSdDataReceived(sdData);
}
}
// Given a URL, establishes an HttpUrlConnection and retrieves
// the web page content as a InputStream, which it returns as
// a string.
private String downloadUrl(String myurl) throws IOException {
InputStream is = null;
// Only display the first 500 characters of the retrieved
// web page content.
int len = 500;
try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(5000 /* milliseconds */);
conn.setConnectTimeout(5000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
int response = conn.getResponseCode();
Log.d(TAG, "The response is: " + response);
is = conn.getInputStream();
// Convert the InputStream into a string
String contentAsString = readInputStream(is, len);
return contentAsString;
// Makes sure that the InputStream is closed after the app is
// finished using it.
} finally {
if (is != null) {
is.close();
}
}
}
// Reads an InputStream and converts it to a String.
public String readInputStream(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
Reader reader = null;
reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[len];
reader.read(buffer);
return new String(buffer);
}
}

View File

@@ -40,6 +40,7 @@ import android.content.res.AssetManager;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.media.ToneGenerator;
import android.os.CountDownTimer;
import android.os.Environment;
import android.os.HandlerThread;
import android.os.Binder;
@@ -80,6 +81,9 @@ public class SdServer extends Service implements SdDataReceiver {
private WebServer webServer = null;
private final static String TAG = "SdServer";
private Timer dataLogTimer = null;
private CancelAudibleTimer mCancelAudibleTimer = null;
private int mCancelAudiblePeriod = 10; // Cancel Audible Period in minutes
private long mCancelAudibleTimeRemaining = 0;
private HandlerThread thread;
private WakeLock mWakeLock = null;
public SdDataSource mSdDataSource;
@@ -351,6 +355,7 @@ public class SdServer extends Service implements SdDataReceiver {
}
mSdData = sdData;
Log.v(TAG,"onSdDataReceived() - setting mSdData to "+mSdData.toString());
}
public void onSdDataFault(SdData sdData) {
@@ -455,6 +460,34 @@ public class SdServer extends Service implements SdDataReceiver {
}
public void cancelAudible() {
// Start timer to remove the cancel audible flag
// after the required period.
if (mCancelAudibleTimer!=null) {
Log.v(TAG,"onCreate(): cancel audible timer already running - cancelling it.");
mCancelAudibleTimer.cancel();
mCancelAudibleTimer = null;
mCancelAudible = false;
} else {
Log.v(TAG,"cancelAudible(): starting cancel audible timer");
mCancelAudible = true;
mCancelAudibleTimer =
// conver to ms.
new CancelAudibleTimer(mCancelAudiblePeriod*60*1000,1000);
mCancelAudibleTimer.start();
}
}
public boolean isAudibleCancelled() {
return mCancelAudible;
}
public long cancelAudibleTimeRemaining() {
return mCancelAudibleTimeRemaining;
}
/**
* Start the web server (on port 8080)
*/
@@ -609,6 +642,30 @@ public class SdServer extends Service implements SdDataReceiver {
}
}
/*
* Temporary cancel audible alarms, for the period specified by the
* CancelAudiblePeriod setting.
*/
private class CancelAudibleTimer extends CountDownTimer {
public CancelAudibleTimer(long startTime, long interval) {
super(startTime, interval);
}
@Override
public void onFinish() {
mCancelAudible = false;
Log.v(TAG,"mCancelAudibleTimer - removing cancelAudible flag");
}
@Override
public void onTick(long msRemaining) {
mCancelAudibleTimeRemaining = msRemaining/1000;
Log.v(TAG,"mCancelAudibleTimer - onTick() - Time Remaining = "
+ mCancelAudibleTimeRemaining);
}
}
/**
* Class describing the seizure detector web server - appears on port
* 8080.