From cd1f82ae15443849ba255e44d7c5cac3917b9cfc Mon Sep 17 00:00:00 2001 From: Lennart Goedhart <lennart@omnibase.com.au> Date: Thu, 26 May 2016 19:39:49 +1000 Subject: [PATCH] Removed a whole bunch of code we don't use. Everything is still working. Quick! Commit, before you break something! --- app/src/main/AndroidManifest.xml | 5 - .../nightscout/android/dexcom/CSVWriter.java | 302 -- .../android/dexcom/DexcomG4Service.java | 346 -- .../android/dexcom/DexcomReader.java | 469 --- .../nightscout/android/dexcom/EGVRecord.java | 30 - .../android/dexcom/ResultSetHelper.java | 33 - .../dexcom/ResultSetHelperService.java | 183 - .../dexcom/USB/CdcAcmSerialDriver.java | 257 -- .../dexcom/USB/CommonUsbSerialDriver.java | 138 - .../dexcom/USB/SerialInputOutputManager.java | 187 - .../android/dexcom/USB/UsbSerialDriver.java | 207 -- .../android/dexcom/USB/UsbSerialProber.java | 171 - .../medtronic/CommandSenderThread.java | 388 -- .../nightscout/android/medtronic/DataLog.java | 11 - .../medtronic/HistoricGetterThread.java | 191 - .../medtronic/Medtronic640gActivity.java | 375 +- .../medtronic/MedtronicCGMService.java | 2005 ----------- .../android/medtronic/MedtronicCNLReader.java | 60 +- .../medtronic/MedtronicCalibration.java | 5 - .../android/medtronic/MedtronicConstants.java | 136 +- .../android/medtronic/MedtronicReader.java | 3119 ----------------- .../service/MedtronicCNLService.java | 28 +- .../medtronic/service/TestService.java | 87 - .../android/upload/MedtronicPumpRecord.java | 250 -- .../android/upload/MedtronicSensorRecord.java | 35 - .../android/upload/UploadHelper.java | 946 +---- .../{dexcom/USB => utils}/HexDump.java | 2 +- .../nightscout/android/widget/CGMWidget.java | 108 - .../android/widget/CGMWidgetUpdater.java | 117 - 29 files changed, 174 insertions(+), 10017 deletions(-) delete mode 100644 app/src/main/java/info/nightscout/android/dexcom/CSVWriter.java delete mode 100644 app/src/main/java/info/nightscout/android/dexcom/DexcomG4Service.java delete mode 100644 app/src/main/java/info/nightscout/android/dexcom/DexcomReader.java delete mode 100644 app/src/main/java/info/nightscout/android/dexcom/EGVRecord.java delete mode 100644 app/src/main/java/info/nightscout/android/dexcom/ResultSetHelper.java delete mode 100644 app/src/main/java/info/nightscout/android/dexcom/ResultSetHelperService.java delete mode 100644 app/src/main/java/info/nightscout/android/dexcom/USB/CdcAcmSerialDriver.java delete mode 100644 app/src/main/java/info/nightscout/android/dexcom/USB/CommonUsbSerialDriver.java delete mode 100644 app/src/main/java/info/nightscout/android/dexcom/USB/SerialInputOutputManager.java delete mode 100644 app/src/main/java/info/nightscout/android/dexcom/USB/UsbSerialDriver.java delete mode 100644 app/src/main/java/info/nightscout/android/dexcom/USB/UsbSerialProber.java delete mode 100644 app/src/main/java/info/nightscout/android/medtronic/CommandSenderThread.java delete mode 100644 app/src/main/java/info/nightscout/android/medtronic/DataLog.java delete mode 100644 app/src/main/java/info/nightscout/android/medtronic/HistoricGetterThread.java delete mode 100644 app/src/main/java/info/nightscout/android/medtronic/MedtronicCGMService.java delete mode 100644 app/src/main/java/info/nightscout/android/medtronic/MedtronicCalibration.java delete mode 100644 app/src/main/java/info/nightscout/android/medtronic/MedtronicReader.java delete mode 100644 app/src/main/java/info/nightscout/android/medtronic/service/TestService.java delete mode 100644 app/src/main/java/info/nightscout/android/upload/MedtronicPumpRecord.java delete mode 100644 app/src/main/java/info/nightscout/android/upload/MedtronicSensorRecord.java rename app/src/main/java/info/nightscout/android/{dexcom/USB => utils}/HexDump.java (99%) delete mode 100644 app/src/main/java/info/nightscout/android/widget/CGMWidget.java delete mode 100644 app/src/main/java/info/nightscout/android/widget/CGMWidgetUpdater.java diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 1f9b4a4..c7995f0 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -60,11 +60,6 @@ android:name=".medtronic.service.MedtronicCNLService" android:icon="@drawable/ic_launcher" > </service> - <service - android:name=".medtronic.service.TestService" - android:icon="@drawable/ic_launcher" - android:process=":nightscoutcnlservice" > - </service> <service android:name=".widget.CGMWidgetUpdater" android:icon="@drawable/ic_launcher" diff --git a/app/src/main/java/info/nightscout/android/dexcom/CSVWriter.java b/app/src/main/java/info/nightscout/android/dexcom/CSVWriter.java deleted file mode 100644 index dbe42c2..0000000 --- a/app/src/main/java/info/nightscout/android/dexcom/CSVWriter.java +++ /dev/null @@ -1,302 +0,0 @@ -package info.nightscout.android.dexcom; - -/** - Copyright 2005 Bytecode Pty Ltd. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ - -import java.io.Closeable; -import java.io.IOException; -import java.io.PrintWriter; -import java.io.Writer; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.List; - -/** - * A very simple CSV writer released under a commercial-friendly license. - * - * @author Glen Smith - * - */ -public class CSVWriter implements Closeable { - - public static final int INITIAL_STRING_SIZE = 128; - - private Writer rawWriter; - - private PrintWriter pw; - - private char separator; - - private char quotechar; - - private char escapechar; - - private String lineEnd; - - /** The character used for escaping quotes. */ - public static final char DEFAULT_ESCAPE_CHARACTER = '"'; - - /** The default separator to use if none is supplied to the constructor. */ - public static final char DEFAULT_SEPARATOR = ','; - - /** - * The default quote character to use if none is supplied to the - * constructor. - */ - public static final char DEFAULT_QUOTE_CHARACTER = '"'; - - /** The quote constant to use when you wish to suppress all quoting. */ - public static final char NO_QUOTE_CHARACTER = '\u0000'; - - /** The escape constant to use when you wish to suppress all escaping. */ - public static final char NO_ESCAPE_CHARACTER = '\u0000'; - - /** Default line terminator uses platform encoding. */ - public static final String DEFAULT_LINE_END = "\n"; - - private ResultSetHelper resultService = new ResultSetHelperService(); - - /** - * Constructs CSVWriter using a comma for the separator. - * - * @param writer - * the writer to an underlying CSV source. - */ - public CSVWriter(Writer writer) { - this(writer, DEFAULT_SEPARATOR); - } - - /** - * Constructs CSVWriter with supplied separator. - * - * @param writer - * the writer to an underlying CSV source. - * @param separator - * the delimiter to use for separating entries. - */ - public CSVWriter(Writer writer, char separator) { - this(writer, separator, DEFAULT_QUOTE_CHARACTER); - } - - /** - * Constructs CSVWriter with supplied separator and quote char. - * - * @param writer - * the writer to an underlying CSV source. - * @param separator - * the delimiter to use for separating entries - * @param quotechar - * the character to use for quoted elements - */ - public CSVWriter(Writer writer, char separator, char quotechar) { - this(writer, separator, quotechar, DEFAULT_ESCAPE_CHARACTER); - } - - /** - * Constructs CSVWriter with supplied separator and quote char. - * - * @param writer - * the writer to an underlying CSV source. - * @param separator - * the delimiter to use for separating entries - * @param quotechar - * the character to use for quoted elements - * @param escapechar - * the character to use for escaping quotechars or escapechars - */ - public CSVWriter(Writer writer, char separator, char quotechar, char escapechar) { - this(writer, separator, quotechar, escapechar, DEFAULT_LINE_END); - } - - - /** - * Constructs CSVWriter with supplied separator and quote char. - * - * @param writer - * the writer to an underlying CSV source. - * @param separator - * the delimiter to use for separating entries - * @param quotechar - * the character to use for quoted elements - * @param lineEnd - * the line feed terminator to use - */ - public CSVWriter(Writer writer, char separator, char quotechar, String lineEnd) { - this(writer, separator, quotechar, DEFAULT_ESCAPE_CHARACTER, lineEnd); - } - - - - /** - * Constructs CSVWriter with supplied separator, quote char, escape char and line ending. - * - * @param writer - * the writer to an underlying CSV source. - * @param separator - * the delimiter to use for separating entries - * @param quotechar - * the character to use for quoted elements - * @param escapechar - * the character to use for escaping quotechars or escapechars - * @param lineEnd - * the line feed terminator to use - */ - public CSVWriter(Writer writer, char separator, char quotechar, char escapechar, String lineEnd) { - this.rawWriter = writer; - this.pw = new PrintWriter(writer); - this.separator = separator; - this.quotechar = quotechar; - this.escapechar = escapechar; - this.lineEnd = lineEnd; - } - - /** - * Writes the entire list to a CSV file. The list is assumed to be a - * String[] - * - * @param allLines - * a List of String[], with each String[] representing a line of - * the file. - */ - public void writeAll(List<String[]> allLines) { - for (String[] line : allLines) { - writeNext(line); - } - } - - protected void writeColumnNames(ResultSet rs) - throws SQLException { - - writeNext(resultService.getColumnNames(rs)); - } - - /** - * Writes the entire ResultSet to a CSV file. - * - * The caller is responsible for closing the ResultSet. - * - * @param rs the recordset to write - * @param includeColumnNames true if you want column names in the output, false otherwise - * - * @throws java.io.IOException thrown by getColumnValue - * @throws java.sql.SQLException thrown by getColumnValue - */ - public void writeAll(ResultSet rs, boolean includeColumnNames) throws SQLException, IOException { - - - if (includeColumnNames) { - writeColumnNames(rs); - } - - while (rs.next()) - { - writeNext(resultService.getColumnValues(rs)); - } - } - - - /** - * Writes the next line to the file. - * - * @param nextLine - * a string array with each comma-separated element as a separate - * entry. - */ - public void writeNext(String[] nextLine) { - - if (nextLine == null) - return; - - StringBuilder sb = new StringBuilder(INITIAL_STRING_SIZE); - for (int i = 0; i < nextLine.length; i++) { - - if (i != 0) { - sb.append(separator); - } - - String nextElement = nextLine[i]; - if (nextElement == null) - continue; - if (quotechar != NO_QUOTE_CHARACTER) - sb.append(quotechar); - - sb.append(stringContainsSpecialCharacters(nextElement) ? processLine(nextElement) : nextElement); - - if (quotechar != NO_QUOTE_CHARACTER) - sb.append(quotechar); - } - - sb.append(lineEnd); - pw.write(sb.toString()); - - } - - private boolean stringContainsSpecialCharacters(String line) { - return line.indexOf(quotechar) != -1 || line.indexOf(escapechar) != -1; - } - - protected StringBuilder processLine(String nextElement) - { - StringBuilder sb = new StringBuilder(INITIAL_STRING_SIZE); - for (int j = 0; j < nextElement.length(); j++) { - char nextChar = nextElement.charAt(j); - if (escapechar != NO_ESCAPE_CHARACTER && nextChar == quotechar) { - sb.append(escapechar).append(nextChar); - } else if (escapechar != NO_ESCAPE_CHARACTER && nextChar == escapechar) { - sb.append(escapechar).append(nextChar); - } else { - sb.append(nextChar); - } - } - - return sb; - } - - /** - * Flush underlying stream to writer. - * - * @throws java.io.IOException if bad things happen - */ - public void flush() throws IOException { - - pw.flush(); - - } - - /** - * Close the underlying stream writer flushing any buffered content. - * - * @throws java.io.IOException if bad things happen - * - */ - public void close() throws IOException { - flush(); - pw.close(); - rawWriter.close(); - } - - /** - * Checks to see if the there has been an error in the printstream. - */ - public boolean checkError() { - return pw.checkError(); - } - - public void setResultService(ResultSetHelper resultService) { - this.resultService = resultService; - } - -} diff --git a/app/src/main/java/info/nightscout/android/dexcom/DexcomG4Service.java b/app/src/main/java/info/nightscout/android/dexcom/DexcomG4Service.java deleted file mode 100644 index 4f4898f..0000000 --- a/app/src/main/java/info/nightscout/android/dexcom/DexcomG4Service.java +++ /dev/null @@ -1,346 +0,0 @@ -package info.nightscout.android.dexcom; - -import android.annotation.SuppressLint; -import android.app.Notification; -import android.app.NotificationManager; -import android.app.Service; -import android.content.Context; -import android.content.Intent; -import android.content.SharedPreferences; -import android.graphics.BitmapFactory; -import android.hardware.usb.UsbManager; -import android.net.ConnectivityManager; -import android.net.NetworkInfo; -import android.net.wifi.WifiManager; -import android.os.AsyncTask.Status; -import android.os.Handler; -import android.os.IBinder; -import android.preference.PreferenceManager; -import android.util.Log; -import android.view.Gravity; -import android.widget.LinearLayout; -import android.widget.TextView; -import android.widget.Toast; -import info.nightscout.android.R; -import info.nightscout.android.dexcom.USB.SerialInputOutputManager; -import info.nightscout.android.USB.USBPower; -import info.nightscout.android.dexcom.USB.UsbSerialDriver; -import info.nightscout.android.dexcom.USB.UsbSerialProber; -import info.nightscout.android.upload.UploadHelper; - -import java.io.IOException; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.*; - -@SuppressLint("NewApi") -public class DexcomG4Service extends Service { - - public UsbManager mUsbManager; - private static final String TAG = DexcomG4Service.class.getSimpleName(); - private Context mContext; - private NotificationManager NM; - private final int FIVE_MINS_MS = 300000; - private final int THREE_MINS_MS = 180000; - private final int UPLOAD_OFFSET_MS = 3000; - private long nextUploadTimer = THREE_MINS_MS; - private boolean initialRead = true; - private UsbSerialDriver mSerialDevice; - private UploadHelper uploader; - private Handler mHandler = new Handler(); - private SerialInputOutputManager mSerialIoManager; - private WifiManager wifiManager; - - @Override - public IBinder onBind(Intent arg0) { - // TODO Auto-generated method stub - return null; - } - - @Override - public void onCreate() { - super.onCreate(); - Log.i(TAG, "onCreate called"); - mContext = this.getBaseContext(); - wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE); - mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE); - // connectToG4(); - mHandler.removeCallbacks(readAndUpload); - mHandler.post(readAndUpload); - } - - @Override - public void onDestroy() { - super.onDestroy(); - Log.i(TAG, "onDestroy called"); - mHandler.removeCallbacks(readAndUpload); - stopIoManager(); - - if (NM != null) { - NM.cancelAll(); - NM = null; - } - - if (mSerialDevice != null) { - try { - Log.i(TAG, "Closing serial device..."); - mSerialDevice.close(); - } catch (IOException e) { - Log.e(TAG, "Unable to close serial device.", e); - } - mSerialDevice = null; - } - } - - //get the data upload it - //if you don't have root, the On, Off commands won't do a thing - shouldn't break anything either - private Runnable readAndUpload = new Runnable() { - public void run() { - - try { - uploader = new UploadHelper(getBaseContext()); - boolean connected = isConnected(); - if (connected && isOnline()) { - - USBOn(); - doReadAndUpload(); - USBOff(); - } else { - USBOn(); - USBOff(); - - if (!connected) - displayMessage("CGM connection error"); - else - displayMessage("NET connection error"); - } - - } catch (Exception e) { - // ignore... for now - simply prevent service and activity from - // losing its shit. - USBOn(); - USBOff(); - Log.e(TAG, "Unable to read from dexcom or upload", e); - } - mHandler.removeCallbacks(readAndUpload); - mHandler.postDelayed(readAndUpload, nextUploadTimer); - } - }; - - private void acquireSerialDevice() { - mSerialDevice = UsbSerialProber.acquire(mUsbManager); - if (mSerialDevice == null) { - - Log.i(TAG, "Unable to get the serial device, forcing USB PowerOn, and trying to get an updated USB Manager"); - - try { - USBPower.PowerOn(); - } catch (Exception e) { - Log.w(TAG, "acquireSerialDevice: Unable to PowerOn", e); - } - - try { - Thread.sleep(2500); - } catch (InterruptedException e) { - Log.w(TAG, "Interrupted during sleep after Power On", e); - } - - mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE); - - try { - Thread.sleep(2500); - } catch (InterruptedException e) { - Log.w(TAG, "Interrupted during sleep after getting updated USB Manager", e); - } - - mSerialDevice = UsbSerialProber.acquire(mUsbManager); - } - } - - - protected void doReadAndUpload() { - - acquireSerialDevice(); - - if (mSerialDevice != null) { - startIoManager(); - try { - mSerialDevice.open(); - } catch (Exception e) { - Log.e(TAG, "Unable to open serial device", e); - } - - //Go get the data - DexcomReader dexcomReader = new DexcomReader(mSerialDevice); - - SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); - - if (initialRead && prefs.getBoolean("InitialTwoDayUpload", true)) { - // for first time on, read at least 2 days of data. Each Dexcom read of EGV records - // is limited to 4 pages which is equivalent to 12 hours of contiguous data, so - // read 20 pages which is ~ 2.5 days. - List<EGVRecord> data = new ArrayList<EGVRecord>(); - for(int i = 5; i >= 1; i--) { - dexcomReader.readFromReceiver(getBaseContext(), i); - Collections.addAll(data, dexcomReader.mRD); - } - EGVRecord[] dataRecords = new EGVRecord[data.size()]; - dataRecords = data.toArray(dataRecords); - uploader.execute(dataRecords); - } else { - // just read most recent pages (consider only reading 1 page since only need latest value). - dexcomReader.readFromReceiver(getBaseContext(), 1); - uploader.execute(dexcomReader.mRD[dexcomReader.mRD.length - 1]); - } - - initialRead = false; - - nextUploadTimer = getNextUploadTimer(dexcomReader); - } - } - - private void USBOff() { - if (mSerialDevice != null) { - try { - mSerialDevice.close(); - } catch (IOException e) { - Log.e(TAG, "Unable to close serial device", e); - } - - try { - Thread.sleep(2000); - } catch (InterruptedException e) { - Log.e(TAG, "Sleep after close interrupted", e); - } - - USBPower.PowerOff(); - Log.i(TAG, "USB OFF"); - } else { - Log.i(TAG, "USBOff: Receiver Not Found"); - // displayMessage("Receiver Not Found"); - // android.os.Process.killProcess(android.os.Process.myPid()); - } - - } - - private void USBOn() { - - acquireSerialDevice(); - - if (mSerialDevice != null) { - try { - mSerialDevice.close(); - } catch (IOException e) { - Log.e(TAG, "Unable to close serial device", e); - } - - USBPower.PowerOn(); - - try { - Thread.sleep(2000); - } catch (InterruptedException e) { - Log.e(TAG, "Sleep after close and PowerOn interrupted", e); - } - - Log.i(TAG, "USB ON"); - } else { - Log.i(TAG, "USBOn: Receiver Not Found"); - // displayMessage("Receiver Not Found"); - // android.os.Process.killProcess(android.os.Process.myPid()); - } - - } - - private boolean isConnected() { - acquireSerialDevice(); - return mSerialDevice != null; - } - - private boolean isOnline() { - ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); - NetworkInfo netInfo = cm.getActiveNetworkInfo(); - return netInfo != null && netInfo.isConnectedOrConnecting(); - } - - private void displayMessage(String message) { - Toast toast = Toast.makeText(getBaseContext(), message, Toast.LENGTH_LONG); - toast.setGravity(Gravity.CENTER, 0, 0); - LinearLayout toastLayout = (LinearLayout) toast.getView(); - TextView toastTV = (TextView) toastLayout.getChildAt(0); - if (toastTV != null) { - toastTV.setTextSize(20); - toastTV.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL); - } - toast.show(); - - } - - private void stopIoManager() { - if (mSerialIoManager != null) { - Log.i(TAG, "Stopping io manager..."); - mSerialIoManager.stop(); - mSerialIoManager = null; - } - } - - private void startIoManager() { - if (mSerialDevice != null) { - Log.i(TAG, "Starting io manager..."); - mSerialIoManager = new SerialInputOutputManager(mSerialDevice); - // mExecutor.submit(mSerialIoManager); - } - } - - // Get the devices display time and compare with its last upload time to determine - // when to poll for next reading, since readings are on 5 minute intervals - @SuppressLint("NewApi") - private long getNextUploadTimer(DexcomReader dexcomReader) { - - SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a"); - Date dexcomTime = dexcomReader.getDisplayTime(); - Date androidTime = Calendar.getInstance().getTime(); - long dt = dexcomTime.getTime() - androidTime.getTime(); - - if (Math.abs(dt) > FIVE_MINS_MS * 2) { - // Use ContextText and bigText in case < 16 API - NM = (NotificationManager)mContext.getSystemService(Context.NOTIFICATION_SERVICE); - Notification n = new Notification.Builder(mContext) - .setDefaults(Notification.DEFAULT_ALL) - .setContentTitle("Devices time mismatch!") - .setStyle(new Notification.BigTextStyle() - .bigText("Receiver: " + formatter.format(dexcomTime) + - "\nAndroid: " + formatter.format(androidTime))) - .setContentText("Check that devices times match") - .setTicker("Devices time mismatch!") - .setSmallIcon(R.drawable.ic_action_warning) - .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher)) - .getNotification(); - NM.notify(R.string.app_name, n); - } - - Date lastRecord; - long timeSinceLastRecord = -1; - try { - lastRecord = formatter.parse(dexcomReader.mRD[dexcomReader.mRD.length - 1].displayTime); - timeSinceLastRecord = dexcomTime.getTime() - lastRecord.getTime(); - Log.d(TAG, "The time since last record is: " + timeSinceLastRecord / 1000 + " secs"); - } catch (ParseException e) { - Log.d(TAG, "Error parsing last record displayTime."); - e.printStackTrace(); - } - - if (timeSinceLastRecord < 0) { - displayMessage("Dexcom's time is less than current record time, possible time change."); - nextUploadTimer = THREE_MINS_MS; - } else if (timeSinceLastRecord > FIVE_MINS_MS) { - nextUploadTimer = THREE_MINS_MS; - // TODO: consider making UI display "???" for SG records since likely to be out of range - } else { - nextUploadTimer = FIVE_MINS_MS - timeSinceLastRecord; - nextUploadTimer += UPLOAD_OFFSET_MS; - Log.d(TAG, "Setting next upload time to: " + nextUploadTimer / 1000 + " secs"); - } - - return nextUploadTimer; - } -} diff --git a/app/src/main/java/info/nightscout/android/dexcom/DexcomReader.java b/app/src/main/java/info/nightscout/android/dexcom/DexcomReader.java deleted file mode 100644 index 4bf28c6..0000000 --- a/app/src/main/java/info/nightscout/android/dexcom/DexcomReader.java +++ /dev/null @@ -1,469 +0,0 @@ -package info.nightscout.android.dexcom; - -import android.content.Context; -import android.hardware.usb.UsbManager; -import android.os.AsyncTask; -import android.util.Log; -import info.nightscout.android.dexcom.USB.UsbSerialDriver; -import info.nightscout.android.dexcom.USB.UsbSerialProber; - -import java.io.*; -import java.nio.ByteBuffer; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.*; - -//Still kludgy -//Newer, similar to Dex's architecture, classes are in progress, but this works reliably, if not the -//most efficient, elegant design around. - -public class DexcomReader extends AsyncTask<UsbSerialDriver, Object, Object>{ - - private static final String TAG = DexcomReader.class.getSimpleName(); - private final String EPOCH = "01-01-2009"; - private UsbSerialDriver mSerialDevice; - public String bGValue; - public String displayTime; - public String trend; - public EGVRecord[] mRD; - - public DexcomReader (UsbSerialDriver device) { - mSerialDevice = device; - } - - public void readFromReceiver(Context context, int pageOffset) { - - assert pageOffset < 1 : "Page offset must be greater than 1"; - - //locate the EGV data pages - byte[] dexcomPageRange = getEGVDataPageRange(); - //Get the last 4 pages - byte[] databasePages = getLastFourPages(dexcomPageRange, pageOffset); - //Parse 'dem pages - EGVRecord[] mostRecentData = parseDatabasePages(databasePages); - - // make first read public - mRD = mostRecentData; - - //save them to the android file system for later access - //TODO: should be removed? - writeLocalCSV(mostRecentData, context); - } - - //Not being used, but this is a nice to have if we want to kill the receiver, etc from - //UI - public void shutDownReceiver(Context context){ - - UsbManager manager = (UsbManager) context.getSystemService(Context.USB_SERVICE); - UsbSerialDriver mSerialDevice = UsbSerialProber.acquire(manager); - if (mSerialDevice != null) { - try { - mSerialDevice.open(); - // EGVData page range read command - byte[] resetPacket = new byte[6]; - resetPacket[0] = 0x01; - resetPacket[1] = 0x06; - resetPacket[3] = 0x2e; - resetPacket[4] = (byte) 0xb8; - resetPacket[5] = (byte) 0x01; - try { - mSerialDevice.write(resetPacket, 200); - } catch (IOException e) { - Log.e(TAG, "unable to write to serial device", e); - } - } catch (IOException e) { - Log.e(TAG, "unable to shutDownReceiver", e); - } - } - } - - public Date getDisplayTime() { - int dt = getSystemTime() + getDisplayTimeOffset(); - SimpleDateFormat f = new SimpleDateFormat("dd-MM-yyyy"); - Date epoch; - - try { - epoch = f.parse(EPOCH); - } catch (ParseException e) { - Log.e(TAG, "Unable to parse date: " + EPOCH + ", using current time", e); - epoch = new Date(); - } - - // Epoch is PST, but but having epoch have user timezone added, then don't have to add to the - // display time - long milliseconds = epoch.getTime(); - long timeAdd = milliseconds + (1000L * dt); - TimeZone tz = TimeZone.getDefault(); - if (tz.inDaylightTime(new Date())) timeAdd = timeAdd - 3600000L; - Date displayTime = new Date(timeAdd); - - Log.d(TAG, "The devices Display Time is: " + displayTime.toString()); - - return displayTime; - } - - private int getSystemTime() { - - byte[] readSystemTime = new byte[6]; - readSystemTime[0] = 0x01; - readSystemTime[1] = 0x06; - readSystemTime[2] = 0x00; - readSystemTime[3] = 0x22; - readSystemTime[4] = 0x34; - readSystemTime[5] = (byte)0xc0; - - try { - mSerialDevice.write(readSystemTime, 200); - } catch (IOException e) { - Log.e(TAG, "Unable to write to serial device", e); - } - - byte[] readData = new byte[256]; - try { - mSerialDevice.read(readData, 200); - } catch (IOException e) { - Log.e(TAG, "Unable to read from serial device", e); - } - - int systemTime = readData[4] & 0xFF | - (readData[5] & 0xFF) << 8 | - (readData[6] & 0xFF) << 16 | - (readData[7] & 0xFF) << 24; - - Log.d(TAG, "The devices System Time is " + systemTime); - - return systemTime; - } - - private int getDisplayTimeOffset() { - - byte[] readDisplayTimeOffset = new byte[6]; - readDisplayTimeOffset[0] = 0x01; - readDisplayTimeOffset[1] = 0x06; - readDisplayTimeOffset[2] = 0x00; - readDisplayTimeOffset[3] = 0x1d; - readDisplayTimeOffset[4] = (byte)0x88; - readDisplayTimeOffset[5] = 0x07; - - try { - mSerialDevice.write(readDisplayTimeOffset, 200); - } catch (IOException e) { - Log.e(TAG, "Unable to write to serial device", e); - } - - byte[] readData = new byte[256]; - try { - mSerialDevice.read(readData, 200); - } catch (IOException e) { - Log.e(TAG, "Unable to read from serial device", e); - } - - int displayTimeOffset = readData[4] & 0xFF | - (readData[5] & 0xFF) << 8 | - (readData[6] & 0xFF) << 16 | - (readData[7] & 0xFF) << 24; - - Log.d(TAG, "The devices Display Time Offset is " + displayTimeOffset); - - return displayTimeOffset; - } - - private byte[] getEGVDataPageRange(){ - int[] rets = new int[24]; - int c = 0; - - //EGVData page range read command - byte[] readEGVDataPageRange = new byte[7]; - readEGVDataPageRange[0] = 0x01; - readEGVDataPageRange[1] = 0x07; - readEGVDataPageRange[3] = 0x10; - readEGVDataPageRange[4] = 0x04; - readEGVDataPageRange[5] = (byte)0x8b; - readEGVDataPageRange[6] = (byte)0xb8; - - try { - rets[c++] = mSerialDevice.write(readEGVDataPageRange, 200); - } catch (IOException e) { - Log.e(TAG, "Unable to write to serial device", e); - } - byte[] dexcomPageRange = new byte[256]; - try { - rets[c++] = mSerialDevice.read(dexcomPageRange, 200); - } catch (IOException e) { - Log.e(TAG, "Unable to read from serial device", e); - } - - return dexcomPageRange; - } - - private byte[] getLastFourPages(byte [] dexcomPageRange, int pageOffset) - { - int[] rets = new int[24]; - int c = 0; - byte [] endPage = new byte[]{dexcomPageRange[8], dexcomPageRange[9], dexcomPageRange[10], dexcomPageRange[11]}; - - //ONLY interested in the last 4 pages of data for this app's requirements - int endInt = toInt(endPage, 1); - int lastFour = endInt - 4 * pageOffset + 1; - - //support for a receiver without any old data - if (lastFour < 0) lastFour = 0; - - ByteBuffer b = ByteBuffer.allocate(4); - b.putInt(lastFour); - byte[] result = b.array(); - - //Build get page (EGV) command - byte [] getLastEGVPage = new byte[636]; - getLastEGVPage[0] = 0x01; - getLastEGVPage[1] = 0x0c; - getLastEGVPage[2] = 0x00; - getLastEGVPage[3] = 0x11; - getLastEGVPage[4] = 0x04; - getLastEGVPage[5] = result[3]; - getLastEGVPage[6] = result[2]; - getLastEGVPage[7] = result[1]; - getLastEGVPage[8] = result[0]; - getLastEGVPage[9] = 0x04; - - //Get checksum - int getLastEGVCRC = calculateCRC16(getLastEGVPage, 0, 10); - byte crcByte1 = (byte) (getLastEGVCRC & 0xff); - byte crcByte2 = (byte) ((getLastEGVCRC >> 8) & 0xff); - - getLastEGVPage[10] = crcByte1; - getLastEGVPage[11] = crcByte2; - - try { - rets[c++] = mSerialDevice.write(getLastEGVPage, 200); - } catch (IOException e) { - Log.e(TAG, "Unable to write to serial device", e); - } - - //Get pages - byte[] dexcomDatabasePages = new byte[2122]; - - try { - rets[c++] = mSerialDevice.read(dexcomDatabasePages, 20000); - } catch (IOException e) { - Log.e(TAG, "Unable to read from serial device", e); - } - - //Parse pages - byte [] databasePages = new byte[2112]; - System.arraycopy(dexcomDatabasePages, 4, databasePages, 0, 2112); - return databasePages; - } - - private EGVRecord[] parseDatabasePages(byte[] databasePages) { - - byte [][] fourPages = new byte[4][528]; - int [] recordCounts = new int[4]; - int totalRecordCount = 0; - - //we parse 4 pages at a time, calculate total record count while we do this - for (int i = 0; i < 4; i++) - { - System.arraycopy(databasePages, 528*i, fourPages[i], 0, 528); - recordCounts[i] = fourPages[i][4]; - totalRecordCount = totalRecordCount + recordCounts[i]; - } - - EGVRecord[] recordsToReturn = new EGVRecord[totalRecordCount]; - int k = 0; - - //parse each record, plenty of room for improvement - byte [] tempRecord = new byte[13]; - for (int i = 0; i < 4; i++) - { - for (int j = 0; j < recordCounts[i]; j++) - { - System.arraycopy(fourPages[i], 28 + j*13, tempRecord, 0, 13); - - byte [] eGValue = new byte[]{tempRecord[8],tempRecord[9]}; - - int bGValue = ((eGValue[1]<<8) + (eGValue[0] & 0xff)) & 0x3ff; - - byte [] dateTime = new byte[]{tempRecord[7],tempRecord[6],tempRecord[5],tempRecord[4]}; - - ByteBuffer buffer = ByteBuffer.wrap(dateTime); - int dt = buffer.getInt(); - - SimpleDateFormat f = new SimpleDateFormat("dd-MM-yyyy"); - Date d; - try { - d = f.parse(EPOCH); - } catch (ParseException e) { - Log.e(TAG, "Unable to parse date: " + EPOCH + ", using current time", e); - d = new Date(); - } - - // Epoch is PST, but but having epoch have user timezone added, then don't have to add to the - // display time - long milliseconds = d.getTime(); - - long timeAdd = milliseconds + (1000L*dt); - TimeZone tz = TimeZone.getDefault(); - - if (tz.inDaylightTime(new Date())) - timeAdd = timeAdd - 3600000L; - - Date display = new Date(timeAdd); - byte trendArrow = (byte) (tempRecord[10] & (byte)15); - String trend = "Not Calculated"; - String trendA = "--X"; - - switch (trendArrow) { - - case (0): - trendA = "\u2194"; - trend = "NONE"; - break; - case (1): - trendA = "\u21C8"; - trend = "DoubleUp"; - break; - case (2): - trendA = "\u2191"; - trend = "SingleUp"; - break; - case (3): - trendA = "\u2197"; - trend = "FortyFiveUp"; - break; - case (4): - trendA = "\u2192"; - trend = "Flat"; - break; - case (5): - trendA = "\u2198"; - trend = "FortyFiveDown"; - break; - case (6): - trendA = "\u2193"; - trend = "SingleDown"; - break; - case (7): - trendA = "\u21CA"; - trend = "DoubleDown"; - break; - case (8): - trendA = "\u2194"; - trend = "NOT COMPUTABLE"; - break; - case (9): - trendA = "\u2194"; - trend = "RATE OUT OF RANGE"; - break; - } - - this.trend = trend; - this.displayTime = new SimpleDateFormat("MM/dd/yyy hh:mm:ss aa").format(display); - this.bGValue = String.valueOf(bGValue); - - EGVRecord record = new EGVRecord(); - record.setBGValue(this.bGValue); - record.setDisplayTime(this.displayTime); - record.setTrend(this.trend); - record.setTrendArrow(trendA); - - recordsToReturn[k++] = record; - } - } - return recordsToReturn; - - } - - //TODO: why are we writing CSV? - private void writeLocalCSV(EGVRecord[] mostRecentData, Context context) { - - //Write EGV Binary of last (most recent) data - try { - ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File(context.getFilesDir(), "save.bin"))); //Select where you wish to save the file... - oos.writeObject(mostRecentData[mostRecentData.length - 1]); // write the class as an 'object' - oos.flush(); // flush the stream to insure all of the information was written to 'save.bin' - oos.close();// close the stream - } catch(Exception e) { - Log.e(TAG, "write to OutputStream failed", e); - } - - //Write CSV of EGV from last 4 pages - CSVWriter writer; - try { - - writer = new CSVWriter(new FileWriter(new File(context.getFilesDir(), "hayden.csv")),',', CSVWriter.NO_QUOTE_CHARACTER); - List<String[]> data = new ArrayList<String[]>(); - data.add(new String[] {"GlucoseValue","DisplayTime"}); - - for (int i = 0; i < mostRecentData.length; i++) - { - data.add(new String[] {mostRecentData[i].bGValue, mostRecentData[i].displayTime}); - } - - writer.writeAll(data); - - writer.close(); - } catch (IOException e) { - Log.e(TAG, "write to CSV failed", e); - } - } - - //CRC methods - public static int calculateCRC16 (byte [] buff, int start, int end) { - - int crc = 0; - for (int i = start; i < end; i++) - { - - crc = ((crc >>> 8) | (crc << 8) )& 0xffff; - crc ^= (buff[i] & 0xff); - crc ^= ((crc & 0xff) >> 4); - crc ^= (crc << 12) & 0xffff; - crc ^= ((crc & 0xFF) << 5) & 0xffff; - - } - crc &= 0xffff; - return crc; - - } - - //Convert the packet data - public static int toInt(byte[] b, int flag) { - switch(flag){ - case 0: //BitConverter.FLAG_JAVA: - return (int)(((b[0] & 0xff)<<24) | ((b[1] & 0xff)<<16) | ((b[2] & 0xff)<<8) | (b[3] & 0xff)); - case 1: //BitConverter.FLAG_REVERSE: - return (int)(((b[3] & 0xff)<<24) | ((b[2] & 0xff)<<16) | ((b[1] & 0xff)<<8) | (b[0] & 0xff)); - default: - throw new IllegalArgumentException("BitConverter: toInt"); - } - } - - public static byte[] getBytes(int i, int flag) { - byte[] b = new byte[4]; - switch (flag) { - case 0: - b[0] = (byte) ((i >> 24) & 0xff); - b[1] = (byte) ((i >> 16) & 0xff); - b[2] = (byte) ((i >> 8) & 0xff); - b[3] = (byte) (i & 0xff); - break; - case 1: - b[3] = (byte) ((i >> 24) & 0xff); - b[2] = (byte) ((i >> 16) & 0xff); - b[1] = (byte) ((i >> 8) & 0xff); - b[0] = (byte) (i & 0xff); - break; - default: - break; - } - return b; - } - - @Override - protected Object doInBackground(UsbSerialDriver... params) { - - return new String[]{displayTime, bGValue, trend}; - - } -} diff --git a/app/src/main/java/info/nightscout/android/dexcom/EGVRecord.java b/app/src/main/java/info/nightscout/android/dexcom/EGVRecord.java deleted file mode 100644 index 1f715a5..0000000 --- a/app/src/main/java/info/nightscout/android/dexcom/EGVRecord.java +++ /dev/null @@ -1,30 +0,0 @@ -package info.nightscout.android.dexcom; - -import java.io.Serializable; - -import info.nightscout.android.upload.Record; - -public class EGVRecord extends Record implements Serializable { - public String bGValue = "---"; - public String trend ="---"; - public String trendArrow = "---"; - - - private static final long serialVersionUID = 4654897646L; - - - public void setBGValue (String input) { - this.bGValue = input; - } - - public void setTrend (String input) { - this.trend = input; - } - - public void setTrendArrow (String input) { - this.trendArrow = input; - } - - -} - diff --git a/app/src/main/java/info/nightscout/android/dexcom/ResultSetHelper.java b/app/src/main/java/info/nightscout/android/dexcom/ResultSetHelper.java deleted file mode 100644 index 7eb7c49..0000000 --- a/app/src/main/java/info/nightscout/android/dexcom/ResultSetHelper.java +++ /dev/null @@ -1,33 +0,0 @@ -package info.nightscout.android.dexcom; -/** - Copyright 2005 Bytecode Pty Ltd. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ - -import java.io.IOException; -import java.sql.ResultSet; -import java.sql.SQLException; - -/** - * - * - * - * - * - */ -public interface ResultSetHelper { - public String[] getColumnNames(ResultSet rs) throws SQLException; - - public String[] getColumnValues(ResultSet rs) throws SQLException, IOException; -} diff --git a/app/src/main/java/info/nightscout/android/dexcom/ResultSetHelperService.java b/app/src/main/java/info/nightscout/android/dexcom/ResultSetHelperService.java deleted file mode 100644 index 373671b..0000000 --- a/app/src/main/java/info/nightscout/android/dexcom/ResultSetHelperService.java +++ /dev/null @@ -1,183 +0,0 @@ -package info.nightscout.android.dexcom; -/** - Copyright 2005 Bytecode Pty Ltd. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ -import java.io.IOException; -import java.io.Reader; -import java.math.BigDecimal; -import java.sql.*; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.List; - -/** - * - * - * helper class for processing JDBC ResultSet objects - * - * - */ -public class ResultSetHelperService implements ResultSetHelper { - public static final int CLOBBUFFERSIZE = 2048; - - // note: we want to maintain compatibility with Java 5 VM's - // These types don't exist in Java 5 - private static final int NVARCHAR = -9; - private static final int NCHAR = -15; - private static final int LONGNVARCHAR = -16; - private static final int NCLOB = 2011; - - public String[] getColumnNames(ResultSet rs) throws SQLException { - List<String> names = new ArrayList<String>(); - ResultSetMetaData metadata = rs.getMetaData(); - - for (int i = 0; i < metadata.getColumnCount(); i++) { - names.add(metadata.getColumnName(i+1)); - } - - String[] nameArray = new String[names.size()]; - return names.toArray(nameArray); - } - - public String[] getColumnValues(ResultSet rs) throws SQLException, IOException { - - List<String> values = new ArrayList<String>(); - ResultSetMetaData metadata = rs.getMetaData(); - - for (int i = 0; i < metadata.getColumnCount(); i++) { - values.add(getColumnValue(rs, metadata.getColumnType(i + 1), i + 1)); - } - - String[] valueArray = new String[values.size()]; - return values.toArray(valueArray); - } - - private String handleObject(Object obj){ - return obj == null ? "" : String.valueOf(obj); - } - - private String handleBigDecimal(BigDecimal decimal) { - return decimal == null ? "" : decimal.toString(); - } - - private String handleLong(ResultSet rs, int columnIndex) throws SQLException { - long lv = rs.getLong(columnIndex); - return rs.wasNull() ? "" : Long.toString(lv); - } - - private String handleInteger(ResultSet rs, int columnIndex) throws SQLException { - int i = rs.getInt(columnIndex); - return rs.wasNull() ? "" : Integer.toString(i); - } - - private String handleDate(ResultSet rs, int columnIndex) throws SQLException { - Date date = rs.getDate(columnIndex); - String value = null; - if (date != null) { - SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy"); - value = dateFormat.format(date); - } - return value; - } - - private String handleTime(Time time) { - return time == null ? null : time.toString(); - } - - private String handleTimestamp(Timestamp timestamp) { - SimpleDateFormat timeFormat = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss"); - return timestamp == null ? null : timeFormat.format(timestamp); - } - - private String getColumnValue(ResultSet rs, int colType, int colIndex) - throws SQLException, IOException { - - String value = ""; - - switch (colType) - { - case Types.BIT: - case Types.JAVA_OBJECT: - value = handleObject(rs.getObject(colIndex)); - break; - case Types.BOOLEAN: - boolean b = rs.getBoolean(colIndex); - value = Boolean.valueOf(b).toString(); - break; - case NCLOB: // todo : use rs.getNClob - case Types.CLOB: - Clob c = rs.getClob(colIndex); - if (c != null) { - value = read(c); - } - break; - case Types.BIGINT: - value = handleLong(rs, colIndex); - break; - case Types.DECIMAL: - case Types.DOUBLE: - case Types.FLOAT: - case Types.REAL: - case Types.NUMERIC: - value = handleBigDecimal(rs.getBigDecimal(colIndex)); - break; - case Types.INTEGER: - case Types.TINYINT: - case Types.SMALLINT: - value = handleInteger(rs, colIndex); - break; - case Types.DATE: - value = handleDate(rs, colIndex); - break; - case Types.TIME: - value = handleTime(rs.getTime(colIndex)); - break; - case Types.TIMESTAMP: - value = handleTimestamp(rs.getTimestamp(colIndex)); - break; - case NVARCHAR: // todo : use rs.getNString - case NCHAR: // todo : use rs.getNString - case LONGNVARCHAR: // todo : use rs.getNString - case Types.LONGVARCHAR: - case Types.VARCHAR: - case Types.CHAR: - value = rs.getString(colIndex); - break; - default: - value = ""; - } - - - if (value == null) - { - value = ""; - } - - return value; - - } - - private static String read(Clob c) throws SQLException, IOException - { - StringBuilder sb = new StringBuilder( (int) c.length()); - Reader r = c.getCharacterStream(); - char[] cbuf = new char[CLOBBUFFERSIZE]; - int n; - while ((n = r.read(cbuf, 0, cbuf.length)) != -1) { - sb.append(cbuf, 0, n); - } - return sb.toString(); - } -} diff --git a/app/src/main/java/info/nightscout/android/dexcom/USB/CdcAcmSerialDriver.java b/app/src/main/java/info/nightscout/android/dexcom/USB/CdcAcmSerialDriver.java deleted file mode 100644 index 97fc8b6..0000000 --- a/app/src/main/java/info/nightscout/android/dexcom/USB/CdcAcmSerialDriver.java +++ /dev/null @@ -1,257 +0,0 @@ -package info.nightscout.android.dexcom.USB; - -import android.hardware.usb.*; -import android.util.Log; - -import java.io.IOException; - -//import com.hoho.android.usbserial.driver.UsbId; - -/** - * USB CDC/ACM serial driver implementation. - * - * @author mike wakerly (opensource@hoho.com) - * @see <a - * href="http://www.usb.org/developers/devclass_docs/usbcdc11.pdf">Universal - * Serial Bus Class Definitions for Communication Devices, v1.1</a> - */ -public class CdcAcmSerialDriver extends CommonUsbSerialDriver { - - private final String TAG = CdcAcmSerialDriver.class.getSimpleName(); - - private UsbInterface mControlInterface; - private UsbInterface mDataInterface; - - private UsbEndpoint mControlEndpoint; - private UsbEndpoint mReadEndpoint; - private UsbEndpoint mWriteEndpoint; - - private boolean mRts = false; - private boolean mDtr = false; - - private boolean isConnectionOpen = false; - - private static final int USB_RECIP_INTERFACE = 0x01; - private static final int USB_RT_ACM = UsbConstants.USB_TYPE_CLASS | USB_RECIP_INTERFACE; - - private static final int SET_LINE_CODING = 0x20; // USB CDC 1.1 section 6.2 - private static final int GET_LINE_CODING = 0x21; - private static final int SET_CONTROL_LINE_STATE = 0x22; - private static final int SEND_BREAK = 0x23; - private static final String SET_POWER_ON_COMMAND = "echo 'on' > \"/sys/bus/usb/devices/1-1/power/level\""; - - public CdcAcmSerialDriver(UsbDevice device, UsbDeviceConnection connection) { - super(device, connection); - } - - @Override - public void open() throws IOException { - Log.d(TAG, "claiming interfaces, count=" + mDevice.getInterfaceCount()); - - Log.d(TAG, "Claiming control interface."); - mControlInterface = mDevice.getInterface(0); - Log.d(TAG, "Control iface=" + mControlInterface); - // class should be USB_CLASS_COMM - - if (!mConnection.claimInterface(mControlInterface, true)) { - isConnectionOpen = false; - throw new IOException("Could not claim control interface."); - } - mControlEndpoint = mControlInterface.getEndpoint(0); - Log.d(TAG, "Control endpoint direction: " + mControlEndpoint.getDirection()); - - Log.d(TAG, "Claiming data interface."); - mDataInterface = mDevice.getInterface(1); - Log.d(TAG, "data iface=" + mDataInterface); - // class should be USB_CLASS_CDC_DATA - - if (!mConnection.claimInterface(mDataInterface, true)) { - isConnectionOpen = false; - throw new IOException("Could not claim data interface."); - } - mReadEndpoint = mDataInterface.getEndpoint(1); - Log.d(TAG, "Read endpoint direction: " + mReadEndpoint.getDirection()); - mWriteEndpoint = mDataInterface.getEndpoint(0); - Log.d(TAG, "Write endpoint direction: " + mWriteEndpoint.getDirection()); - isConnectionOpen = true; - } - - private int sendAcmControlMessage(int request, int value, byte[] buf) { - return mConnection.controlTransfer( - USB_RT_ACM, request, value, 0, buf, buf != null ? buf.length : 0, 5000); - } - - @Override - public void close() throws IOException { - mConnection.close(); - isConnectionOpen = false; - } - - @Override - public int read(byte[] dest, int timeoutMillis) throws IOException { - final int numBytesRead; - synchronized (mReadBufferLock) { - int readAmt = Math.min(dest.length, mReadBuffer.length); - numBytesRead = mConnection.bulkTransfer(mReadEndpoint, mReadBuffer, readAmt, - timeoutMillis); - if (numBytesRead < 0) { - // This sucks: we get -1 on timeout, not 0 as preferred. - // We *should* use UsbRequest, except it has a bug/api oversight - // where there is no way to determine the number of bytes read - // in response :\ -- http://b.android.com/28023 - return 0; - } - System.arraycopy(mReadBuffer, 0, dest, 0, numBytesRead); - } - return numBytesRead; - } - - @Override - public int write(byte[] src, int timeoutMillis) throws IOException { - // TODO(mikey): Nearly identical to FtdiSerial write. Refactor. - int offset = 0; - - while (offset < src.length) { - final int writeLength; - final int amtWritten; - - synchronized (mWriteBufferLock) { - final byte[] writeBuffer; - - writeLength = Math.min(src.length - offset, mWriteBuffer.length); - if (offset == 0) { - writeBuffer = src; - } else { - // bulkTransfer does not support offsets, make a copy. - System.arraycopy(src, offset, mWriteBuffer, 0, writeLength); - writeBuffer = mWriteBuffer; - } - - amtWritten = mConnection.bulkTransfer(mWriteEndpoint, writeBuffer, writeLength, - timeoutMillis); - } - if (amtWritten <= 0) { - throw new IOException("Error writing " + writeLength - + " bytes at offset " + offset + " length=" + src.length); - } - - Log.d(TAG, "Wrote amt=" + amtWritten + " attempted=" + writeLength); - offset += amtWritten; - } - return offset; - } - - @Override - public void setParameters(int baudRate, int dataBits, int stopBits, int parity) { - byte stopBitsByte; - switch (stopBits) { - case STOPBITS_1: stopBitsByte = 0; break; - case STOPBITS_1_5: stopBitsByte = 1; break; - case STOPBITS_2: stopBitsByte = 2; break; - default: throw new IllegalArgumentException("Bad value for stopBits: " + stopBits); - } - - byte parityBitesByte; - switch (parity) { - case PARITY_NONE: parityBitesByte = 0; break; - case PARITY_ODD: parityBitesByte = 1; break; - case PARITY_EVEN: parityBitesByte = 2; break; - case PARITY_MARK: parityBitesByte = 3; break; - case PARITY_SPACE: parityBitesByte = 4; break; - default: throw new IllegalArgumentException("Bad value for parity: " + parity); - } - - byte[] msg = { - (byte) ( baudRate & 0xff), - (byte) ((baudRate >> 8 ) & 0xff), - (byte) ((baudRate >> 16) & 0xff), - (byte) ((baudRate >> 24) & 0xff), - stopBitsByte, - parityBitesByte, - (byte) dataBits}; - sendAcmControlMessage(SET_LINE_CODING, 0, msg); - } - - @Override - public boolean getCD() throws IOException { - return false; // TODO - } - - @Override - public boolean getCTS() throws IOException { - return false; // TODO - } - - @Override - public boolean getDSR() throws IOException { - return false; // TODO - } - - @Override - public boolean getDTR() throws IOException { - return mDtr; - } - - @Override - public void setDTR(boolean value) throws IOException { - mDtr = value; - setDtrRts(); - } - - @Override - public boolean getRI() throws IOException { - return false; // TODO - } - - @Override - public boolean getRTS() throws IOException { - return mRts; - } - - @Override - public void setRTS(boolean value) throws IOException { - mRts = value; - setDtrRts(); - } - - private void setDtrRts() { - int value = (mRts ? 0x2 : 0) | (mDtr ? 0x1 : 0); - sendAcmControlMessage(SET_CONTROL_LINE_STATE, value, null); - } - - @Override - public boolean isConnectionOpen(){ - return isConnectionOpen; - } - - -/* public static Map<Integer, int[]> getSupportedDevices() { - final Map<Integer, int[]> supportedDevices = new LinkedHashMap<Integer, int[]>(); - supportedDevices.put(Integer.valueOf(UsbId.VENDOR_ARDUINO), - new int[] { - UsbId.ARDUINO_UNO, - UsbId.ARDUINO_UNO_R3, - UsbId.ARDUINO_MEGA_2560, - UsbId.ARDUINO_MEGA_2560_R3, - UsbId.ARDUINO_SERIAL_ADAPTER, - UsbId.ARDUINO_SERIAL_ADAPTER_R3, - UsbId.ARDUINO_MEGA_ADK, - UsbId.ARDUINO_MEGA_ADK_R3, - UsbId.ARDUINO_LEONARDO, - }); - supportedDevices.put(Integer.valueOf(UsbId.VENDOR_VAN_OOIJEN_TECH), - new int[] { - UsbId.VAN_OOIJEN_TECH_TEENSYDUINO_SERIAL, - }); - supportedDevices.put(Integer.valueOf(UsbId.VENDOR_ATMEL), - new int[] { - UsbId.ATMEL_LUFA_CDC_DEMO_APP, - }); - supportedDevices.put(Integer.valueOf(UsbId.VENDOR_LEAFLABS), - new int[] { - UsbId.LEAFLABS_MAPLE, - }); - return supportedDevices; - }*/ - -} diff --git a/app/src/main/java/info/nightscout/android/dexcom/USB/CommonUsbSerialDriver.java b/app/src/main/java/info/nightscout/android/dexcom/USB/CommonUsbSerialDriver.java deleted file mode 100644 index 12efe9a..0000000 --- a/app/src/main/java/info/nightscout/android/dexcom/USB/CommonUsbSerialDriver.java +++ /dev/null @@ -1,138 +0,0 @@ -/* Copyright 2013 Google Inc. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * Project home page: http://code.google.com/p/usb-serial-for-android/ - */ - -package info.nightscout.android.dexcom.USB; - -import android.hardware.usb.UsbDevice; -import android.hardware.usb.UsbDeviceConnection; - -import java.io.IOException; - - -/** - * A base class shared by several driver implementations. - * - * @author mike wakerly (opensource@hoho.com) - */ -abstract class CommonUsbSerialDriver implements UsbSerialDriver { - - public static final int DEFAULT_READ_BUFFER_SIZE = 16 * 1024; - public static final int DEFAULT_WRITE_BUFFER_SIZE = 16 * 1024; - - protected final UsbDevice mDevice; - protected final UsbDeviceConnection mConnection; - - protected final Object mReadBufferLock = new Object(); - protected final Object mWriteBufferLock = new Object(); - - /** Internal read buffer. Guarded by {@link #mReadBufferLock}. */ - protected byte[] mReadBuffer; - - /** Internal write buffer. Guarded by {@link #mWriteBufferLock}. */ - protected byte[] mWriteBuffer; - - public CommonUsbSerialDriver(UsbDevice device, UsbDeviceConnection connection) { - mDevice = device; - mConnection = connection; - - mReadBuffer = new byte[DEFAULT_READ_BUFFER_SIZE]; - mWriteBuffer = new byte[DEFAULT_WRITE_BUFFER_SIZE]; - } - - /** - * Returns the currently-bound USB device. - * - * @return the device - */ - public final UsbDevice getDevice() { - return mDevice; - } - - /** - * Sets the size of the internal buffer used to exchange data with the USB - * stack for read operations. Most users should not need to change this. - * - * @param bufferSize the size in bytes - */ - public final void setReadBufferSize(int bufferSize) { - synchronized (mReadBufferLock) { - if (bufferSize == mReadBuffer.length) { - return; - } - mReadBuffer = new byte[bufferSize]; - } - } - - /** - * Sets the size of the internal buffer used to exchange data with the USB - * stack for write operations. Most users should not need to change this. - * - * @param bufferSize the size in bytes - */ - public final void setWriteBufferSize(int bufferSize) { - synchronized (mWriteBufferLock) { - if (bufferSize == mWriteBuffer.length) { - return; - } - mWriteBuffer = new byte[bufferSize]; - } - } - - @Override - public abstract void open() throws IOException; - - @Override - public abstract void close() throws IOException; - - @Override - public abstract int read(final byte[] dest, final int timeoutMillis) throws IOException; - - @Override - public abstract int write(final byte[] src, final int timeoutMillis) throws IOException; - - @Override - public abstract void setParameters( - int baudRate, int dataBits, int stopBits, int parity) throws IOException; - - @Override - public abstract boolean getCD() throws IOException; - - @Override - public abstract boolean getCTS() throws IOException; - - @Override - public abstract boolean getDSR() throws IOException; - - @Override - public abstract boolean getDTR() throws IOException; - - @Override - public abstract void setDTR(boolean value) throws IOException; - - @Override - public abstract boolean getRI() throws IOException; - - @Override - public abstract boolean getRTS() throws IOException; - - @Override - public abstract void setRTS(boolean value) throws IOException; - -} diff --git a/app/src/main/java/info/nightscout/android/dexcom/USB/SerialInputOutputManager.java b/app/src/main/java/info/nightscout/android/dexcom/USB/SerialInputOutputManager.java deleted file mode 100644 index 5e364dd..0000000 --- a/app/src/main/java/info/nightscout/android/dexcom/USB/SerialInputOutputManager.java +++ /dev/null @@ -1,187 +0,0 @@ -/* Copyright 2011 Google Inc. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * Project home page: http://code.google.com/p/usb-serial-for-android/ - */ - -package info.nightscout.android.dexcom.USB; - -import android.util.Log; - -import java.io.IOException; -import java.nio.ByteBuffer; - - -/** - * Utility class which services a {@link UsbSerialDriver} in its {@link #run()} - * method. - * - * @author mike wakerly (opensource@hoho.com) - */ -public class SerialInputOutputManager implements Runnable { - - private static final String TAG = SerialInputOutputManager.class.getSimpleName(); - private static final boolean DEBUG = true; - - private static final int READ_WAIT_MILLIS = 200; - private static final int BUFSIZ = 4096; - - private final UsbSerialDriver mDriver; - - private final ByteBuffer mReadBuffer = ByteBuffer.allocate(BUFSIZ); - - // Synchronized by 'mWriteBuffer' - private final ByteBuffer mWriteBuffer = ByteBuffer.allocate(BUFSIZ); - - private enum State { - STOPPED, - RUNNING, - STOPPING - } - - // Synchronized by 'this' - private State mState = State.STOPPED; - - // Synchronized by 'this' - private Listener mListener; - - public interface Listener { - /** - * Called when new incoming data is available. - */ - public void onNewData(byte[] data); - - /** - * Called when {@link SerialInputOutputManager#run()} aborts due to an - * error. - */ - public void onRunError(Exception e); - } - - /** - * Creates a new instance with no listener. - */ - public SerialInputOutputManager(UsbSerialDriver driver) { - this(driver, null); - } - - /** - * Creates a new instance with the provided listener. - */ - public SerialInputOutputManager(UsbSerialDriver driver, Listener listener) { - mDriver = driver; - mListener = listener; - } - - public synchronized void setListener(Listener listener) { - mListener = listener; - } - - public synchronized Listener getListener() { - return mListener; - } - - public void writeAsync(byte[] data) { - synchronized (mWriteBuffer) { - mWriteBuffer.put(data); - } - } - - public synchronized void stop() { - if (getState() == State.RUNNING) { - Log.i(TAG, "Stop requested"); - mState = State.STOPPING; - } - } - - private synchronized State getState() { - return mState; - } - - /** - * Continuously services the read and write buffers until {@link #stop()} is - * called, or until a driver exception is raised. - * - * NOTE(mikey): Uses inefficient read/write-with-timeout. - * TODO(mikey): Read asynchronously with {@link android.hardware.usb.UsbRequest#queue(java.nio.ByteBuffer, int)} - */ - @Override - public void run() { - synchronized (this) { - if (getState() != State.STOPPED) { - throw new IllegalStateException("Already running."); - } - mState = State.RUNNING; - } - - Log.i(TAG, "Running .."); - try { - while (true) { - if (getState() != State.RUNNING) { - Log.i(TAG, "Stopping mState=" + getState()); - break; - } - step(); - } - } catch (Exception e) { - Log.w(TAG, "Run ending due to exception: " + e.getMessage(), e); - final Listener listener = getListener(); - if (listener != null) { - listener.onRunError(e); - } - } finally { - synchronized (this) { - mState = State.STOPPED; - Log.i(TAG, "Stopped."); - } - } - } - - private void step() throws IOException { - // Handle incoming data. - int len = mDriver.read(mReadBuffer.array(), READ_WAIT_MILLIS); - if (len > 0) { - if (DEBUG) Log.d(TAG, "Read data len=" + len); - final Listener listener = getListener(); - if (listener != null) { - final byte[] data = new byte[len]; - mReadBuffer.get(data, 0, len); - listener.onNewData(data); - } - mReadBuffer.clear(); - } - - // Handle outgoing data. - byte[] outBuff = null; - synchronized (mWriteBuffer) { - if (mWriteBuffer.position() > 0) { - len = mWriteBuffer.position(); - outBuff = new byte[len]; - mWriteBuffer.rewind(); - mWriteBuffer.get(outBuff, 0, len); - mWriteBuffer.clear(); - } - } - if (outBuff != null) { - if (DEBUG) { - Log.d(TAG, "Writing data len=" + len); - } - mDriver.write(outBuff, READ_WAIT_MILLIS); - } - } - -} diff --git a/app/src/main/java/info/nightscout/android/dexcom/USB/UsbSerialDriver.java b/app/src/main/java/info/nightscout/android/dexcom/USB/UsbSerialDriver.java deleted file mode 100644 index 1c6fde0..0000000 --- a/app/src/main/java/info/nightscout/android/dexcom/USB/UsbSerialDriver.java +++ /dev/null @@ -1,207 +0,0 @@ -/* Copyright 2011 Google Inc. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * Project home page: http://code.google.com/p/usb-serial-for-android/ - */ - -package info.nightscout.android.dexcom.USB; - -import java.io.IOException; - -/** - * Driver interface for a USB serial device. - * - * @author mike wakerly (opensource@hoho.com) - */ -public interface UsbSerialDriver { - - /** 5 data bits. */ - public static final int DATABITS_5 = 5; - - /** 6 data bits. */ - public static final int DATABITS_6 = 6; - - /** 7 data bits. */ - public static final int DATABITS_7 = 7; - - /** 8 data bits. */ - public static final int DATABITS_8 = 8; - - /** No flow control. */ - public static final int FLOWCONTROL_NONE = 0; - - /** RTS/CTS input flow control. */ - public static final int FLOWCONTROL_RTSCTS_IN = 1; - - /** RTS/CTS output flow control. */ - public static final int FLOWCONTROL_RTSCTS_OUT = 2; - - /** XON/XOFF input flow control. */ - public static final int FLOWCONTROL_XONXOFF_IN = 4; - - /** XON/XOFF output flow control. */ - public static final int FLOWCONTROL_XONXOFF_OUT = 8; - - /** No parity. */ - public static final int PARITY_NONE = 0; - - /** Odd parity. */ - public static final int PARITY_ODD = 1; - - /** Even parity. */ - public static final int PARITY_EVEN = 2; - - /** Mark parity. */ - public static final int PARITY_MARK = 3; - - /** Space parity. */ - public static final int PARITY_SPACE = 4; - - /** 1 stop bit. */ - public static final int STOPBITS_1 = 1; - - /** 1.5 stop bits. */ - public static final int STOPBITS_1_5 = 3; - - /** 2 stop bits. */ - public static final int STOPBITS_2 = 2; - - /** - * Opens and initializes the device as a USB serial device. Upon success, - * caller must ensure that {@link #close()} is eventually called. - * - * @throws java.io.IOException on error opening or initializing the device. - */ - public void open() throws IOException; - - /** - * Closes the serial device. - * - * @throws java.io.IOException on error closing the device. - */ - public void close() throws IOException; - - /** - * Reads as many bytes as possible into the destination buffer. - * - * @param dest the destination byte buffer - * @param timeoutMillis the timeout for reading - * @return the actual number of bytes read - * @throws java.io.IOException if an error occurred during reading - */ - public int read(final byte[] dest, final int timeoutMillis) throws IOException; - - /** - * Writes as many bytes as possible from the source buffer. - * - * @param src the source byte buffer - * @param timeoutMillis the timeout for writing - * @return the actual number of bytes written - * @throws java.io.IOException if an error occurred during writing - */ - public int write(final byte[] src, final int timeoutMillis) throws IOException; - - /** - * Sets various serial port parameters. - * - * @param baudRate baud rate as an integer, for example {@code 115200}. - * @param dataBits one of {@link #DATABITS_5}, {@link #DATABITS_6}, - * {@link #DATABITS_7}, or {@link #DATABITS_8}. - * @param stopBits one of {@link #STOPBITS_1}, {@link #STOPBITS_1_5}, or - * {@link #STOPBITS_2}. - * @param parity one of {@link #PARITY_NONE}, {@link #PARITY_ODD}, - * {@link #PARITY_EVEN}, {@link #PARITY_MARK}, or - * {@link #PARITY_SPACE}. - * @throws java.io.IOException on error setting the port parameters - */ - public void setParameters( - int baudRate, int dataBits, int stopBits, int parity) throws IOException; - - /** - * Gets the CD (Carrier Detect) bit from the underlying UART. - * - * @return the current state, or {@code false} if not supported. - * @throws java.io.IOException if an error occurred during reading - */ - public boolean getCD() throws IOException; - - /** - * Gets the CTS (Clear To Send) bit from the underlying UART. - * - * @return the current state, or {@code false} if not supported. - * @throws java.io.IOException if an error occurred during reading - */ - public boolean getCTS() throws IOException; - - /** - * Gets the DSR (Data Set Ready) bit from the underlying UART. - * - * @return the current state, or {@code false} if not supported. - * @throws java.io.IOException if an error occurred during reading - */ - public boolean getDSR() throws IOException; - - /** - * Gets the DTR (Data Terminal Ready) bit from the underlying UART. - * - * @return the current state, or {@code false} if not supported. - * @throws java.io.IOException if an error occurred during reading - */ - public boolean getDTR() throws IOException; - - /** - * Sets the DTR (Data Terminal Ready) bit on the underlying UART, if - * supported. - * - * @param value the value to set - * @throws java.io.IOException if an error occurred during writing - */ - public void setDTR(boolean value) throws IOException; - - /** - * Gets the RI (Ring Indicator) bit from the underlying UART. - * - * @return the current state, or {@code false} if not supported. - * @throws java.io.IOException if an error occurred during reading - */ - public boolean getRI() throws IOException; - - /** - * Gets the RTS (Request To Send) bit from the underlying UART. - * - * @return the current state, or {@code false} if not supported. - * @throws java.io.IOException if an error occurred during reading - */ - public boolean getRTS() throws IOException; - - /** - * Sets the RTS (Request To Send) bit on the underlying UART, if - * supported. - * - * @param value the value to set - * @throws java.io.IOException if an error occurred during writing - */ - public void setRTS(boolean value) throws IOException; - /** - * Just to check if this device has the connection openned and claimed - * - * @return boolean - * @throws java.io.IOException if an error occurred during writing - */ - public boolean isConnectionOpen(); - -} diff --git a/app/src/main/java/info/nightscout/android/dexcom/USB/UsbSerialProber.java b/app/src/main/java/info/nightscout/android/dexcom/USB/UsbSerialProber.java deleted file mode 100644 index 6daa6b8..0000000 --- a/app/src/main/java/info/nightscout/android/dexcom/USB/UsbSerialProber.java +++ /dev/null @@ -1,171 +0,0 @@ -/* Copyright 2011 Google Inc. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * Project home page: http://code.google.com/p/usb-serial-for-android/ - */ - -package info.nightscout.android.dexcom.USB; - -import android.hardware.usb.UsbDevice; -import android.hardware.usb.UsbDeviceConnection; -import android.hardware.usb.UsbManager; -import android.util.Log; - -import java.util.Map; - -//import com.hoho.android.usbserial.driver.Cp2102SerialDriver; -//import com.hoho.android.usbserial.driver.FtdiSerialDriver; - -/** - * Helper class to assist in detecting and building {@link UsbSerialDriver} - * instances from available hardware. - * - * @author mike wakerly (opensource@hoho.com) - */ -public enum UsbSerialProber { - - // TODO(mikey): Too much boilerplate. - - /** - * Prober for {@link FtdiSerialDriver}. - * - * @see FtdiSerialDriver - */ -/* FTDI_SERIAL { - @Override - public UsbSerialDriver getDevice(final UsbManager manager, final UsbDevice usbDevice) { - if (!testIfSupported(usbDevice, FtdiSerialDriver.getSupportedDevices())) { - return null; - } - final UsbDeviceConnection connection = manager.openDevice(usbDevice); - if (connection == null) { - return null; - } - return new FtdiSerialDriver(usbDevice, connection); - } - },*/ - - CDC_ACM_SERIAL { - @Override - public UsbSerialDriver getDevice(UsbManager manager, UsbDevice usbDevice) { -// if (!testIfSupported(usbDevice, CdcAcmSerialDriver.getSupportedDevices())) { -// return null; -// } - final UsbDeviceConnection connection = manager.openDevice(usbDevice); - if (connection == null) { - return null; - } - return new CdcAcmSerialDriver(usbDevice, connection); - } - }; //, - -/* SILAB_SERIAL { - @Override - public UsbSerialDriver getDevice(final UsbManager manager, final UsbDevice usbDevice) { - if (!testIfSupported(usbDevice, Cp2102SerialDriver.getSupportedDevices())) { - return null; - } - final UsbDeviceConnection connection = manager.openDevice(usbDevice); - if (connection == null) { - return null; - } - return new Cp2102SerialDriver(usbDevice, connection); - } - };*/ - - private static final String TAG = UsbSerialProber.class.getSimpleName(); - - /** - * Builds a new {@link UsbSerialDriver} instance from the raw device, or - * returns <code>null</code> if it could not be built (for example, if the - * probe failed). - * - * @param manager the {@link android.hardware.usb.UsbManager} to use - * @param usbDevice the raw {@link android.hardware.usb.UsbDevice} to use - * @return the first available {@link UsbSerialDriver}, or {@code null} if - * no devices could be acquired - */ - public abstract UsbSerialDriver getDevice(final UsbManager manager, final UsbDevice usbDevice); - - /** - * Acquires and returns the first available serial device among all - * available {@link android.hardware.usb.UsbDevice}s, or returns {@code null} if no device could - * be acquired. - * - * @param usbManager the {@link android.hardware.usb.UsbManager} to use - * @return the first available {@link UsbSerialDriver}, or {@code null} if - * no devices could be acquired - */ - public static UsbSerialDriver acquire(final UsbManager usbManager) { - for (final UsbDevice usbDevice : usbManager.getDeviceList().values()) { - final UsbSerialDriver probedDevice = acquire(usbManager, usbDevice); - if (probedDevice != null) { - return probedDevice; - } - } - return null; - } - - /** - * Builds and returns a new {@link UsbSerialDriver} from the given - * {@link android.hardware.usb.UsbDevice}, or returns {@code null} if no drivers supported this - * device. - * - * @param usbManager the {@link android.hardware.usb.UsbManager} to use - * @param usbDevice the {@link android.hardware.usb.UsbDevice} to use - * @return a new {@link UsbSerialDriver}, or {@code null} if no devices - * could be acquired - */ - public static UsbSerialDriver acquire(final UsbManager usbManager, final UsbDevice usbDevice) { - if (!usbManager.hasPermission(usbDevice)) { - Log.i(TAG, "No permission for " + usbDevice.getVendorId() + " " + usbDevice.getProductId()); - return null; - } - for (final UsbSerialProber prober : values()) { - final UsbSerialDriver probedDevice = prober.getDevice(usbManager, usbDevice); - if (probedDevice != null) { - return probedDevice; - } - } - return null; - } - - /** - * Returns {@code true} if the given device is found in the vendor/product map. - * - * @param usbDevice the device to test - * @param supportedDevices map of vendor ids to product id(s) - * @return {@code true} if supported - */ - private static boolean testIfSupported(final UsbDevice usbDevice, - final Map<Integer, int[]> supportedDevices) { - final int[] supportedProducts = supportedDevices.get( - Integer.valueOf(usbDevice.getVendorId())); - if (supportedProducts == null) { - return false; - } - - final int productId = usbDevice.getProductId(); - for (int supportedProductId : supportedProducts) { - if (productId == supportedProductId) { - return true; - } - } - return false; - } - -} diff --git a/app/src/main/java/info/nightscout/android/medtronic/CommandSenderThread.java b/app/src/main/java/info/nightscout/android/medtronic/CommandSenderThread.java deleted file mode 100644 index 52f9b98..0000000 --- a/app/src/main/java/info/nightscout/android/medtronic/CommandSenderThread.java +++ /dev/null @@ -1,388 +0,0 @@ -package info.nightscout.android.medtronic; - -import android.os.Bundle; -import android.os.Handler; -import android.os.Message; -import android.os.Messenger; -import android.os.RemoteException; -import android.util.Log; - -import info.nightscout.android.dexcom.USB.HexDump; -import com.physicaloid.lib.Physicaloid; - -import org.slf4j.LoggerFactory; - -import java.util.ArrayList; - -import ch.qos.logback.classic.Logger; - - -/** - * Class: CommandSenderThread - * This class manages the command send operations over the Medtronic's pump. - * This class also access the shared variables located in MedtronicReader class to know when the application is commanding or it has finished a request. - * @author lmmarguenda - * - */ -public class CommandSenderThread implements Runnable{ - protected Logger log = (Logger) LoggerFactory.getLogger(MedtronicReader.class.getName()); - protected byte[] commandList; - protected MedtronicReader reader; - protected byte[] idPump; - protected Physicaloid mSerialDevice; - protected Handler mHandler3 = new Handler(); - protected Handler mHandler4 = null; - protected int index = 0; - protected WriterThread wThread = new WriterThread(); - protected ArrayList<Messenger> mClients = new ArrayList<Messenger>(); - long waitTime = MedtronicConstants.WAIT_ANSWER; - int withoutConfirmation = 0; - - - public CommandSenderThread(MedtronicReader reader,byte[]idPump,Physicaloid mSerialDevice, Handler mHandler4){ - this.reader = reader; - this.idPump = idPump; - this.mSerialDevice = mSerialDevice; - this.mHandler4 = mHandler4; - } - - /** - * Constructor - * @param commandList, array of commands to send in order. - * @param mClient, communication with the UI. - * @param reader, MedtronicReader instance. - * @param idPump - * @param mSerialDevice - * @param mHandler4, Handler which has started this process. - */ - public CommandSenderThread(byte[]commandList, ArrayList<Messenger> mClients, MedtronicReader reader,byte[]idPump,Physicaloid mSerialDevice, Handler mHandler4){ - this.commandList = commandList; - this.mClients = mClients; - this.reader = reader; - this.idPump = idPump; - this.mSerialDevice = mSerialDevice; - this.mHandler4 = mHandler4; - } - - - /** - * Runnable Method, It tries to send all the commands in "commanList", in order to do that, - * It creates a second handler calling WriterThread to manage the command send. - */ - public void run() { - try{ - //sendMessageToUI("sending Command "+ HexDump.toHexString(command), false); - if (index == 0){ - sendMessageToUI("Starting Pump info request...", true); - } - if (wThread.retries >= MedtronicConstants.NUMBER_OF_RETRIES){ - mHandler3.removeCallbacks(wThread); - synchronized (reader.sendingCommandLock) { - reader.sendingCommand = false; - } - synchronized (reader.waitingCommandLock) { - reader.waitingCommand = false; - reader.lastCommandSend = null; - } - synchronized (reader.processingCommandLock) { - reader.processingCommand = false; - } - sendMessageToUI("Timeout expired executing command list", false); - synchronized (reader.processingCommandLock) { - reader.processingCommand = false; - } - synchronized (reader.waitingCommandLock) { - reader.waitingCommand = false; - reader.lastCommandSend = null; - } - return; - } - - if (index >= commandList.length){ - synchronized (reader.processingCommandLock) { - reader.processingCommand = false; - } - synchronized (reader.waitingCommandLock) { - reader.waitingCommand = false; - reader.lastCommandSend = null; - } - return; - } - if (withoutConfirmation <= 0){ - synchronized (reader.waitingCommandLock) { - reader.waitingCommand = true; - reader.lastCommandSend = null; - } - }else{ - synchronized (reader.waitingCommandLock) { - reader.waitingCommand = false; - reader.lastCommandSend = null; - } - } - byte command = commandList[index]; - //sendMessageToUI("COMMAND SENDER: sending Command "+ HexDump.toHexString(command), false); - wThread.retries = -1; - wThread.command = command; - wThread.instance = this; - mHandler3.post(wThread); - index++; - }catch(Exception e){ - StringBuffer sb1 = new StringBuffer(""); - sb1.append("EXCEPTION!!!!!! "+ e.getMessage()+" "+e.getCause()); - for (StackTraceElement st : e.getStackTrace()){ - sb1.append(st.toString()); - } - sendMessageToUI(sb1.toString(), false); - } - - } - /** - * Sends a message to the serial device - * @param command, Medtronic command from MedtronicConstants.class - * @param repeat, Number of times to send this message. - * @return bytes written - */ - protected int sendMedtronicPumpRequest(byte command, byte repeat) { - try{ - if (idPump != null && idPump.length > 0){ - byte[] readSystemTime = new byte[6+idPump.length]; - int i = 0; - readSystemTime[0] = (byte)0x81; - readSystemTime[1] = (byte)0x06; - readSystemTime[2] = repeat; - readSystemTime[3] = (byte)MedtronicConstants.MEDTRONIC_PUMP; - for (i=0; i < idPump.length; i++) - readSystemTime[i+4] = (byte)idPump[i]; - readSystemTime[idPump.length + 4] = command; - readSystemTime[idPump.length + 5] = (byte)0x00; - log.debug("pump request sent ");//+ HexDump.toHexString(readSystemTime)); - int resultWrite = mSerialDevice.write(readSystemTime); - return resultWrite; - } - }catch(Exception e){ - StringBuffer sb1 = new StringBuffer(""); - sb1.append("EXCEPTION!!!!!! "+ e.getMessage()+" "+e.getCause()); - for (StackTraceElement st : e.getStackTrace()){ - sb1.append(st.toString()); - } - sendMessageToUI(sb1.toString(), false); - } - - return -1; - } - /** - * Sends a message to the serial device - * @param command, Medtronic command from MedtronicConstants.class - * @param repeat, Number of times to send this message. - * @return bytes written - */ - protected int sendMedtronicPumpCommand(byte command, byte repeat, byte[]postCommand) { - try{ - if (idPump != null && idPump.length > 0){ - int pCLength = 0; - if (postCommand != null) - pCLength = postCommand.length; - byte[] readSystemTime = new byte[6+idPump.length+pCLength]; - int i = 0; - int size= 2 +idPump.length+pCLength+1; - byte[] sizByte = HexDump.hexStringToByteArray(HexDump.toHexString(size)); - log.debug("sizByte "+ HexDump.toHexString(sizByte)); - readSystemTime[0] = (byte)0x81; - readSystemTime[1] = (byte)sizByte[sizByte.length-1]; - readSystemTime[2] = repeat; - readSystemTime[3] = (byte)MedtronicConstants.MEDTRONIC_PUMP; - for (i=0; i < idPump.length; i++) - readSystemTime[i+4] = (byte)idPump[i]; - readSystemTime[idPump.length + 4] = command; - log.debug("postcommadnLength ");//+ postCommand.length); - for (i=0; i < postCommand.length; i++) - readSystemTime[idPump.length + 5 + i] = (byte)postCommand[i]; - log.debug("command sent "+ HexDump.toHexString(readSystemTime)); - int resultWrite = mSerialDevice.write(readSystemTime); - return resultWrite; - } - }catch(Exception e){ - StringBuffer sb1 = new StringBuffer(""); - sb1.append("EXCEPTION!!!!!! "+ e.getMessage()+" "+e.getCause()); - for (StackTraceElement st : e.getStackTrace()){ - sb1.append(st.toString()); - } - sendMessageToUI(sb1.toString(), false); - } - - return -1; - } - /** - * Runnable to manage the command send, retries included. - * @author lmmarguenda - * - */ - class WriterThread implements Runnable{ - byte command; - int retries = -1; //first retry does not count; - boolean sent = false; - boolean isRequest = true; - byte[] postCommandBytes = null; - CommandSenderThread instance = null; - int timeoutSending = 0; - public WriterThread(){ - - } - public void setCommand(byte command){ - this.command = command; - } - - public void run(){ - try{ - synchronized (reader.processingCommandLock) { - if (!reader.processingCommand) - return; - } - boolean isWakeUp = false; - byte repeat = (byte)0x01; - if (command == MedtronicConstants.MEDTRONIC_WAKE_UP){ - repeat = (byte)0xff; - isWakeUp = true; - } - log.debug("sendcommand"); - - synchronized (reader.sendingCommandLock) { - if (reader.sendingCommand){ - if (timeoutSending < 11){ - log.debug("timeoutSending++ "+timeoutSending); - mHandler3.removeCallbacks(wThread); - mHandler3.postDelayed(wThread, 3000); - timeoutSending++; - return; - }else{ - reader.sendingCommand = false; - timeoutSending = 0; - } - - } - } - log.debug("timeoutSending "+timeoutSending); - timeoutSending = 0; - if (sent){ - log.debug("sent "); - //if I have sent it, I will wait once to give the "enlite" time to answer, next time I will retry. - sent = false; - synchronized (reader.waitingCommandLock) { - if (!reader.waitingCommand){ - retries = 0; - mHandler4.removeCallbacks(instance); - mHandler4.post(instance); - return;//exit I have received the answer expected - } - } - long delay = waitTime; - if (isWakeUp) - delay = 10000; - mHandler3.postDelayed(wThread, delay); - return; - } - synchronized (reader.waitingCommandLock) { - if (!reader.waitingCommand){ - if (withoutConfirmation > 0){ - log.debug("sending command without expecting confirmation still send -->"+ (withoutConfirmation--)); - if (isRequest || postCommandBytes == null || postCommandBytes.length == 0) - sendMedtronicPumpRequest(command,repeat); //command sent - else - sendMedtronicPumpCommand(command, repeat, postCommandBytes); - withoutConfirmation--; - }else - log.debug("answer received"); - retries = 0; - mHandler4.removeCallbacks(instance); - mHandler4.post(instance); - return;//exit I have received the answer expected - } - } - if (isRequest || postCommandBytes == null || postCommandBytes.length == 0) - sendMedtronicPumpRequest(command,repeat); //command sent - else - sendMedtronicPumpCommand(command, repeat, postCommandBytes); - - synchronized (reader.waitingCommandLock) { - reader.lastCommandSend = command;// register the command - } - - synchronized (reader.sendingCommandLock) { - log.debug("send command "+retries); - reader.sendingCommand = true; - if (!sent){ - retries++; - sent = true; - } - if (retries < MedtronicConstants.NUMBER_OF_RETRIES){ - // sendMessageToUI("ANOTHER RETRY", false); - mHandler3.removeCallbacks(wThread); - long delay = waitTime; - if (isWakeUp) - delay = 10000; - mHandler3.postDelayed(wThread, delay); - }else{ - //sendMessageToUI("I do not have more retries!!", false); - mHandler4.removeCallbacks(instance); - mHandler4.post(instance); - } - - } - }catch(Exception e){ - StringBuffer sb1 = new StringBuffer(""); - sb1.append("EXCEPTION!!!!!! "+ e.getMessage()+" "+e.getCause()); - for (StackTraceElement st : e.getStackTrace()){ - sb1.append(st.toString()); - } - sendMessageToUI(sb1.toString(), false); - } - - } - } - /** - * Method to send a Message to the UI. - * @param valuetosend - * @param clear - */ - protected void sendMessageToUI(String valuetosend, boolean clear) { - Log.i("medtronic.CommandSender", valuetosend); - if (mClients != null && mClients.size() > 0){ - for (int i=mClients.size()-1; i>=0; i--) { - try { - Message mSend = null; - if (clear){ - mSend = Message.obtain(null, MedtronicConstants.MSG_MEDTRONIC_CGM_CLEAR_DISPLAY); - mClients.get(i).send(mSend); - continue; - } - mSend = Message.obtain(null, MedtronicConstants.MSG_MEDTRONIC_CGM_MESSAGE_RECEIVED); - Bundle b = new Bundle(); - b.putString("data", valuetosend); - mSend.setData(b); - mClients.get(i).send(mSend); - - } catch (RemoteException e) { - // The client is dead. Remove it from the list; we are going through the list from back to front so this is safe to do inside the loop. - mClients.remove(i); - } - } - } - } - - public byte[] getCommandList() { - return commandList; - } - - public void setCommandList(byte[] commandList) { - this.index = 0; - this.commandList = commandList; - } - - public ArrayList<Messenger> getmClients() { - return mClients; - } - - public void setmClients(ArrayList<Messenger> mClients) { - this.mClients = mClients; - } -} diff --git a/app/src/main/java/info/nightscout/android/medtronic/DataLog.java b/app/src/main/java/info/nightscout/android/medtronic/DataLog.java deleted file mode 100644 index 2c7db13..0000000 --- a/app/src/main/java/info/nightscout/android/medtronic/DataLog.java +++ /dev/null @@ -1,11 +0,0 @@ -package info.nightscout.android.medtronic; - -import java.util.Date; - -public class DataLog { - int numEntries; - Date[] dateField = new Date [4096]; - char[] entryType = new char [4096]; - int[] glucose = new int [4096]; - int[] calFactor = new int [4096]; -} diff --git a/app/src/main/java/info/nightscout/android/medtronic/HistoricGetterThread.java b/app/src/main/java/info/nightscout/android/medtronic/HistoricGetterThread.java deleted file mode 100644 index af556d5..0000000 --- a/app/src/main/java/info/nightscout/android/medtronic/HistoricGetterThread.java +++ /dev/null @@ -1,191 +0,0 @@ -package info.nightscout.android.medtronic; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; - -import android.os.Handler; -import android.os.Messenger; - -import info.nightscout.android.dexcom.USB.HexDump; -import com.physicaloid.lib.Physicaloid; - -public class HistoricGetterThread extends CommandSenderThread { - ArrayList<byte[]> historicPage = new ArrayList<byte[]>(); - HashMap<String,ArrayList<byte[]>> historic = new HashMap<String, ArrayList<byte[]>>(); - boolean firstReadPage = true; - byte[] currentPage = new byte[4]; - byte[] lastHistoricPage = new byte[4]; - int historicPageIndex = -1; - int currentLine = -1; - int shift = 0; - int timeout = 0; - boolean isWaitingNextLine = false; - - public HistoricGetterThread( - ArrayList<Messenger> mClients, MedtronicReader reader, - byte[] idPump, Physicaloid mSerialDevice, Handler mHandler4) { - - super(new byte[]{MedtronicConstants.MEDTRONIC_WAKE_UP, MedtronicConstants.MEDTRONIC_GET_LAST_PAGE, MedtronicConstants.MEDTRONIC_READ_PAGE_COMMAND}, mClients, reader, idPump, mSerialDevice, mHandler4); - // TODO Auto-generated constructor stub - waitTime = 500; - log.debug("HistoricGetterConstructor"); - } - public void init() { - log.debug("HistoricGetterInit"); - - mHandler3.removeCallbacks(wThread); - //mHandler4.removeCallbacks(this); - if (reader != null){ - synchronized (reader.sendingCommandLock) { - reader.sendingCommand = false; - } - synchronized (reader.waitingCommandLock) { - reader.waitingCommand = false; - reader.lastCommandSend = null; - } - synchronized (reader.processingCommandLock) { - reader.processingCommand = false; - } - sendMessageToUI("Init historicGetter", false); - synchronized (reader.processingCommandLock) { - reader.processingCommand = false; - } - synchronized (reader.waitingCommandLock) { - reader.waitingCommand = false; - reader.lastCommandSend = null; - } - } - - byte[] cList = new byte[]{MedtronicConstants.MEDTRONIC_WAKE_UP, MedtronicConstants.MEDTRONIC_GET_LAST_PAGE, MedtronicConstants.MEDTRONIC_READ_PAGE_COMMAND}; - commandList = cList; - historicPage.clear(); - historic.clear(); - firstReadPage = true; - currentPage = new byte[4]; - lastHistoricPage = new byte[4]; - currentLine = -1; - isWaitingNextLine = false; - shift = 0; - timeout = 0; - index = 0; - historicPageIndex = -1; - wThread.retries = -1; //first retry does not count; - wThread.sent = false; - wThread.isRequest = true; - wThread.postCommandBytes = null; - } - /** - * Runnable Method, It tries to send all the commands in "commanList", in order to do that, - * It creates a second handler calling WriterThread to manage the command send. - */ - @Override - public void run() { - try - { - //sendMessageToUI("sending Command "+ HexDump.toHexString(command), false); - if (index == 0){ - sendMessageToUI(" ", true); - sendMessageToUI("Starting Historic log request...", false); - } - if (wThread.retries >= MedtronicConstants.NUMBER_OF_RETRIES){ - mHandler3.removeCallbacks(wThread); - synchronized (reader.sendingCommandLock) { - reader.sendingCommand = false; - } - synchronized (reader.waitingCommandLock) { - reader.waitingCommand = false; - reader.lastCommandSend = null; - } - synchronized (reader.processingCommandLock) { - reader.processingCommand = false; - } - sendMessageToUI("Timeout expired executing command list", false); - synchronized (reader.processingCommandLock) { - reader.processingCommand = false; - } - synchronized (reader.waitingCommandLock) { - reader.waitingCommand = false; - reader.lastCommandSend = null; - } - return; - } - synchronized (reader.processingCommandLock) {//TODO: LAST - if (!reader.processingCommand) - return; - } - log.debug("HistoricGetter index + commandList "+ index + " "+ commandList.length); - if (index >= commandList.length){ - log.debug("HG firstReadPage"); - if (firstReadPage){ - log.debug("HG firstReadPage TRUE"); - firstReadPage = false; - commandList = Arrays.copyOf(commandList, commandList.length+1); - commandList[commandList.length-1] = MedtronicConstants.MEDTRONIC_READ_PAGE_COMMAND; - wThread.isRequest = false; - byte[] lastHistoricPage = HexDump.toByteArray(historicPageIndex - shift); - log.debug("LastPAGE "+HexDump.toHexString(lastHistoricPage)+" size "+lastHistoricPage.length); - wThread.postCommandBytes = new byte[64]; - Arrays.fill(wThread.postCommandBytes, (byte)0x00); - wThread.postCommandBytes[0] = 0x04; - wThread.postCommandBytes[1] = lastHistoricPage[0]; - wThread.postCommandBytes[2] = lastHistoricPage[1]; - wThread.postCommandBytes[3] = lastHistoricPage[2]; - wThread.postCommandBytes[4] = lastHistoricPage[3]; - isWaitingNextLine = true; - - synchronized (reader.waitingCommandLock) { - reader.waitingCommand = true; - reader.lastCommandSend = null; - } - - byte command = commandList[index]; - //sendMessageToUI("COMMAND SENDER: sending Command "+ HexDump.toHexString(command), false); - wThread.retries = -1; - wThread.command = command; - wThread.instance = this; - mHandler3.post(wThread); - index++; - return; - } - synchronized (reader.processingCommandLock) { - reader.processingCommand = false; - } - synchronized (reader.waitingCommandLock) { - reader.waitingCommand = false; - reader.lastCommandSend = null; - } - return; - } - byte command = commandList[index]; - if (withoutConfirmation <= 0 || command == MedtronicConstants.MEDTRONIC_INIT ){ - synchronized (reader.waitingCommandLock) { - reader.waitingCommand = true; - reader.lastCommandSend = null; - } - }else{ - synchronized (reader.waitingCommandLock) { - reader.waitingCommand = false; - reader.lastCommandSend = null; - } - } - if (command == MedtronicConstants.MEDTRONIC_INIT){ - init(); - return; - } - wThread.retries = -1; - wThread.command = command; - wThread.instance = this; - mHandler3.post(wThread); - index++; - }catch(Exception e){ - StringBuffer sb1 = new StringBuffer(""); - sb1.append("EXCEPTION!!!!!! "+ e.getMessage()+" "+e.getCause()); - for (StackTraceElement st : e.getStackTrace()){ - sb1.append(st.toString()); - } - sendMessageToUI(sb1.toString(), false); - } - - } -} diff --git a/app/src/main/java/info/nightscout/android/medtronic/Medtronic640gActivity.java b/app/src/main/java/info/nightscout/android/medtronic/Medtronic640gActivity.java index 19cb30e..34a77f0 100644 --- a/app/src/main/java/info/nightscout/android/medtronic/Medtronic640gActivity.java +++ b/app/src/main/java/info/nightscout/android/medtronic/Medtronic640gActivity.java @@ -2,7 +2,6 @@ package info.nightscout.android.medtronic; import android.app.Activity; import android.app.ActivityManager; -import android.app.ActivityManager.RunningServiceInfo; import android.app.AlertDialog; import android.content.BroadcastReceiver; import android.content.Context; @@ -16,10 +15,7 @@ import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.os.Handler; -import android.os.IBinder; import android.os.Message; -import android.os.Messenger; -import android.os.RemoteException; import android.os.StrictMode; import android.preference.PreferenceManager; import android.text.Html; @@ -33,7 +29,6 @@ import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup.LayoutParams; import android.widget.Button; -import android.widget.EditText; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.TextView.BufferType; @@ -41,8 +36,12 @@ import android.widget.TextView.BufferType; import com.crashlytics.android.Crashlytics; import com.crashlytics.android.answers.Answers; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.text.DecimalFormat; + import info.nightscout.android.R; -import info.nightscout.android.dexcom.DexcomG4Service; import info.nightscout.android.eula.Eula; import info.nightscout.android.eula.Eula.OnEulaAgreedTo; import info.nightscout.android.medtronic.service.MedtronicCNLService; @@ -50,136 +49,33 @@ import info.nightscout.android.service.ServiceManager; import info.nightscout.android.settings.SettingsActivity; import info.nightscout.android.upload.MedtronicNG.CGMRecord; import info.nightscout.android.upload.MedtronicNG.PumpStatusRecord; -import info.nightscout.android.upload.Record; - import io.fabric.sdk.android.Fabric; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.File; -import java.io.FileInputStream; -import java.io.ObjectInputStream; -import java.text.DecimalFormat; /* Main activity for the Medtronic640gActivity program */ public class Medtronic640gActivity extends Activity implements OnSharedPreferenceChangeListener, OnEulaAgreedTo { - private Logger log = (Logger) LoggerFactory.getLogger(Medtronic640gActivity.class.getName()); //CGMs supported - public static final int DEXCOMG4 = 0; - public static final int MEDTRONIC_CGM = 1; public static final int CNL_24 = 2; - private static final String TAG = Medtronic640gActivity.class.getSimpleName(); - private int cgmSelected = CNL_24; - private int calibrationSelected = MedtronicConstants.CALIBRATION_GLUCOMETER; - - private Handler mHandler = new DexcomG4ActivityHandler(); - - private int maxRetries = 20; - private int retryCount = 0; - EditText input; - - private TextView mTitleTextView; - private TextView mDumpTextView; - private Button b1; - private Button b4; - private TextView display; - private Menu menu = null; - private Intent service = null; - private ServiceManager cgmService; // > service - private int msgsDisplayed = 0; + private static final boolean ISDEBUG = true; public static int batLevel = 0; public static PumpStatusRecord pumpStatusRecord = new PumpStatusRecord(); BatteryReceiver mArrow; - IBinder bService = null; Intent batteryReceiver; - Messenger mService = null; - boolean mIsBound; boolean keepServiceAlive = true; Boolean mHandlerActive = false; - Object mHandlerActiveLock = new Object(); - Boolean usbAllowedPermission = false; + final Object mHandlerActiveLock = new Object(); ActivityManager manager = null; - final Context ctx = this; SharedPreferences settings = null; SharedPreferences prefs = null; - private static final boolean ISDEBUG = true; - - public class DexcomG4ActivityHandler extends Handler { - public static final int MSG_ERROR = 1; - public static final int MSG_STATUS = 2; - public static final int MSG_DATA = 3; - - @Override - public void handleMessage(Message msg) { - Log.d( TAG, "Got message from Service." ); - switch ( cgmSelected ) { - case CNL_24: - switch (msg.what) { - case MSG_ERROR: - display.setText(msg.obj.toString(), BufferType.EDITABLE); - break; - case MSG_STATUS: - display.setText(msg.obj.toString(), BufferType.EDITABLE); - break; - case MSG_DATA: - CGMRecord record = (CGMRecord) msg.obj; - - DecimalFormat df = null; - if (prefs.getBoolean("mmolDecimals", false)) - df = new DecimalFormat("#.00"); - else - df = new DecimalFormat("#.0"); - String sgvString = "---"; - String unitsString = "mg/dL"; - if (prefs.getBoolean("mmolxl", false)) { - try { - float fBgValue = Float.valueOf(record.sgv); - sgvString = df.format(fBgValue / 18.016f); - unitsString = "mmol/L"; - log.info("mmolxl true --> " + sgvString); - } catch (Exception e) { - - } - } else { - sgvString = String.valueOf(record.sgv); - log.info("mmolxl false --> " + sgvString); - } - - //mTitleTextView.setTextColor(Color.YELLOW); - mTitleTextView.setText(Html.fromHtml( - String.format( "<big><b>%s</b></big> <small>%s %s</small>", - sgvString, unitsString, renderTrendHtml(record.getTrend())))); - - mDumpTextView.setTextColor(Color.WHITE); - mDumpTextView.setText(Html.fromHtml( - String.format( "<b>SG at:</b> %s<br/><b>Pump Time:</b> %s<br/><b>Active Insulin: </b>%.3f<br/><b>Rate of Change: </b>%s", - DateUtils.formatDateTime(getBaseContext(),record.sgvDate.getTime(),DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_TIME), - DateUtils.formatDateTime(getBaseContext(),pumpStatusRecord.pumpDate.getTime(),DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_TIME), - pumpStatusRecord.activeInsulin, - record.direction - ) - )); - - break; - } - default: - super.handleMessage(msg); - } - } - } - - private class BatteryReceiver extends BroadcastReceiver { - @Override - public void onReceive(Context arg0, Intent arg1) { - if (arg1.getAction().equalsIgnoreCase(Intent.ACTION_BATTERY_LOW) - || arg1.getAction().equalsIgnoreCase(Intent.ACTION_BATTERY_CHANGED) - || arg1.getAction().equalsIgnoreCase(Intent.ACTION_BATTERY_OKAY)) { - Log.i("BatteryReceived", "BatteryReceived"); - batLevel = arg1.getIntExtra("level", 0); - } - } - } + private Logger log = (Logger) LoggerFactory.getLogger(Medtronic640gActivity.class.getName()); + private int cgmSelected = CNL_24; + private Handler mHandler = new Medtronic640gActivityHandler(); + private TextView mTitleTextView; + private TextView mDumpTextView; + private Button b1; + private TextView display; + private Intent service = null; + private ServiceManager cgmService; // > service //Look for and launch the service, display status to user @Override @@ -197,10 +93,10 @@ public class Medtronic640gActivity extends Activity implements OnSharedPreferenc PreferenceManager.getDefaultSharedPreferences(getBaseContext()).registerOnSharedPreferenceChangeListener(this); prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); - if( prefs.getBoolean( getString(R.string.preferences_enable_crashlytics), true ) ) { + if (prefs.getBoolean(getString(R.string.preferences_enable_crashlytics), true)) { Fabric.with(this, new Crashlytics()); } - if( prefs.getBoolean( getString(R.string.preferences_enable_answers), true ) ) { + if (prefs.getBoolean(getString(R.string.preferences_enable_answers), true)) { Fabric.with(this, new Answers()); } @@ -226,10 +122,6 @@ public class Medtronic640gActivity extends Activity implements OnSharedPreferenc if (!prefs.getBoolean("IUNDERSTAND", false)) { stopCGMServices(); } else { - if (isMyServiceRunning() && cgmSelected == MEDTRONIC_CGM) { - doBindService(); - } - //mHandler.post(updateDataView); mHandlerActive = true; } @@ -240,7 +132,7 @@ public class Medtronic640gActivity extends Activity implements OnSharedPreferenc Button b2 = new Button(this); b2.setText("Clear Log"); b2.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, 1.0f)); - b4 = new Button(this); + Button b4 = new Button(this); b4.setText("Get Now"); b4.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, 1.0f)); lnr3.addView(b4); @@ -267,7 +159,6 @@ public class Medtronic640gActivity extends Activity implements OnSharedPreferenc public void onClick(View v) { display.setText("", BufferType.EDITABLE); display.setKeyListener(null); - msgsDisplayed = 0; } }); @@ -275,7 +166,7 @@ public class Medtronic640gActivity extends Activity implements OnSharedPreferenc @Override public void onClick(View v) { display.setKeyListener(null); - if( cgmService != null ) { + if (cgmService != null) { if (!cgmService.isRunning()) { cgmService.start(); } else { @@ -296,26 +187,10 @@ public class Medtronic640gActivity extends Activity implements OnSharedPreferenc keepServiceAlive = false; stopCGMServices(); b1.setText("Start Uploading CGM Data"); - //mTitleTextView.setTextColor(Color.RED); - //mTitleTextView.setText("CGM Service Stopped"); finish(); } else { - mHandlerActive = false; - //mHandler.removeCallbacks(updateDataView); - //mHandler.post(updateDataView); - if (!usbAllowedPermission) - if (mService == null && bService != null) { - mService = new Messenger(bService); - } - if (mService != null) { - try { - Message msg = Message.obtain(null, MedtronicConstants.MSG_MEDTRONIC_CGM_REQUEST_PERMISSION, 0, 0); - //msg.replyTo = mMessenger; - mService.send(msg); - } catch (RemoteException e) { - mService = null; - } - } + startCGMServices(); + mHandlerActive = true; b1.setText("Stop Uploading CGM Data"); } @@ -329,8 +204,8 @@ public class Medtronic640gActivity extends Activity implements OnSharedPreferenc protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); startCGMServices(); - if( cgmService != null ) { - Log.d( TAG, "onPostCreate: Starting the service"); + if (cgmService != null) { + Log.d(TAG, "onPostCreate: Starting the service"); cgmService.start(); } } @@ -348,52 +223,21 @@ public class Medtronic640gActivity extends Activity implements OnSharedPreferenc super.onResume(); } - //Check to see if service is running - private boolean isMyServiceRunning() { - - for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) { - if (isServiceAlive(service.service.getClassName())) - return true; - } - return false; - } - - //Deserialize the EGVRecord (most recent) value - public Record loadClassFile(File f) { - ObjectInputStream ois = null; - try { - ois = new ObjectInputStream(new FileInputStream(f)); - Object o = ois.readObject(); - ois.close(); - return (Record) o; - } catch (Exception ex) { - Log.w(TAG, " unable to loadEGVRecord"); - try { - if (ois != null) - ois.close(); - } catch (Exception e) { - Log.e(TAG, " Error closing ObjectInputStream"); - } - } - return new Record(); - } - @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); - this.menu = menu; inflater.inflate(R.menu.menu, menu); return true; } - private boolean checkOnline( String title, String message ) { + private boolean checkOnline(String title, String message) { ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netInfo = cm.getActiveNetworkInfo(); - boolean isOnline = ( netInfo != null && netInfo.isConnectedOrConnecting() ); + boolean isOnline = (netInfo != null && netInfo.isConnectedOrConnecting()); - if( !isOnline ) { + if (!isOnline) { new AlertDialog.Builder(this) .setTitle(title) .setMessage(message) @@ -420,7 +264,7 @@ public class Medtronic640gActivity extends Activity implements OnSharedPreferenc startActivity(settingsIntent); break; case R.id.registerCNL: - if( checkOnline( "Please connect to the Internet", "You must be online to register your USB stick.") ) { + if (checkOnline("Please connect to the Internet", "You must be online to register your USB stick.")) { Intent loginIntent = new Intent(this, GetHmacAndKeyActivity.class); startActivity(loginIntent); } @@ -434,49 +278,20 @@ public class Medtronic640gActivity extends Activity implements OnSharedPreferenc private void startCGMServices() { Log.d("DexcomActivity", "Starting service for CGM: " + cgmSelected); switch (cgmSelected) { - case MEDTRONIC_CGM: - if (service != null || isMyServiceRunning()) - stopCGMServices(); - doBindService(); - return; - case CNL_24: + default: Log.d("DexcomActivity", "Starting Medtronic CNL service"); - cgmService = new ServiceManager(this, MedtronicCNLService.class, mHandler ); - //cgmService.start(); + cgmService = new ServiceManager(this, MedtronicCNLService.class, mHandler); break; - default: - startService(new Intent(Medtronic640gActivity.this, DexcomG4Service.class)); } - return; } private void stopCGMServices() { switch (cgmSelected) { - case MEDTRONIC_CGM: - if (service != null) { - doUnbindService(); - killService(); - } - return; - case CNL_24: - if( cgmService != null ) { + default: + if (cgmService != null) { cgmService.stop(); } break; - default: - stopService(new Intent(Medtronic640gActivity.this, DexcomG4Service.class)); - } - return; - } - - private boolean isServiceAlive(String name) { - switch (cgmSelected) { - case MEDTRONIC_CGM: - return MedtronicCGMService.class.getName().equals(name); - case CNL_24: - return MedtronicCNLService.class.getName().equals(name); - default: - return DexcomG4Service.class.getName().equals(name); } } @@ -488,55 +303,17 @@ public class Medtronic640gActivity extends Activity implements OnSharedPreferenc unregisterReceiver(mArrow); synchronized (mHandlerActiveLock) { //mHandler.removeCallbacks(updateDataView); - doUnbindService(); + + stopCGMServices(); if (keepServiceAlive) { - killService(); - service = new Intent(this, MedtronicCGMService.class); - startService(service); + startCGMServices(); } mHandlerActive = false; SharedPreferences.Editor editor = getBaseContext().getSharedPreferences(MedtronicConstants.PREFS_NAME, 0).edit(); editor.putLong("lastDestroy", System.currentTimeMillis()); - editor.commit(); + editor.apply(); super.onDestroy(); } - stopCGMServices(); - } - - void doBindService() { - if ((service != null && isMyServiceRunning()) || mIsBound) - stopCGMServices(); - service = new Intent(this, MedtronicCGMService.class); - //bindService(service, mConnection, Context.BIND_AUTO_CREATE); - mIsBound = true; - } - - void doUnbindService() { - if (mIsBound) { - // If we have received the service, and hence registered with it, then now is the time to unregister. - if (mService == null && bService != null) { - mService = new Messenger(bService); - } - if (mService != null) { - try { - Message msg = Message.obtain(null, MedtronicConstants.MSG_UNREGISTER_CLIENT); - //msg.replyTo = mMessenger; - mService.send(msg); - } catch (RemoteException e) { - // There is nothing special we need to do if the service has crashed. - } - } - // Detach our existing connection. - //unbindService(mConnection); - mIsBound = false; - } - } - - protected void killService() { - if (service != null) { - stopService(service); - service = null; - } } @Override @@ -584,10 +361,8 @@ public class Medtronic640gActivity extends Activity implements OnSharedPreferenc } - private String renderTrendHtml(CGMRecord.TREND trend) - { - switch( trend ) - { + private String renderTrendHtml(CGMRecord.TREND trend) { + switch (trend) { case DOUBLE_UP: return "⇈"; case SINGLE_UP: @@ -606,4 +381,78 @@ public class Medtronic640gActivity extends Activity implements OnSharedPreferenc return "—"; } } + + public class Medtronic640gActivityHandler extends Handler { + public static final int MSG_ERROR = 1; + public static final int MSG_STATUS = 2; + public static final int MSG_DATA = 3; + + @Override + public void handleMessage(Message msg) { + Log.d(TAG, "Got message from Service."); + switch (cgmSelected) { + case CNL_24: + switch (msg.what) { + case MSG_ERROR: + display.setText(msg.obj.toString(), BufferType.EDITABLE); + break; + case MSG_STATUS: + display.setText(msg.obj.toString(), BufferType.EDITABLE); + break; + case MSG_DATA: + CGMRecord record = (CGMRecord) msg.obj; + + DecimalFormat df; + if (prefs.getBoolean("mmolDecimals", false)) + df = new DecimalFormat("#.00"); + else + df = new DecimalFormat("#.0"); + String sgvString = "---"; + String unitsString = "mg/dL"; + if (prefs.getBoolean("mmolxl", false)) { + + float fBgValue = (float) record.sgv; + sgvString = df.format(fBgValue / 18.016f); + unitsString = "mmol/L"; + log.info("mmolxl true --> " + sgvString); + + } else { + sgvString = String.valueOf(record.sgv); + log.info("mmolxl false --> " + sgvString); + } + + //mTitleTextView.setTextColor(Color.YELLOW); + mTitleTextView.setText(Html.fromHtml( + String.format("<big><b>%s</b></big> <small>%s %s</small>", + sgvString, unitsString, renderTrendHtml(record.getTrend())))); + + mDumpTextView.setTextColor(Color.WHITE); + mDumpTextView.setText(Html.fromHtml( + String.format("<b>SG at:</b> %s<br/><b>Pump Time:</b> %s<br/><b>Active Insulin: </b>%.3f<br/><b>Rate of Change: </b>%s", + DateUtils.formatDateTime(getBaseContext(), record.sgvDate.getTime(), DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_TIME), + DateUtils.formatDateTime(getBaseContext(), pumpStatusRecord.pumpDate.getTime(), DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_TIME), + pumpStatusRecord.activeInsulin, + record.direction + ) + )); + + break; + } + default: + super.handleMessage(msg); + } + } + } + + private class BatteryReceiver extends BroadcastReceiver { + @Override + public void onReceive(Context arg0, Intent arg1) { + if (arg1.getAction().equalsIgnoreCase(Intent.ACTION_BATTERY_LOW) + || arg1.getAction().equalsIgnoreCase(Intent.ACTION_BATTERY_CHANGED) + || arg1.getAction().equalsIgnoreCase(Intent.ACTION_BATTERY_OKAY)) { + Log.i("BatteryReceived", "BatteryReceived"); + batLevel = arg1.getIntExtra("level", 0); + } + } + } } diff --git a/app/src/main/java/info/nightscout/android/medtronic/MedtronicCGMService.java b/app/src/main/java/info/nightscout/android/medtronic/MedtronicCGMService.java deleted file mode 100644 index bfa692c..0000000 --- a/app/src/main/java/info/nightscout/android/medtronic/MedtronicCGMService.java +++ /dev/null @@ -1,2005 +0,0 @@ -package info.nightscout.android.medtronic; - -import java.io.File; -import java.io.FileInputStream; -import java.io.ObjectInputStream; -import java.text.DecimalFormat; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Date; -import java.util.List; - -import org.bson.Document; -import org.json.JSONArray; -import org.json.JSONException; -import org.slf4j.LoggerFactory; -import ch.qos.logback.classic.Level; -import ch.qos.logback.classic.Logger; - -import android.app.NotificationManager; -import android.app.Service; -import android.content.BroadcastReceiver; -import android.content.Context; -import android.content.Intent; -import android.content.IntentFilter; -import android.content.SharedPreferences; -import android.content.SharedPreferences.OnSharedPreferenceChangeListener; -import android.hardware.usb.UsbDevice; -import android.hardware.usb.UsbManager; -import android.net.ConnectivityManager; -import android.net.NetworkInfo; -import android.net.wifi.WifiManager; -import android.os.AsyncTask.Status; -import android.os.Bundle; -import android.os.Handler; -import android.os.IBinder; -import android.os.Message; -import android.os.Messenger; -import android.os.RemoteException; -import android.os.StrictMode; -import android.preference.PreferenceManager; -import android.util.Log; -import android.view.Gravity; -import android.widget.LinearLayout; -import android.widget.TextView; -import android.widget.Toast; - -import com.mongodb.MongoClient; -import com.mongodb.MongoClientOptions; -import com.mongodb.MongoClientOptions.Builder; -import com.mongodb.MongoClientURI; -import com.mongodb.MongoCredential; -import com.mongodb.ServerAddress; -import com.mongodb.client.MongoCollection; -import com.mongodb.client.MongoDatabase; - -import info.nightscout.android.dexcom.USB.HexDump; -import info.nightscout.android.upload.GlucometerRecord; -import info.nightscout.android.upload.MedtronicSensorRecord; -import info.nightscout.android.upload.Record; -import info.nightscout.android.upload.UploadHelper; -import com.physicaloid.lib.Physicaloid; -import com.physicaloid.lib.usb.driver.uart.ReadLisener; -import com.physicaloid.lib.usb.driver.uart.UartConfig; -/** - * This class is the service responsible of manage correctly the interface with the enlite. - * @author lmmarguenda - * - */ -public class MedtronicCGMService extends Service implements - OnSharedPreferenceChangeListener { - - private Logger log = (Logger)LoggerFactory.getLogger(MedtronicReader.class.getName()); - public UsbManager mUsbManager; - private static final String TAG = MedtronicCGMService.class.getSimpleName(); - private NotificationManager NM; - - private MedtronicCGMService instance = null; - private boolean listenerAttached = false; - private UploadHelper uploader; - private String dbURI = null; - private String collectionName = null; - private String dsCollectionName = null; - private String gdCollectionName = null; - private String devicesCollectionName = "devices"; - private MongoDatabase db = null; - private MongoCollection<Document> dexcomData = null; - private MongoCollection<Document> glucomData = null; - private MongoCollection<Document> deviceData = null; - private MongoClient client = null; - private MongoCollection<Document> dsCollection = null; - private Physicaloid mSerial; - private Handler mHandlerCheckSerial = new Handler();// This handler runs readAndUpload Runnable which checks the USB device and NET connection. - private Handler mHandler2CheckDevice = new Handler(); // this Handler is used to read the device info each thirty minutes - private Handler mHandler3ActivatePump = new Handler();// this Handler is used to execute commands after changing the pump ID - private Handler mHandlerReadFromHistoric = new Handler();// this Handler is used to read data from pump log file. - private Handler mHandlerRead = new Handler();// this Handler is used to read and parse the messages received from the USB, It is only activated after a Read. - private Handler mHandlerProcessRead = new Handler();// this Handler is used to process the messages parsed. - private Handler mHandlerReviewParameters = new Handler(); - private Handler mHandlerCheckLastRead = new Handler(); - private boolean mHandlerActive = false; - private SharedPreferences settings = null;// Here I store the settings needed to store the status of the service. - private Runnable checker = null; - private WifiManager wifiManager; - private MedtronicReader medtronicReader = null;//Medtronic Reader - private BufferedMessagesProcessor processBufferedMessages = new BufferedMessagesProcessor();// Runnable which manages the message processing; - private ArrayList<Messenger> mClients = new ArrayList<Messenger>(); // clients subscribed; - private final Messenger mMessenger = new Messenger(new IncomingHandler()); // Target we publish for clients to send messages to IncomingHandler. - private CommandSenderThread cMThread = null;// Thread to process a set of commands - private SharedPreferences prefs = null;// common application preferences - private int calibrationSelected = MedtronicConstants.CALIBRATION_GLUCOMETER;//calibration Selected - private Handler mHandlerSensorCalibration = new Handler();// this Handler is used to ask for SensorCalibration. - private Handler mHandlerReloadLost = new Handler();// this Handler is used to upload records which upload failed due to a network error. - private long pumpPeriod = MedtronicConstants.TIME_30_MIN_IN_MS; - private boolean connectedSent = false; - private boolean isDestroying = false; - private Object reloadLostLock = new Object(); - private Object resultLock = new Object(); - private Object checkSerialLock = new Object(); - private Boolean isUploading = false; - private Object isUploadingLock = new Object(); - private Object readByListenerSizeLock = new Object(); - private Object buffMessagesLock = new Object(); - private Object mSerialLock = new Object(); - private boolean isDBInitialized = false; - private HistoricGetterThread hGetter = null;//Medtronic Historic Log retriever - private long historicLogPeriod = 0; - private ReadByListener readByListener = new ReadByListener();//Listener to read data - private boolean isReloaded = false; - - @Override - public IBinder onBind(Intent intent) { - return mMessenger.getBinder(); - - } - - /** - * Handler of incoming messages from clients. - * @author lmmarguenda - * - */ - class IncomingHandler extends Handler { - @Override - public void handleMessage(Message msg) { - switch (msg.what) { - case MedtronicConstants.MSG_REGISTER_CLIENT: - mClients.add(msg.replyTo); - break; - case MedtronicConstants.MSG_UNREGISTER_CLIENT: - mClients.remove(msg.replyTo); - break; - case MedtronicConstants.MSG_MEDTRONIC_GLUCMEASURE_APPROVED: - if (msg.getData().getBoolean("approved")) - medtronicReader.approveGlucValueForCalibration(msg.getData().getFloat("data"), msg.getData().getBoolean("calibrating"), msg.getData().getBoolean("isCalFactorFromPump")); - else{ - medtronicReader.lastGlucometerRecord = new GlucometerRecord(); - medtronicReader.lastGlucometerRecord.numGlucometerValue = msg.getData().getFloat("data"); - medtronicReader.lastGlucometerValue = msg.getData().getFloat("data"); - Date d = new Date(); - medtronicReader.lastGlucometerRecord.lastDate = d.getTime(); - medtronicReader.lastGlucometerDate = d.getTime(); - medtronicReader.calculateDate(medtronicReader.lastGlucometerRecord, d, 0); - SharedPreferences.Editor editor = settings.edit(); - editor.putFloat("lastGlucometerValue", (float) medtronicReader.lastGlucometerValue); - editor.putLong("glucometerLastDate", d.getTime()); - editor.commit(); - } - - break; - case MedtronicConstants.MSG_MEDTRONIC_SEND_MANUAL_CALIB_VALUE: - String value = msg.getData().getString("sgv"); - if (value == null || value.equals("")){ - value = prefs.getString("manual_sgv", ""); - if (value != null && value.indexOf(",") >= 0) - value = value.replace(",", "."); - } - log.debug("Manual Calibration Received SGV "+value); - try{ - Float val = null; - if (medtronicReader != null && value != null && !value.equals("")){ - if (prefs.getBoolean("mmolxl", false)){ - try { - if (value.indexOf(".") > -1){ - val = Float.parseFloat(value); - medtronicReader.processManualCalibrationDataMessage(val, false, true); - }else{ - medtronicReader.processManualCalibrationDataMessage(Integer.parseInt(value), false, true); - } - sendMessageCalibrationDoneToUI(); - } catch (Exception e) { - sendErrorMessageToUI("Error parsing Calibration"); - StringBuffer sb1 = new StringBuffer(""); - sb1.append("EXCEPTION!!!!!! " + e.getMessage() + " " + e.getCause()); - for (StackTraceElement st : e.getStackTrace()) { - sb1.append(st.toString()); - } - sendMessageToUI(sb1.toString(), false); - } - }else{ - if (value.indexOf(".") > -1){ - val = Float.parseFloat(value); - medtronicReader.processManualCalibrationDataMessage(val.intValue(), false, true); - }else{ - medtronicReader.processManualCalibrationDataMessage(Integer.parseInt(value), false, true); - } - sendMessageCalibrationDoneToUI(); - } - } - }catch(Exception e){ - sendErrorMessageToUI("Error parsing Calibration"); - StringBuffer sb1 = new StringBuffer(""); - sb1.append("EXCEPTION!!!!!! " + e.getMessage() + " " + e.getCause()); - for (StackTraceElement st : e.getStackTrace()) { - sb1.append(st.toString()); - } - sendMessageToUI(sb1.toString(), false); - } - break; - case MedtronicConstants.MSG_MEDTRONIC_SEND_INSTANT_CALIB_VALUE: - value = msg.getData().getString("sgv"); - if (value == null || value.equals("")){ - value = prefs.getString("instant_sgv", ""); - if (value != null && value.indexOf(",") >= 0) - value = value.replace(",", "."); - } - log.debug("Instant Calibration received SGV "+value); - try{ - Float val = null; - if (medtronicReader != null && value != null && !value.equals("")){ - if (prefs.getBoolean("mmolxl", false)){ - try { - if (value.indexOf(".") > -1){ - val = Float.parseFloat(value); - medtronicReader.calculateInstantCalibration(val*18f); - }else{ - medtronicReader.calculateInstantCalibration(Integer.parseInt(value)*18f); - } - sendMessageCalibrationDoneToUI(); - } catch (Exception e) { - sendErrorMessageToUI("Error parsing Calibration"); - StringBuffer sb1 = new StringBuffer(""); - sb1.append("EXCEPTION!!!!!! " + e.getMessage() + " " + e.getCause()); - for (StackTraceElement st : e.getStackTrace()) { - sb1.append(st.toString()); - } - sendMessageToUI(sb1.toString(), false); - } - }else{ - if (value.indexOf(".") > -1){ - val = Float.parseFloat(value); - medtronicReader.calculateInstantCalibration(val.intValue()); - }else{ - medtronicReader.calculateInstantCalibration(Integer.parseInt(value)); - } - sendMessageCalibrationDoneToUI(); - } - }else{ - sendErrorMessageToUI("Error parsing Calibration"); - } - }catch(Exception e){ - sendErrorMessageToUI("Error parsing Calibration"); - StringBuffer sb1 = new StringBuffer(""); - sb1.append("EXCEPTION!!!!!! " + e.getMessage() + " " + e.getCause()); - for (StackTraceElement st : e.getStackTrace()) { - sb1.append(st.toString()); - } - sendMessageToUI(sb1.toString(), false); - } - break; - case MedtronicConstants.MSG_MEDTRONIC_SEND_GET_PUMP_INFO: - sendMessageToUI("Retrieving Pump info...", false); - log.debug("Retrieving Pump info..."); - mHandler3ActivatePump.removeCallbacks(activateNewPump); - mHandler3ActivatePump.post(activateNewPump); - break; - case MedtronicConstants.MSG_MEDTRONIC_SEND_GET_SENSORCAL_FACTOR: - sendMessageToUI("Retrieve calibration factor...Now!", false); - log.debug("Retrieve calibration factor...Now!"); - mHandlerSensorCalibration.removeCallbacks(getCalibrationFromSensor); - mHandlerSensorCalibration.post(getCalibrationFromSensor); - break; - case MedtronicConstants.MSG_MEDTRONIC_CGM_REQUEST_PERMISSION: - openUsbSerial(false); - break; - case MedtronicConstants.MSG_REFRESH_DB_CONNECTION: - initializeDB(); - break; - default: - super.handleMessage(msg); - } - } - } - /** - * This method initializes only one instance of mongo db (It would be better use something like Google guice but ...) - * @return DB initialized successfully - */ - private boolean initializeDB(){ - dbURI = prefs.getString("MongoDB URI", null); - collectionName = prefs.getString("Collection Name", "entries"); - dsCollectionName = prefs.getString("DeviceStatus Collection Name", "devicestatus"); - gdCollectionName = prefs.getString("gcdCollectionName", null); - devicesCollectionName = "devices"; - - db = null; - if (dbURI != null) { - log.debug("URI != null"); - - try { - if (!prefs.getBoolean("isMongoRest", false)){ - // connect to db gYumpKyCgbOhcAGOTXvkCcq4V04W6K1Z - MongoClientURI uri = new MongoClientURI(dbURI.trim()); - Builder b = MongoClientOptions.builder(); - b.heartbeatConnectTimeout(150000); - b.heartbeatFrequency(120000); - b.heartbeatSocketTimeout(150000); - b.maxWaitTime(150000); - b.connectTimeout(150000); - boolean bAchieved = false; - String user = ""; - String password = ""; - String source = ""; - String host = ""; - String port = ""; - int iPort = -1; - if (dbURI.length() > 0){ - String[] splitted = dbURI.split(":"); - if (splitted.length >= 4 ){ - user = splitted[1].substring(2); - if (splitted[2].indexOf("@") < 0) - bAchieved = false; - else{ - password = splitted[2].substring(0,splitted[2].indexOf("@")); - host = splitted[2].substring(splitted[2].indexOf("@")+1, splitted[2].length()); - if (splitted[3].indexOf("/") < 0) - bAchieved = false; - else{ - port = splitted[3].substring(0, splitted[3].indexOf("/")); - source = splitted[3].substring(splitted[3].indexOf("/")+1, splitted[3].length()); - try{ - iPort = Integer.parseInt(port); - }catch(Exception ne){ - iPort = -1; - } - if (iPort > -1) - bAchieved = true; - } - } - } - } - log.debug("Uri TO CHANGE user "+user+" host "+source+" password "+password); - if (bAchieved){ - MongoCredential mc = MongoCredential.createMongoCRCredential(user, source , password.toCharArray()); - ServerAddress sa = new ServerAddress(host, iPort); - List<MongoCredential> lcredential = new ArrayList<MongoCredential>(); - lcredential.add(mc); - if (sa != null && sa.getHost() != null && sa.getHost().indexOf("localhost") < 0){ - client = new MongoClient(sa, lcredential, b.build()); - } - } - // get db - db = client.getDatabase(uri.getDatabase()); - - - // get collection - dexcomData = null; - glucomData = null; - deviceData = db.getCollection(devicesCollectionName); - if (deviceData == null){ - db.createCollection("device", null); - deviceData = db.getCollection("device"); - } - if (collectionName != null) - dexcomData = db.getCollection(collectionName.trim()); - if (gdCollectionName != null) - glucomData = db.getCollection(gdCollectionName.trim()); - dsCollection = db.getCollection(dsCollectionName); - if (dsCollection == null){ - db.createCollection("devicestatus", null); - dsCollection = db.getCollection("devicestatus"); - } - } - }catch (Exception e){ - log.error("EXCEPTION INIT",e); - return false; - } - return true; - } - return false; - } - - /** - * Sends a message to be printed in the display (DEBUG) or launches a pop-up message. - * @param valuetosend - * @param clear, if true, the display is cleared before printing "valuetosend" - */ - private void sendMessageToUI(String valuetosend, boolean clear) { - Log.i("medtronicCGMService", valuetosend); - log.debug("send Message To UI -> "+valuetosend); - if (mClients != null && mClients.size() > 0) { - for (int i = mClients.size() - 1; i >= 0; i--) { - try { - Message mSend = null; - if (clear) { - mSend = Message - .obtain(null, - MedtronicConstants.MSG_MEDTRONIC_CGM_CLEAR_DISPLAY); - mClients.get(i).send(mSend); - continue; - } - mSend = Message - .obtain(null, - MedtronicConstants.MSG_MEDTRONIC_CGM_MESSAGE_RECEIVED); - Bundle b = new Bundle(); - b.putString("data", valuetosend); - mSend.setData(b); - mClients.get(i).send(mSend); - - } catch (RemoteException e) { - // The client is dead. Remove it from the list; we are going - // through the list from back to front so this is safe to do - // inside the loop. - mClients.remove(i); - } - } - } else { - displayMessage(valuetosend); - } - } - /** - * Sends an error message to be printed in the display (DEBUG) if it is repeated, It is not printed again. If UI is not visible, It will launch a pop-up message. - * @param valuetosend - * @param clear, if true, the display is cleared before printing "valuetosend" - */ - private void sendErrorMessageToUI(String valuetosend) { - Log.e("medtronicCGMService", valuetosend); - log.error("Send Error Message to UI "+ valuetosend); - if (mClients != null && mClients.size() > 0) { - for (int i = mClients.size() - 1; i >= 0; i--) { - try { - Message mSend = null; - mSend = Message - .obtain(null, - MedtronicConstants.MSG_MEDTRONIC_CGM_ERROR_RECEIVED); - Bundle b = new Bundle(); - b.putString("data", valuetosend); - mSend.setData(b); - mClients.get(i).send(mSend); - - } catch (RemoteException e) { - // The client is dead. Remove it from the list; we are going - // through the list from back to front so this is safe to do - // inside the loop. - mClients.remove(i); - } - } - } else { - displayMessage(valuetosend); - } - } - - /** - * Sends message to the UI to indicate that the device is connected. - */ - private void sendMessageConnectedToUI() { - Log.i("medtronicCGMService", "Connected"); - if (!connectedSent){ - log.debug("Send Message Connected to UI"); - connectedSent = true; - } - for (int i = mClients.size() - 1; i >= 0; i--) { - try { - Message mSend = null; - mSend = Message.obtain(null, - MedtronicConstants.MSG_MEDTRONIC_CGM_USB_GRANTED); - mClients.get(i).send(mSend); - - } catch (RemoteException e) { - // The client is dead. Remove it from the list; we are going - // through the list from back to front so this is safe to do - // inside the loop. - mClients.remove(i); - } - } - } - - /** - * Sends message to the UI to indicate that a calibration has been made. - */ - private void sendMessageCalibrationDoneToUI() { - Log.i("medtronicCGMService", "Calibration done"); - for (int i = mClients.size() - 1; i >= 0; i--) { - try { - Message mSend = null; - mSend = Message.obtain(null, - MedtronicConstants.MSG_MEDTRONIC_CALIBRATION_DONE); - mClients.get(i).send(mSend); - - } catch (RemoteException e) { - // The client is dead. Remove it from the list; we are going - // through the list from back to front so this is safe to do - // inside the loop. - mClients.remove(i); - } - } - } - - /** - * Sends message to the UI to indicate that the device is disconnected. - */ - private void sendMessageDisconnectedToUI() { - Log.i("medtronicCGMService", "Disconnected"); - if (connectedSent) - log.debug("Send Message Disconnected to UI"); - connectedSent = false; - for (int i = mClients.size() - 1; i >= 0; i--) { - try { - Message mSend = null; - mSend = Message.obtain(null, - MedtronicConstants.MSG_MEDTRONIC_CGM_NO_PERMISSION); - mClients.get(i).send(mSend); - - } catch (RemoteException e) { - // The client is dead. Remove it from the list; we are going - // through the list from back to front so this is safe to do - // inside the loop. - mClients.remove(i); - } - } - } - - @Override - public void onCreate() { - //Debug.startMethodTracing(); - log.debug("medCGM onCreate!"); - super.onCreate(); - instance = this; - if (android.os.Build.VERSION.SDK_INT > 9) - { - StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); - StrictMode.setThreadPolicy(policy); - } - - settings = getSharedPreferences(MedtronicConstants.PREFS_NAME, 0); - prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); - prefs.edit().remove("isCheckedWUP").commit(); - prefs.registerOnSharedPreferenceChangeListener(this); - - String level = prefs.getString("logLevel", "1"); - if ("2".equalsIgnoreCase(level)) - log.setLevel(Level.INFO); - else if ("3".equalsIgnoreCase(level)) - log.setLevel(Level.DEBUG); - else - log.setLevel(Level.ERROR); - - if (prefs.contains("pumpPeriod")){ - String type = prefs.getString("pumpPeriod", "1"); - if ("2".equalsIgnoreCase(type)) - pumpPeriod = MedtronicConstants.TIME_60_MIN_IN_MS; - else if ("3".equalsIgnoreCase(type)) - pumpPeriod = MedtronicConstants.TIME_90_MIN_IN_MS; - else if ("4".equalsIgnoreCase(type)) - pumpPeriod = MedtronicConstants.TIME_60_MIN_IN_MS + MedtronicConstants.TIME_60_MIN_IN_MS; - else - pumpPeriod = MedtronicConstants.TIME_30_MIN_IN_MS; - } - if (prefs.contains("monitor_type")){ - String type = prefs.getString("monitor_type", "1"); - if ("2".equalsIgnoreCase(type)){ - if (prefs.contains("calibrationType")){ - type = prefs.getString("calibrationType", "3"); - if ("3".equalsIgnoreCase(type)) - calibrationSelected = MedtronicConstants.CALIBRATION_MANUAL; - else if ("2".equalsIgnoreCase(type)){ - calibrationSelected = MedtronicConstants.CALIBRATION_SENSOR; - // start handler to ask for sensor calibration value - mHandlerSensorCalibration.postDelayed(getCalibrationFromSensor, pumpPeriod); - }else - calibrationSelected = MedtronicConstants.CALIBRATION_GLUCOMETER; - } - } - } - - wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE); - mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE); - mSerial = new Physicaloid(this); - medtronicReader = new MedtronicReader(mSerial, getBaseContext(), - mClients, null); - - Record auxRecord = MedtronicCGMService.this.loadClassFile(new File(getBaseContext().getFilesDir(), "save.bin")); - long calDate = -1; - - if (settings.contains("lastCalibrationDate")){ - calDate = settings.getLong("lastCalibrationDate", -1); - } - SharedPreferences prefs = PreferenceManager - .getDefaultSharedPreferences(getBaseContext()); - - - - DecimalFormat df = null; - if (prefs.getBoolean("mmolDecimals", false)) - df = new DecimalFormat("#.##"); - else - df = new DecimalFormat("#.#"); - if (auxRecord instanceof MedtronicSensorRecord && auxRecord != null){ - - MedtronicSensorRecord record = (MedtronicSensorRecord) auxRecord; - - if (prefs.getBoolean("mmolxl", false)){ - Float fBgValue = null; - try{ - fBgValue = (float)Integer.parseInt(record.bGValue); - log.info("mmolxl true --> "+record.bGValue); - record.bGValue = df.format(fBgValue/18f); - log.info("mmolxl/18 true --> "+record.bGValue); - }catch (Exception e){ - - } - }else - log.info("mmolxl false --> "+record.bGValue); - boolean isCalibrating = record.isCalibrating; - String calib = "---"; - if (isCalibrating){ - calib = MedtronicConstants.CALIBRATING_STR; - }else{ - calib = MedtronicConstants.getCalibrationStrValue(record.calibrationStatus); - } - calib += "\nlast cal. "; - String tail = " min. ago"; - int lastCal = 0; - if (calDate > 0){ - lastCal = (int)((System.currentTimeMillis() - calDate)/60000); - if (lastCal >= 60){ - lastCal = lastCal / 60; - tail = " hour(s) ago"; - } - } - calib+= ""+ lastCal + tail; - if (prefs.getBoolean("isWarmingUp",false)){ - calib = ""; - record.bGValue = "W_Up"; - record.trendArrow="---"; - } - medtronicReader.previousRecord = record; - } - - medtronicReader.mHandlerSensorCalibration = mHandlerSensorCalibration; - medtronicReader.getCalibrationFromSensor = getCalibrationFromSensor; - checker = medtronicReader.new CalibrationStatusChecker(mHandlerReviewParameters); - mHandlerReviewParameters.postDelayed(checker, MedtronicConstants.TIME_5_MIN_IN_MS); - IntentFilter filter = new IntentFilter(); - filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED); - registerReceiver(mUsbReceiver, filter); - mHandlerCheckSerial.removeCallbacks(readAndUpload); - mHandlerCheckSerial.post(readAndUpload); - mHandlerReloadLost.postDelayed(reloadLostRecords, 60000); - mHandlerActive = true; - long currentTime = System.currentTimeMillis(); - long diff = currentTime - settings.getLong("lastDestroy", 0); - if (diff == currentTime || diff > (2*MedtronicConstants.TIME_12_HOURS_IN_MS)) { - if (calibrationSelected == MedtronicConstants.CALIBRATION_SENSOR || !prefs.getString("glucSrcTypes","1").equals("1")) - { - if (isConnected()) - mHandler3ActivatePump.post(activateNewPump); - else - mHandler3ActivatePump.postDelayed(activateNewPump, MedtronicConstants.TIME_5_MIN_IN_MS); - } - } - //if I have selected "historic log read" then ... - if (prefs.getString("glucSrcTypes","1").equals("2")){ - medtronicReader.mHandlerCheckLastRead = null; - medtronicReader.checkLastRead = null; - log.debug("LOG READ ON CREATE"); - String type = prefs.getString("historicPeriod", "1"); - if ("2".equalsIgnoreCase(type)) - historicLogPeriod = MedtronicConstants.TIME_10_MIN_IN_MS; - else if ("3".equalsIgnoreCase(type)) - historicLogPeriod = MedtronicConstants.TIME_15_MIN_IN_MS; - else if ("4".equalsIgnoreCase(type)) - historicLogPeriod = MedtronicConstants.TIME_15_MIN_IN_MS; - else - historicLogPeriod = MedtronicConstants.TIME_5_MIN_IN_MS; - - if (settings.getLong("lastHistoricRead", 0) != 0 ){ - log.debug("PREVIOUS READ"); - if ((System.currentTimeMillis() - settings.getLong("lastHistoricRead", 0)) >= historicLogPeriod ){ - log.debug("periodRead "+(System.currentTimeMillis() - settings.getLong("lastHistoricRead", 0))+" >= "+historicLogPeriod); - mHandlerReadFromHistoric.post(readDataFromHistoric); - SharedPreferences.Editor editor = settings.edit(); - editor.putLong("lastHistoricRead", System.currentTimeMillis()); - editor.commit(); - }else{ - log.debug("Read after delay"); - mHandlerReadFromHistoric.postDelayed(readDataFromHistoric, historicLogPeriod); - } - }else{ - log.debug("Read log immediatly"); - mHandlerReadFromHistoric.post(readDataFromHistoric); - SharedPreferences.Editor editor = settings.edit(); - editor.putLong("lastHistoricRead", System.currentTimeMillis()); - editor.commit(); - } - - }else if (prefs.getString("glucSrcTypes","1").equals("3")){ - medtronicReader.mHandlerCheckLastRead = mHandlerCheckLastRead; - medtronicReader.checkLastRead = checkLastRead; - - String type = prefs.getString("historicMixPeriod", "1"); - if ("2".equalsIgnoreCase(type)) - historicLogPeriod = MedtronicConstants.TIME_15_MIN_IN_MS; - else if ("3".equalsIgnoreCase(type)) - historicLogPeriod = MedtronicConstants.TIME_20_MIN_IN_MS; - else if ("4".equalsIgnoreCase(type)) - historicLogPeriod = MedtronicConstants.TIME_20_MIN_IN_MS + MedtronicConstants.TIME_5_MIN_IN_MS; - else if ("5".equalsIgnoreCase(type)) - historicLogPeriod = MedtronicConstants.TIME_30_MIN_IN_MS; - else if ("6".equalsIgnoreCase(type)) - historicLogPeriod = MedtronicConstants.TIME_30_MIN_IN_MS + MedtronicConstants.TIME_5_MIN_IN_MS; - else if ("7".equalsIgnoreCase(type)) - historicLogPeriod = MedtronicConstants.TIME_30_MIN_IN_MS + MedtronicConstants.TIME_10_MIN_IN_MS; - else if ("8".equalsIgnoreCase(type)) - historicLogPeriod = MedtronicConstants.TIME_30_MIN_IN_MS + MedtronicConstants.TIME_15_MIN_IN_MS; - else if ("9".equalsIgnoreCase(type)) - historicLogPeriod = MedtronicConstants.TIME_30_MIN_IN_MS + MedtronicConstants.TIME_20_MIN_IN_MS; - else if ("10".equalsIgnoreCase(type)) - historicLogPeriod = MedtronicConstants.TIME_60_MIN_IN_MS - MedtronicConstants.TIME_5_MIN_IN_MS; - else if ("11".equalsIgnoreCase(type)) - historicLogPeriod = MedtronicConstants.TIME_60_MIN_IN_MS; - else - historicLogPeriod = MedtronicConstants.TIME_10_MIN_IN_MS; - mHandlerCheckLastRead.post(checkLastRead); - - } - - } - - @Override - public void onDestroy() { - //Debug.stopMethodTracing(); - log.debug("medCGM onDestroy!"); - isDestroying = true; - prefs.unregisterOnSharedPreferenceChangeListener(this); - synchronized (medtronicReader.processingCommandLock) { - SharedPreferences.Editor editor = prefs.edit(); - - editor.putBoolean("wasProcessing", medtronicReader.processingCommand); - editor.commit(); - } - synchronized (reloadLostLock) { - mHandlerReloadLost.removeCallbacks(reloadLostRecords); - } - synchronized (checkSerialLock) { - Log.i(TAG, "onDestroy called"); - log.debug("Medtronic Service onDestroy called"); - mHandlerCheckSerial.removeCallbacks(readAndUpload); - - if (NM != null) { - NM.cancelAll(); - NM = null; - } - SharedPreferences.Editor editor = settings.edit(); - editor.putLong("lastDestroy", System.currentTimeMillis()); - editor.commit(); - closeUsbSerial(); - mHandlerActive = false; - unregisterReceiver(mUsbReceiver); - } - mHandlerReadFromHistoric.removeCallbacks(readDataFromHistoric); - mHandlerCheckLastRead.removeCallbacks(checkLastRead); - synchronized (isUploadingLock) { - super.onDestroy(); - } - } - - - /** - * Check last Historic Log read. (This will not be possible in newer Medtronic Pumps) - */ - private Runnable checkLastRead = new Runnable() { - public void run() { - if (prefs.getString("glucSrcTypes","1").equals("3")){ - - String type = prefs.getString("historicMixPeriod", "1"); - if ("2".equalsIgnoreCase(type)) - historicLogPeriod = MedtronicConstants.TIME_15_MIN_IN_MS; - else if ("3".equalsIgnoreCase(type)) - historicLogPeriod = MedtronicConstants.TIME_20_MIN_IN_MS; - else if ("4".equalsIgnoreCase(type)) - historicLogPeriod = MedtronicConstants.TIME_20_MIN_IN_MS + MedtronicConstants.TIME_5_MIN_IN_MS; - else if ("5".equalsIgnoreCase(type)) - historicLogPeriod = MedtronicConstants.TIME_30_MIN_IN_MS; - else if ("6".equalsIgnoreCase(type)) - historicLogPeriod = MedtronicConstants.TIME_30_MIN_IN_MS + MedtronicConstants.TIME_5_MIN_IN_MS; - else if ("7".equalsIgnoreCase(type)) - historicLogPeriod = MedtronicConstants.TIME_30_MIN_IN_MS + MedtronicConstants.TIME_10_MIN_IN_MS; - else if ("8".equalsIgnoreCase(type)) - historicLogPeriod = MedtronicConstants.TIME_30_MIN_IN_MS + MedtronicConstants.TIME_15_MIN_IN_MS; - else if ("9".equalsIgnoreCase(type)) - historicLogPeriod = MedtronicConstants.TIME_30_MIN_IN_MS + MedtronicConstants.TIME_20_MIN_IN_MS; - else if ("10".equalsIgnoreCase(type)) - historicLogPeriod = MedtronicConstants.TIME_60_MIN_IN_MS - MedtronicConstants.TIME_5_MIN_IN_MS; - else if ("11".equalsIgnoreCase(type)) - historicLogPeriod = MedtronicConstants.TIME_60_MIN_IN_MS; - else - historicLogPeriod = MedtronicConstants.TIME_10_MIN_IN_MS; - - if (medtronicReader != null && medtronicReader.lastSensorValueDate > 0){ - if ((System.currentTimeMillis() - medtronicReader.lastSensorValueDate) >= historicLogPeriod ){ - if (settings.getLong("lastHistoricRead", 0) != 0 ){ - if ((System.currentTimeMillis() - settings.getLong("lastHistoricRead", 0)) >= historicLogPeriod ){ - mHandlerReadFromHistoric.post(readDataFromHistoric); - return; - } - }else{ - mHandlerReadFromHistoric.post(readDataFromHistoric); - return; - } - } - }else{ - if (settings.getLong("lastHistoricRead", 0) != 0 ){ - if ((System.currentTimeMillis() - settings.getLong("lastHistoricRead", 0)) >= historicLogPeriod ){ - mHandlerReadFromHistoric.post(readDataFromHistoric); - return; - } - }else{ - mHandlerReadFromHistoric.post(readDataFromHistoric); - return; - } - } - mHandlerCheckLastRead.postDelayed(checkLastRead, MedtronicConstants.TIME_10_MIN_IN_MS); - } - - } - }; - - - /** - * Listener which throws a handler that manages the reading from the serial buffer, when a read happens - */ - private ReadLisener readListener = new ReadLisener() { - - @Override - public void onRead(int size) { - synchronized (readByListenerSizeLock) { - if (readByListener.size > -1) - readByListener.size += size; - else - readByListener.size = size; - } - mHandlerRead.post(readByListener); - - } - - }; - /** - * Runnable. - * It checks that it is a serial device available, and there is Internet connection. - * It also binds readByListener with the serial device and execute it the first time; - */ - private Runnable readAndUpload = new Runnable() { - public void run() { - log.debug("run readAndUpload"); - try { - UsbManager usbManager = (UsbManager) getSystemService(Context.USB_SERVICE); - boolean hasPermission = false; - for (final UsbDevice usbDevice : usbManager.getDeviceList() - .values()) { - if (!usbManager.hasPermission(usbDevice)) { - continue; - } else { - hasPermission = true; - // sendMessageConnectedToUI(); - } - } - if (!hasPermission) { - synchronized (checkSerialLock) { - log.debug("I have lost usb permission changing listener attached to false..."); - listenerAttached = false; - mSerial.clearReadListener(); - mHandlerRead.removeCallbacks(readByListener); - sendMessageDisconnectedToUI(); - if (!mHandlerActive || isDestroying){ - log.debug("destroy readAnd Upload "+ mHandlerActive + " isDes "+ isDestroying); - return; - } - mHandlerCheckSerial.removeCallbacks(readAndUpload); - mHandlerCheckSerial.postDelayed(readAndUpload, MedtronicConstants.FIVE_SECONDS__MS); - return; - } - } else - sendMessageConnectedToUI(); - boolean connected = false; - synchronized (mSerialLock) { - connected = isConnected(); - } - if (connected) { - if (!isOnline()) - sendErrorMessageToUI("NET connection error"); - if (!listenerAttached) { - log.debug("!listener attached readByListener triggered"); - mSerial.clearReadListener(); - mHandlerRead.removeCallbacks(readByListener); - mSerial.addReadListener(readListener); - mHandlerRead.post(readByListener); - listenerAttached = true; - - if (calibrationSelected == MedtronicConstants.CALIBRATION_SENSOR){ - mHandlerSensorCalibration.removeCallbacks(getCalibrationFromSensor); - mHandlerSensorCalibration.postDelayed(getCalibrationFromSensor, MedtronicConstants.FIVE_SECONDS__MS); - } - /*long timeToAwake = pumpPeriod; - if (timeToAwake > -1){ - if (prefs != null){ - if (prefs.contains("wasProcessing") && prefs.getBoolean("wasProcessing", true)) - timeToAwake = 6*MedtronicConstants.FIVE_SECONDS__MS; - else if (prefs.contains("lastPumpAwake")){ - long diff = System.currentTimeMillis() - prefs.getLong("lastPumpAwake", 0); - if (diff >= pumpPeriod) - timeToAwake = 6*MedtronicConstants.FIVE_SECONDS__MS; - else - timeToAwake = diff; - }else - timeToAwake = 6*MedtronicConstants.FIVE_SECONDS__MS; - }else - timeToAwake = 2*MedtronicConstants.FIVE_SECONDS__MS; - if (timeToAwake < 0) - timeToAwake = 2*MedtronicConstants.FIVE_SECONDS__MS; - mHandler3ActivatePump.removeCallbacks(activateNewPump); - mHandler3ActivatePump.postDelayed(activateNewPump, timeToAwake); - }else - mHandler3ActivatePump.post(activateNewPump);*/ - } - - } else { - - if (!connected) - openUsbSerial(false); - connected = isConnected(); - - if (!connected) - sendErrorMessageToUI("Receptor connection error"); - else if (!isOnline()) - sendErrorMessageToUI("NET connection error"); - else { - sendMessageConnectedToUI(); - sendMessageToUI("connected", false); - } - } - - } catch (Exception e) { - Log.e(TAG, "Unable to read from receptor or upload", e); - StringBuffer sb1 = new StringBuffer(""); - sb1.append("EXCEPTION!!!!!! " + e.getMessage() + " " - + e.getCause()); - for (StackTraceElement st : e.getStackTrace()) { - sb1.append(st.toString()).append("\n"); - ; - } - sendMessageToUI(sb1.toString(), false); - log.error("Unable to read from receptor or upload \n"+ e.toString()); - } - synchronized (checkSerialLock) { - if (!mHandlerActive || isDestroying){ - log.debug("destroy readAnd Upload2 "+ mHandlerActive + " isDes "+ isDestroying); - return; - } - mHandlerCheckSerial.removeCallbacks(readAndUpload); - mHandlerCheckSerial.postDelayed(readAndUpload, MedtronicConstants.FIVE_SECONDS__MS); - } - } - }; - - /** - * Runnable. - * Executes doReadAndUploadFunction; - */ - private class ReadByListener implements Runnable { - public Integer size = -1; - public void run() { - int auxSize = 0; - synchronized (readByListenerSizeLock) { - auxSize = size; - size = -1; - } - if (auxSize >= 0){ - log.debug("Quiero leer "+auxSize+" bytes"); - doReadAndUpload(auxSize); - isReloaded = false; - }else{ - log.debug("ReadByListener NO TIENE NADA QUE SUBIR"); - if (!isReloaded){ - openUsbSerial(true); - medtronicReader.mSerialDevice = mSerial; - } - } - } - }; - - /** - * Process all the parsed messages, checks if there is Records to upload and executes the uploader if necessary. - */ - protected void doReadAndUpload(int size) { - try { - synchronized (mSerialLock) { - if (mSerial.isOpened() && !isDestroying) { - - log.debug("doREadAndUpload"); - ArrayList<byte[]> bufferedMessages = medtronicReader - .readFromReceiver(getApplicationContext(), size); - log.debug("Stream Received--> READED"); - if (bufferedMessages != null && bufferedMessages.size() > 0) { - log.debug("Stream Received--> There are "+bufferedMessages.size()+" to process "); - synchronized (buffMessagesLock) { - processBufferedMessages.bufferedMessages - .addAll(bufferedMessages); - } - if (!isDestroying){ - log.debug("Stream Received--> order process bufferedMessages "); - mHandlerProcessRead.post(processBufferedMessages); - } - }else{ - log.debug("NULL doReadAndUpload"); - } - - } - - } - } catch (Exception e) { - StringBuffer sb1 = new StringBuffer(""); - sb1.append("EXCEPTION!!!!!! " + e.getMessage() + " " + e.getCause()); - for (StackTraceElement st : e.getStackTrace()) { - sb1.append(st.toString()); - } - sendMessageToUI(sb1.toString(), false); - } - } - - - /** - * class This class process all the messages received after being correctly - * parsed. - */ - private Runnable reloadLostRecords = new Runnable() { - public void run() { - log.debug("Reloading Lost Records from medtronic service"); - - JSONArray recordsNotUploadedJson; - JSONArray recordsNotUploaded; - try { - recordsNotUploaded = new JSONArray(settings.getString("recordsNotUploaded","[]")); - recordsNotUploadedJson = new JSONArray(settings.getString("recordsNotUploadedJson","[]")); - synchronized (reloadLostLock) { - if (isOnline()){ - log.debug("reloadnotupload is online "+recordsNotUploaded.length() +" -> "+recordsNotUploadedJson.length() +" "+ !isDestroying); - if ((recordsNotUploaded.length() > 0 || recordsNotUploadedJson.length() > 0) && !isDestroying) { - log.debug("to upload old records"); - uploader = new UploadHelper(getApplicationContext(), - Medtronic640gActivity.MEDTRONIC_CGM, - mClients); - if (!isDBInitialized){ - isDBInitialized = initializeDB(); - if (!isDBInitialized){ - if (!isDestroying) - mHandlerReloadLost.postDelayed(reloadLostRecords, 60000); - return; - } - } - uploader.dbURI = dbURI; - uploader.collectionName = collectionName; - uploader.dsCollectionName = dsCollectionName; - uploader.gdCollectionName = gdCollectionName; - uploader.devicesCollectionName = devicesCollectionName; - uploader.db = db; - uploader.dexcomData = dexcomData; - uploader.glucomData = glucomData; - uploader.deviceData = deviceData; - uploader.dsCollection = dsCollection; - - Record[] params = new Record[0]; - log.debug("calling uploader"); - uploader.execute(params); - log.debug("uploader called"); - } - }else{ - if (!isDestroying) - mHandlerReloadLost.postDelayed(reloadLostRecords, 60000); - } - } - - } catch (JSONException e) { - - log.error("Error Reloading Lost Records"); - e.printStackTrace(); - } - - if (!isDestroying) - mHandlerReloadLost.postDelayed(reloadLostRecords, 60000); - log.debug("lost records reloaded from medtronic service"); - } - }; - /** - * class This class process all the messages received after being correctly - * parsed. - */ - private class BufferedMessagesProcessor implements Runnable { - public ArrayList<byte[]> bufferedMessages = new ArrayList<byte[]>(); - public String sResult = ""; - public void run() { - log.debug("Processing bufferedMessages "); - synchronized (isUploadingLock) { - log.debug("I am Not Uploading "); - - try { - ArrayList<byte[]> bufferedMessages2Process = new ArrayList<byte[]>(); - synchronized (resultLock) { - sResult = ""; - } - synchronized (buffMessagesLock) { - bufferedMessages2Process.addAll(bufferedMessages); - bufferedMessages.clear(); - } - log.debug("I am going to process "+ bufferedMessages2Process.size()+" Messages"); - synchronized (resultLock) { - sResult = medtronicReader - .processBufferedMessages(bufferedMessages2Process); - } - // ONLY FOR DEBUG PURPOUSES - // if (!"".equals(sResult)) - // sendMessageToUI(sResult,false); - // execute uploader - List<Record> listToUpload = new ArrayList<Record>(); - // upload sensor values if available - if (medtronicReader.lastElementsAdded > 0 - && medtronicReader.lastRecordsInMemory != null - && medtronicReader.lastRecordsInMemory.size() >= medtronicReader.lastElementsAdded) { - listToUpload - .addAll(medtronicReader.lastRecordsInMemory - .getListFromTail(medtronicReader.lastElementsAdded));// most - // recent - // First - medtronicReader.lastElementsAdded = 0; - } - // upload glucometer value if available - if (medtronicReader.lastGlucometerRecord != null) { - listToUpload.add(medtronicReader.lastGlucometerRecord); - medtronicReader.lastGlucometerRecord = null; - } - // upload device info if available - if (medtronicReader.lastMedtronicPumpRecord != null) { - listToUpload.add(medtronicReader.lastMedtronicPumpRecord); - medtronicReader.lastMedtronicPumpRecord = null; - } - - - Record[] params = new Record[listToUpload.size()]; - for (int i = listToUpload.size() - 1; i >= 0; i--) { - Record record = listToUpload.get(i); - params[listToUpload.size() - 1 - i] = record; - } - if (params.length > 0) { - synchronized (reloadLostLock) { - uploader = new UploadHelper(getApplicationContext(), - Medtronic640gActivity.MEDTRONIC_CGM, - mClients); - if (!isDBInitialized){ - isDBInitialized = initializeDB(); - } - uploader.dbURI = dbURI; - uploader.collectionName = collectionName; - uploader.dsCollectionName = dsCollectionName; - uploader.gdCollectionName = gdCollectionName; - uploader.devicesCollectionName = devicesCollectionName; - uploader.db = db; - uploader.dexcomData = dexcomData; - uploader.glucomData = glucomData; - uploader.deviceData = deviceData; - uploader.dsCollection = dsCollection; - - uploader.execute(params); - } - } - params = null; - - listToUpload.clear(); - } catch (Exception e) { - StringBuffer sb1 = new StringBuffer(""); - sb1.append("EXCEPTION!!!!!! " + e.getMessage() + " " - + e.getCause()); - for (StackTraceElement st : e.getStackTrace()) { - sb1.append(st.toString()).append("\n"); - } - sendMessageToUI(sb1.toString() + "\n " + sResult, false); - } - } - log.debug("Buffered Messages Processed "); - } - - }; - - private boolean isConnected() { - return mSerial.isOpened(); - } - - private boolean isOnline() { - ConnectivityManager connectivity = (ConnectivityManager) getBaseContext().getSystemService(Context.CONNECTIVITY_SERVICE); - boolean isOnline = false; - if (connectivity != null) { - NetworkInfo[] info = connectivity.getAllNetworkInfo(); - if (info != null) { - for (int i = 0; (i < info.length) && !isOnline; i++) { - log.debug("INTERNET: "+String.valueOf(i)); - if (info[i].getState() == NetworkInfo.State.CONNECTED) { - log.debug("INTERNET: connected!"); - return true; - } - } - } - }else - return false; - return isOnline; - } - - /** - * Launches a pop up message - * @param message - */ - private void displayMessage(String message) { - Toast toast = Toast.makeText(getBaseContext(), message, - Toast.LENGTH_LONG); - toast.setGravity(Gravity.CENTER, 0, 0); - LinearLayout toastLayout = (LinearLayout) toast.getView(); - TextView toastTV = (TextView) toastLayout.getChildAt(0); - if (toastTV != null) { - toastTV.setTextSize(20); - toastTV.setGravity(Gravity.CENTER_VERTICAL - | Gravity.CENTER_HORIZONTAL); - } - toast.show(); - - } - - private void openUsbSerial(boolean reload) { - if (mSerial == null) { - Toast.makeText(this, "cannot open", Toast.LENGTH_SHORT).show(); - return; - } - if (mSerial.isOpened() && reload){ - mSerial.close(); - mSerial.clearReadListener(); - listenerAttached = false; - } - - synchronized (mSerialLock) { - if (!mSerial.isOpened()) { - if (!mSerial.open()) { - Toast.makeText(this, "cannot open", Toast.LENGTH_SHORT) - .show(); - return; - } else { - if (!isReloaded && reload) - isReloaded = true; - boolean dtrOn = true; - boolean rtsOn = false; - mSerial.setConfig(new UartConfig(57600, 8, 1, 0, dtrOn, - rtsOn)); - if (!reload) - Toast.makeText(this, "connected", Toast.LENGTH_SHORT) - .show(); - } - } - } - if (!listenerAttached && reload) { - mSerial.addReadListener(readListener); - listenerAttached = true; - } - - } - - //Deserialize the EGVRecord (most recent) value - public Record loadClassFile(File f) { - ObjectInputStream ois = null; - try { - ois = new ObjectInputStream(new FileInputStream(f)); - Object o = ois.readObject(); - ois.close(); - return (Record) o; - } catch (Exception ex) { - Log.w(TAG, " unable to loadEGVRecord"); - try{ - if (ois != null) - ois.close(); - }catch(Exception e){ - Log.e(TAG, " Error closing ObjectInputStream"); - } - } - return new Record(); - } - - private void closeUsbSerial() { - mSerial.clearReadListener(); - mHandlerRead.removeCallbacks(readByListener); - mHandlerProcessRead.removeCallbacks(processBufferedMessages); - mHandler2CheckDevice.removeCallbacks(cMThread); - mHandler3ActivatePump.removeCallbacks(activateNewPump); - mHandlerSensorCalibration.removeCallbacks(getCalibrationFromSensor); - mHandlerReviewParameters.removeCallbacks(checker); - listenerAttached = false; - mSerial.close(); - } - - /** - * BroadcastReceiver when insert/remove the device USB plug into/from a USB port - */ - BroadcastReceiver mUsbReceiver = new BroadcastReceiver() { - public void onReceive(Context context, Intent intent) { - String action = intent.getAction(); - if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) { - sendMessageDisconnectedToUI(); - closeUsbSerial(); - } - } - }; - - /** - * Method inherited from "OnSharedPreferenceChangeListener" - * Here we listen to the change of some preferences of interest to keep or remove the status - * of our application. - */ - @Override - public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, - String key) { - try { - if (key.equalsIgnoreCase("EnableMongoUpload") || key.equalsIgnoreCase("MongoDB URI") || key.equalsIgnoreCase("Collection Name") || key.equalsIgnoreCase("gcdCollectionName")){ - isDBInitialized = false; - } - if (key.equalsIgnoreCase("logLevel")){ - String level = sharedPreferences.getString("logLevel", "1"); - if ("2".equalsIgnoreCase(level)) - log.setLevel(Level.INFO); - else if ("3".equalsIgnoreCase(level)) - log.setLevel(Level.DEBUG); - else - log.setLevel(Level.ERROR); - } - if (sharedPreferences.contains("monitor_type") && key.equalsIgnoreCase("monitor_type")){ - String type = sharedPreferences.getString("monitor_type", "1"); - if ("2".equalsIgnoreCase(type)){ - if (sharedPreferences.contains("calibrationType")){ - type = sharedPreferences.getString("calibrationType", "3"); - if ("3".equalsIgnoreCase(type)){ - calibrationSelected = MedtronicConstants.CALIBRATION_MANUAL; - mHandlerSensorCalibration.removeCallbacks(getCalibrationFromSensor); - }else if ("2".equalsIgnoreCase(type)){ - type = sharedPreferences.getString("pumpPeriod", "1"); - if ("2".equalsIgnoreCase(type)) - pumpPeriod = MedtronicConstants.TIME_60_MIN_IN_MS; - else if ("3".equalsIgnoreCase(type)) - pumpPeriod = MedtronicConstants.TIME_90_MIN_IN_MS; - else if ("4".equalsIgnoreCase(type)) - pumpPeriod = MedtronicConstants.TIME_60_MIN_IN_MS + MedtronicConstants.TIME_60_MIN_IN_MS; - else - pumpPeriod = MedtronicConstants.TIME_30_MIN_IN_MS; - calibrationSelected = MedtronicConstants.CALIBRATION_SENSOR; - //start handler to ask for sensor calibration value - mHandlerSensorCalibration.removeCallbacks(getCalibrationFromSensor); - mHandlerSensorCalibration.postDelayed(getCalibrationFromSensor, pumpPeriod); - }else{ - calibrationSelected = MedtronicConstants.CALIBRATION_GLUCOMETER; - mHandlerSensorCalibration.removeCallbacks(getCalibrationFromSensor); - } - synchronized (medtronicReader.calibrationSelectedLock) { - medtronicReader.calibrationSelected = calibrationSelected; - } - - } - } - } - - if (sharedPreferences.contains("calibrationType") && key.equalsIgnoreCase("calibrationType")){ - - String type = sharedPreferences.getString("pumpPeriod", "1"); - if ("2".equalsIgnoreCase(type)) - pumpPeriod = MedtronicConstants.TIME_60_MIN_IN_MS; - else if ("3".equalsIgnoreCase(type)) - pumpPeriod = MedtronicConstants.TIME_90_MIN_IN_MS; - else if ("4".equalsIgnoreCase(type)) - pumpPeriod = MedtronicConstants.TIME_60_MIN_IN_MS + MedtronicConstants.TIME_60_MIN_IN_MS; - else - pumpPeriod = MedtronicConstants.TIME_30_MIN_IN_MS; - - type = sharedPreferences.getString("calibrationType", "3"); - if ("3".equalsIgnoreCase(type)){ - calibrationSelected = MedtronicConstants.CALIBRATION_MANUAL; - mHandlerSensorCalibration.removeCallbacks(getCalibrationFromSensor); - }else if ("2".equalsIgnoreCase(type)){ - calibrationSelected = MedtronicConstants.CALIBRATION_SENSOR; - //start handler to ask for sensor calibration value - mHandlerSensorCalibration.removeCallbacks(getCalibrationFromSensor); - mHandlerSensorCalibration.postDelayed(getCalibrationFromSensor, pumpPeriod); - }else{ - calibrationSelected = MedtronicConstants.CALIBRATION_GLUCOMETER; - mHandlerSensorCalibration.removeCallbacks(getCalibrationFromSensor); - } - synchronized (medtronicReader.calibrationSelectedLock) { - medtronicReader.calibrationSelected = calibrationSelected; - } - String type1 = sharedPreferences.getString("glucSrcTypes", "1"); - if (calibrationSelected != MedtronicConstants.CALIBRATION_SENSOR && type1.equals("1")){ - mHandler3ActivatePump.removeCallbacks(getCalibrationFromSensor); - } - } - if (key.equalsIgnoreCase("pumpPeriod")){ - if (sharedPreferences.contains("pumpPeriod")){ - String type = sharedPreferences.getString("pumpPeriod", "1"); - if ("2".equalsIgnoreCase(type)) - pumpPeriod = MedtronicConstants.TIME_60_MIN_IN_MS; - else if ("3".equalsIgnoreCase(type)) - pumpPeriod = MedtronicConstants.TIME_90_MIN_IN_MS; - else if ("4".equalsIgnoreCase(type)) - pumpPeriod = MedtronicConstants.TIME_60_MIN_IN_MS + MedtronicConstants.TIME_60_MIN_IN_MS; - else - pumpPeriod = MedtronicConstants.TIME_30_MIN_IN_MS; - } - if (medtronicReader != null) { - mHandler3ActivatePump.removeCallbacks(getCalibrationFromSensor); - if (pumpPeriod > -1) - mHandler3ActivatePump.postDelayed(getCalibrationFromSensor, pumpPeriod); - else - mHandler3ActivatePump.post(getCalibrationFromSensor); - } - - } - if (key.equalsIgnoreCase("glucSrcTypes")){ - - String type1 = sharedPreferences.getString("glucSrcTypes", "1"); - if (calibrationSelected != MedtronicConstants.CALIBRATION_SENSOR && type1.equals("1")){ - mHandler3ActivatePump.removeCallbacks(getCalibrationFromSensor); - } - if (type1.equals("2")){ - medtronicReader.mHandlerCheckLastRead = null; - medtronicReader.checkLastRead = null; - mHandlerReadFromHistoric.removeCallbacks(readDataFromHistoric); - - String type = prefs.getString("historicPeriod", "1"); - if ("2".equalsIgnoreCase(type)) - historicLogPeriod = MedtronicConstants.TIME_10_MIN_IN_MS; - else if ("3".equalsIgnoreCase(type)) - historicLogPeriod = MedtronicConstants.TIME_15_MIN_IN_MS; - else if ("4".equalsIgnoreCase(type)) - historicLogPeriod = MedtronicConstants.TIME_15_MIN_IN_MS; - else - historicLogPeriod = MedtronicConstants.TIME_5_MIN_IN_MS; - - if (settings.getLong("lastHistoricRead", 0) != 0 ){ - if ((System.currentTimeMillis() - settings.getLong("lastHistoricRead", 0)) >= historicLogPeriod ){ - mHandlerReadFromHistoric.post(readDataFromHistoric); - SharedPreferences.Editor editor = settings.edit(); - editor.putLong("lastHistoricRead", System.currentTimeMillis()); - editor.commit(); - } - }else{ - mHandlerReadFromHistoric.post(readDataFromHistoric); - SharedPreferences.Editor editor = settings.edit(); - editor.putLong("lastHistoricRead", System.currentTimeMillis()); - editor.commit(); - } - - }else if (type1.equals("1")){ - medtronicReader.mHandlerCheckLastRead = null; - medtronicReader.checkLastRead = null; - mHandlerReadFromHistoric.removeCallbacks(readDataFromHistoric); - mHandlerCheckLastRead.removeCallbacks(checkLastRead); - }else if (type1.equals("3")){ - medtronicReader.mHandlerCheckLastRead = mHandlerCheckLastRead; - medtronicReader.checkLastRead = checkLastRead; - mHandlerCheckLastRead.removeCallbacks(checkLastRead); - String type = prefs.getString("historicMixPeriod", "1"); - if ("2".equalsIgnoreCase(type)) - historicLogPeriod = MedtronicConstants.TIME_15_MIN_IN_MS; - else if ("3".equalsIgnoreCase(type)) - historicLogPeriod = MedtronicConstants.TIME_20_MIN_IN_MS; - else if ("4".equalsIgnoreCase(type)) - historicLogPeriod = MedtronicConstants.TIME_20_MIN_IN_MS + MedtronicConstants.TIME_5_MIN_IN_MS; - else if ("5".equalsIgnoreCase(type)) - historicLogPeriod = MedtronicConstants.TIME_30_MIN_IN_MS; - else if ("6".equalsIgnoreCase(type)) - historicLogPeriod = MedtronicConstants.TIME_30_MIN_IN_MS + MedtronicConstants.TIME_5_MIN_IN_MS; - else if ("7".equalsIgnoreCase(type)) - historicLogPeriod = MedtronicConstants.TIME_30_MIN_IN_MS + MedtronicConstants.TIME_10_MIN_IN_MS; - else if ("8".equalsIgnoreCase(type)) - historicLogPeriod = MedtronicConstants.TIME_30_MIN_IN_MS + MedtronicConstants.TIME_15_MIN_IN_MS; - else if ("9".equalsIgnoreCase(type)) - historicLogPeriod = MedtronicConstants.TIME_30_MIN_IN_MS + MedtronicConstants.TIME_20_MIN_IN_MS; - else if ("10".equalsIgnoreCase(type)) - historicLogPeriod = MedtronicConstants.TIME_60_MIN_IN_MS - MedtronicConstants.TIME_5_MIN_IN_MS; - else if ("11".equalsIgnoreCase(type)) - historicLogPeriod = MedtronicConstants.TIME_60_MIN_IN_MS; - else - historicLogPeriod = MedtronicConstants.TIME_10_MIN_IN_MS; - mHandlerCheckLastRead.post(checkLastRead); - - } - - - } - if (key.equalsIgnoreCase("historicPeriod")){ - mHandlerReadFromHistoric.removeCallbacks(readDataFromHistoric); - String type = sharedPreferences.getString("historicPeriod", "1"); - if ("2".equalsIgnoreCase(type)) - historicLogPeriod = MedtronicConstants.TIME_10_MIN_IN_MS; - else if ("3".equalsIgnoreCase(type)) - historicLogPeriod = MedtronicConstants.TIME_15_MIN_IN_MS; - else if ("4".equalsIgnoreCase(type)) - historicLogPeriod = MedtronicConstants.TIME_15_MIN_IN_MS; - else - historicLogPeriod = MedtronicConstants.TIME_5_MIN_IN_MS; - - mHandlerReadFromHistoric.post(readDataFromHistoric); - SharedPreferences.Editor editor = settings.edit(); - editor.putLong("lastHistoricRead", System.currentTimeMillis()); - editor.commit(); - } - if (key.equals("MongoDB URI")){ - initializeDB(); - } - if (key.equals("medtronic_cgm_id") || key.equals("glucometer_cgm_id") || key.equals("sensor_cgm_id")) { - String newID = sharedPreferences.getString("medtronic_cgm_id", ""); - if (newID != null && !"".equals(newID.replaceAll(" ", ""))) { - mHandlerCheckSerial.removeCallbacks(readAndUpload); - byte[] newIdPump = HexDump.hexStringToByteArray(newID); - if (key.equals("medtronic_cgm_id") && !Arrays.equals(newIdPump, medtronicReader.idPump)) { - SharedPreferences.Editor editor = settings.edit(); - editor.remove("lastGlucometerMessage"); - editor.remove("previousValue"); - editor.remove("expectedSensorSortNumber"); - editor.remove("knownDevices"); - editor.remove("isCalibrating"); - editor.remove("previousValue"); - editor.remove("expectedSensorSortNumber"); - editor.remove("lastGlucometerValue"); - editor.remove("lastGlucometerDate"); - editor.remove("expectedSensorSortNumberForCalibration0"); - editor.remove("expectedSensorSortNumberForCalibration1"); - editor.remove("lastPumpAwake"); - editor.commit(); - synchronized (checkSerialLock) { - - mHandlerCheckSerial.removeCallbacks(readAndUpload); - - mHandlerActive = false; - - } - medtronicReader = new MedtronicReader(mSerial, - getBaseContext(), mClients, null); - medtronicReader.idPump = newIdPump; - synchronized (checkSerialLock) { - mHandlerCheckSerial.post(readAndUpload); - mHandlerActive = true; - if (medtronicReader != null) { - mHandler3ActivatePump.removeCallbacks(activateNewPump); - mHandler3ActivatePump.post(activateNewPump); - mHandlerReadFromHistoric.removeCallbacks(readDataFromHistoric); - if (hGetter == null){ - hGetter = new HistoricGetterThread(mClients, medtronicReader, - medtronicReader.idPump, mSerial, mHandlerReadFromHistoric); - - }else - hGetter.init(); - medtronicReader.historicPageIndex = -1; - medtronicReader.historicPageShift = 0; - medtronicReader.datalog = new DataLog(); - String type1 = sharedPreferences.getString("glucSrcTypes", "1"); - if (type1.equals("2")){ - medtronicReader.mHandlerCheckLastRead = null; - medtronicReader.checkLastRead = null; - mHandlerReadFromHistoric.removeCallbacks(readDataFromHistoric); - if (prefs.contains("historicPeriod")){ - String type = prefs.getString("historicPeriod", "1"); - if ("2".equalsIgnoreCase(type)) - historicLogPeriod = MedtronicConstants.TIME_10_MIN_IN_MS; - else if ("3".equalsIgnoreCase(type)) - historicLogPeriod = MedtronicConstants.TIME_15_MIN_IN_MS; - else if ("4".equalsIgnoreCase(type)) - historicLogPeriod = MedtronicConstants.TIME_15_MIN_IN_MS; - else - historicLogPeriod = MedtronicConstants.TIME_5_MIN_IN_MS; - } - if (settings.getLong("lastHistoricRead", 0) != 0 ){ - if ((System.currentTimeMillis() - settings.getLong("lastHistoricRead", 0)) >= historicLogPeriod ){ - mHandlerReadFromHistoric.post(readDataFromHistoric); - SharedPreferences.Editor editor2 = settings.edit(); - editor2.putLong("lastHistoricRead", System.currentTimeMillis()); - editor2.commit(); - } - }else{ - mHandlerReadFromHistoric.post(readDataFromHistoric); - SharedPreferences.Editor editor2 = settings.edit(); - editor2.putLong("lastHistoricRead", System.currentTimeMillis()); - editor2.commit(); - } - - }else if (type1.equals("1")){ - medtronicReader.mHandlerCheckLastRead = null; - medtronicReader.checkLastRead = null; - mHandlerReadFromHistoric.removeCallbacks(readDataFromHistoric); - mHandlerCheckLastRead.removeCallbacks(checkLastRead); - }else if (type1.equals("3")){ - medtronicReader.mHandlerCheckLastRead = mHandlerCheckLastRead; - medtronicReader.checkLastRead = checkLastRead; - mHandlerCheckLastRead.removeCallbacks(checkLastRead); - String type = prefs.getString("historicMixPeriod", "1"); - if ("2".equalsIgnoreCase(type)) - historicLogPeriod = MedtronicConstants.TIME_15_MIN_IN_MS; - else if ("3".equalsIgnoreCase(type)) - historicLogPeriod = MedtronicConstants.TIME_20_MIN_IN_MS; - else if ("4".equalsIgnoreCase(type)) - historicLogPeriod = MedtronicConstants.TIME_20_MIN_IN_MS + MedtronicConstants.TIME_5_MIN_IN_MS; - else if ("5".equalsIgnoreCase(type)) - historicLogPeriod = MedtronicConstants.TIME_30_MIN_IN_MS; - else if ("6".equalsIgnoreCase(type)) - historicLogPeriod = MedtronicConstants.TIME_30_MIN_IN_MS + MedtronicConstants.TIME_5_MIN_IN_MS; - else if ("7".equalsIgnoreCase(type)) - historicLogPeriod = MedtronicConstants.TIME_30_MIN_IN_MS + MedtronicConstants.TIME_10_MIN_IN_MS; - else if ("8".equalsIgnoreCase(type)) - historicLogPeriod = MedtronicConstants.TIME_30_MIN_IN_MS + MedtronicConstants.TIME_15_MIN_IN_MS; - else if ("9".equalsIgnoreCase(type)) - historicLogPeriod = MedtronicConstants.TIME_30_MIN_IN_MS + MedtronicConstants.TIME_20_MIN_IN_MS; - else if ("10".equalsIgnoreCase(type)) - historicLogPeriod = MedtronicConstants.TIME_60_MIN_IN_MS - MedtronicConstants.TIME_5_MIN_IN_MS; - else if ("11".equalsIgnoreCase(type)) - historicLogPeriod = MedtronicConstants.TIME_60_MIN_IN_MS; - else - historicLogPeriod = MedtronicConstants.TIME_10_MIN_IN_MS; - mHandlerCheckLastRead.post(checkLastRead); - - } - - } - - } - }else{ - if (key.equalsIgnoreCase("glucometer_cgm_id") && prefs.contains("glucometer_cgm_id")) { - if (prefs.getString("glucometer_cgm_id", "").length() > 0) { - if (!medtronicReader.knownDevices.contains(prefs.getString("glucometer_cgm_id", ""))){ - medtronicReader.knownDevices.add(prefs.getString("glucometer_cgm_id", "")); - } - medtronicReader.idGluc = HexDump.hexStringToByteArray(prefs.getString( - "glucometer_cgm_id", "")); - - } - } - if (key.equalsIgnoreCase("sensor_cgm_id") && prefs.contains("sensor_cgm_id")) { - if (prefs.getString("sensor_cgm_id", "").length() > 0) { - String sensorID = HexDump.toHexString(Integer.parseInt(prefs - .getString("sensor_cgm_id", "0"))); - while (sensorID != null && sensorID.length() > 6) { - sensorID = sensorID.substring(1); - } - if (!medtronicReader.knownDevices.contains(sensorID)){ - medtronicReader.knownDevices.add(sensorID); - } - medtronicReader.idSensor = HexDump.hexStringToByteArray(sensorID); - } - } - medtronicReader.storeKnownDevices(); - mHandlerCheckSerial.post(readAndUpload); - } - } - } - - } catch (Exception e) { - StringBuffer sb1 = new StringBuffer(""); - sb1.append("EXCEPTION!!!!!! " + e.getMessage() + " " + e.getCause()); - for (StackTraceElement st : e.getStackTrace()) { - sb1.append(st.toString()).append("\n"); - ; - } - sendMessageToUI(sb1.toString(), false); - } - } - - /** - * Runnable, - * If there is a serial device connected. - * This process wakes it up, and gather some information from it to upload to the cloud. - */ - private Runnable activateNewPump = new Runnable() { - public void run() { - boolean executed = false; - try { - synchronized (mSerialLock) { - - if (mSerial.isOpened()) { - synchronized (medtronicReader.processingCommandLock) { - if (medtronicReader.processingCommand){ - while (medtronicReader.processingCommand) { - if (medtronicReader.processingCommand) { - //if (pumpPeriod > -1){ - mHandler3ActivatePump.postDelayed(activateNewPump, - MedtronicConstants.TIMEOUT); - //} - return; - } - medtronicReader.processingCommand = true; - } - }else{ - medtronicReader.processingCommand = true; - } - } - executed = true; - byte[] initProcess = { - MedtronicConstants.MEDTRONIC_WAKE_UP, - MedtronicConstants.MEDTRONIC_GET_REMOTE_CONTROL_IDS, - MedtronicConstants.MEDTRONIC_GET_PARADIGM_LINK_IDS, - MedtronicConstants.MEDTRONIC_GET_SENSORID }; - - cMThread = new CommandSenderThread(medtronicReader, - medtronicReader.idPump, mSerial, mHandler2CheckDevice); - if (hGetter == null){ - hGetter = new HistoricGetterThread(mClients, medtronicReader, - medtronicReader.idPump, mSerial, mHandlerReadFromHistoric); - - } - medtronicReader.hGetter = hGetter; - cMThread.setCommandList(initProcess); - cMThread.setmClients(mClients); - mHandler2CheckDevice.post(cMThread); - SharedPreferences.Editor editor = prefs.edit(); - editor.putLong("lastPumpAwake", System.currentTimeMillis()); - editor.commit(); - } - } - } catch (Exception e) { - StringBuffer sb1 = new StringBuffer(""); - sb1.append("EXCEPTION!!!!!! " + e.getMessage() + " " - + e.getCause()); - for (StackTraceElement st : e.getStackTrace()) { - sb1.append(st.toString()).append("\n"); - ; - } - sendMessageToUI(sb1.toString(), false); - synchronized (medtronicReader.processingCommandLock) { - medtronicReader.processingCommand = false; - } - }finally{ - if (!executed){ - mHandler3ActivatePump.removeCallbacks(activateNewPump); - mHandler3ActivatePump.postDelayed(activateNewPump, MedtronicConstants.TIME_5_MIN_IN_MS); - } - } - - } - }; - /** - * Runnable, - * If my value source is Medtronic Historic Log (not available in newer Pump versions). - * This process wakes it up, and retrieve last historic pages from it to upload last records to the cloud. - */ - private Runnable readDataFromHistoric = new Runnable() { - public void run() { - boolean bAfterPeriod = false; - try { - log.debug("Read data from Historic"); - synchronized (mSerialLock) { - if (mSerial.isOpened()) { - log.debug("mserial open"); - synchronized (medtronicReader.processingCommandLock) { - if (medtronicReader.processingCommand){ - while (medtronicReader.processingCommand) { - if (medtronicReader.processingCommand) { - if (!prefs.getString("glucSrcTypes","1").equals("1")){ - mHandlerReadFromHistoric.postDelayed(readDataFromHistoric, - MedtronicConstants.TIMEOUT); - log.debug("TIMEOUT"); - } - bAfterPeriod = true; - return; - - } - medtronicReader.processingCommand = true; - } - }else{ - medtronicReader.processingCommand = true; - } - } - - - if (prefs.getString("glucSrcTypes","1").equals("2")){ - log.debug("EQUALS 2"); - medtronicReader.mHandlerCheckLastRead = null; - medtronicReader.checkLastRead = null; - String type = prefs.getString("historicPeriod", "1"); - if ("2".equalsIgnoreCase(type)) - historicLogPeriod = MedtronicConstants.TIME_10_MIN_IN_MS; - else if ("3".equalsIgnoreCase(type)) - historicLogPeriod = MedtronicConstants.TIME_15_MIN_IN_MS; - else if ("4".equalsIgnoreCase(type)) - historicLogPeriod = MedtronicConstants.TIME_15_MIN_IN_MS; - else - historicLogPeriod = MedtronicConstants.TIME_5_MIN_IN_MS; - - if (settings.getLong("lastHistoricRead", 0) != 0 ){ - log.debug("PREVIOUS READ"); - if ((System.currentTimeMillis() - settings.getLong("lastHistoricRead", 0)) >= historicLogPeriod ){ - if (hGetter == null){ - hGetter = new HistoricGetterThread(mClients, medtronicReader, - medtronicReader.idPump, mSerial, mHandlerReadFromHistoric); - - }else{ - hGetter.init(); - synchronized (medtronicReader.processingCommandLock) { - medtronicReader.processingCommand = true; - } - medtronicReader.historicPageIndex = -1; - medtronicReader.historicPageShift = 0; - medtronicReader.datalog = new DataLog(); - } - medtronicReader.hGetter = hGetter; - log.debug("SEND GETTER!!!!!"); - mHandlerReadFromHistoric.post(hGetter); - SharedPreferences.Editor editor = settings.edit(); - editor.putLong("lastHistoricRead", System.currentTimeMillis()); - editor.commit(); - }else{ - log.debug("Read after delay"); - bAfterPeriod = true; - mHandlerReadFromHistoric.postDelayed(readDataFromHistoric,historicLogPeriod); - synchronized (medtronicReader.processingCommandLock) { - medtronicReader.processingCommand = false; - } - return; - } - }else{ - log.debug("OTHER ELSE"); - if (hGetter == null){ - hGetter = new HistoricGetterThread(mClients, medtronicReader, - medtronicReader.idPump, mSerial, mHandlerReadFromHistoric); - - }else{ - hGetter.init(); - synchronized (medtronicReader.processingCommandLock) { - medtronicReader.processingCommand = true; - } - medtronicReader.historicPageIndex = -1; - medtronicReader.historicPageShift = 0; - medtronicReader.datalog = new DataLog(); - } - medtronicReader.hGetter = hGetter; - log.debug("SEND GETTER!!!!!"); - mHandlerReadFromHistoric.post(hGetter); - SharedPreferences.Editor editor = settings.edit(); - editor.putLong("lastHistoricRead", System.currentTimeMillis()); - editor.commit(); - } - - }else if (prefs.getString("glucSrcTypes","1").equals("3")){ - medtronicReader.mHandlerCheckLastRead = mHandlerCheckLastRead; - medtronicReader.checkLastRead = checkLastRead; - if (hGetter == null){ - hGetter = new HistoricGetterThread(mClients, medtronicReader, - medtronicReader.idPump, mSerial, mHandlerReadFromHistoric); - - }else{ - hGetter.init(); - synchronized (medtronicReader.processingCommandLock) { - medtronicReader.processingCommand = true; - } - medtronicReader.historicPageIndex = -1; - medtronicReader.historicPageShift = 0; - medtronicReader.datalog = new DataLog(); - } - medtronicReader.hGetter = hGetter; - mHandlerReadFromHistoric.post(hGetter); - log.debug("SEND GETTER!!!!!"); - mHandlerCheckLastRead.postDelayed(checkLastRead, MedtronicConstants.TIME_30_MIN_IN_MS); - } - - - - } - } - } catch (Exception e) { - StringBuffer sb1 = new StringBuffer(""); - sb1.append("EXCEPTION!!!!!! " + e.getMessage() + " " - + e.getCause()); - for (StackTraceElement st : e.getStackTrace()) { - sb1.append(st.toString()).append("\n"); - ; - } - sendMessageToUI(sb1.toString(), false); - synchronized (medtronicReader.processingCommandLock) { - medtronicReader.processingCommand = false; - } - }finally{ - log.debug("Executing read_Historic finally"); - if (prefs.getString("glucSrcTypes","1").equals("2")){ - - String type = prefs.getString("historicPeriod", "1"); - if ("2".equalsIgnoreCase(type)) - historicLogPeriod = MedtronicConstants.TIME_10_MIN_IN_MS; - else if ("3".equalsIgnoreCase(type)) - historicLogPeriod = MedtronicConstants.TIME_15_MIN_IN_MS; - else if ("4".equalsIgnoreCase(type)) - historicLogPeriod = MedtronicConstants.TIME_15_MIN_IN_MS; - else - historicLogPeriod = MedtronicConstants.TIME_5_MIN_IN_MS; - - if (settings.getLong("lastHistoricRead", 0) != 0 ){ - if ((System.currentTimeMillis() - settings.getLong("lastHistoricRead", 0)) >= historicLogPeriod ){ - SharedPreferences.Editor editor = settings.edit(); - editor.putLong("lastHistoricRead", System.currentTimeMillis()); - editor.commit(); - mHandlerReadFromHistoric.postDelayed(readDataFromHistoric, historicLogPeriod); - }else{ - mHandlerReadFromHistoric.removeCallbacks(readDataFromHistoric); - mHandlerReadFromHistoric.postDelayed(readDataFromHistoric, historicLogPeriod); - } - }else{ - mHandlerReadFromHistoric.post(readDataFromHistoric); - if (!bAfterPeriod){ - SharedPreferences.Editor editor = settings.edit(); - editor.putLong("lastHistoricRead", System.currentTimeMillis()); - editor.commit(); - } - - } - - } - } - - } - }; - /** - * Runnable, - * If there is a serial device connected. - * This process wakes it up, asks for its calibration value. - */ - private Runnable getCalibrationFromSensor = new Runnable() { - public void run() { - try { - log.debug("getting Calibration factor!!"); - synchronized (mSerialLock) { - log.debug("mSerial synchronized!"); - if (mSerial.isOpened()) { - log.debug("mSerial open!!"); - if (calibrationSelected == MedtronicConstants.CALIBRATION_SENSOR) { - synchronized (medtronicReader.processingCommandLock) { - if (medtronicReader.processingCommand){ - while (medtronicReader.processingCommand) { - if (medtronicReader.processingCommand) { - log.debug("is processing other commands wait 3 secs."); - mHandlerSensorCalibration.postDelayed(getCalibrationFromSensor, - MedtronicConstants.TIMEOUT); - return; - } - medtronicReader.processingCommand = true; - } - }else{ - medtronicReader.processingCommand = true; - } - } - byte[] initProcess = { - MedtronicConstants.MEDTRONIC_WAKE_UP, - MedtronicConstants.MEDTRONIC_GET_CALIBRATION_FACTOR, - MedtronicConstants.MEDTRONIC_GET_REMAINING_INSULIN, - MedtronicConstants.MEDTRONIC_GET_BATTERY_STATUS}; - log.debug("get Cal Factor and other info!!"); - - //mHandler2CheckDevice.removeCallbacks(cMThread); - cMThread = new CommandSenderThread(medtronicReader, - medtronicReader.idPump, mSerial, mHandler2CheckDevice); - cMThread.setCommandList(initProcess); - cMThread.setmClients(mClients); - if (hGetter == null){ - hGetter = new HistoricGetterThread(mClients, medtronicReader, - medtronicReader.idPump, mSerial, mHandlerReadFromHistoric); - - } - medtronicReader.hGetter = hGetter; - mHandler2CheckDevice.post(cMThread); - } - } - } - } catch (Exception e) { - StringBuffer sb1 = new StringBuffer(""); - sb1.append("EXCEPTION!!!!!! " + e.getMessage() + " " - + e.getCause()); - for (StackTraceElement st : e.getStackTrace()) { - sb1.append(st.toString()).append("\n"); - ; - } - sendMessageToUI(sb1.toString(), false); - synchronized (medtronicReader.processingCommandLock) { - medtronicReader.processingCommand = false; - } - }finally{ - if (pumpPeriod > -1){ - mHandlerSensorCalibration.removeCallbacks(getCalibrationFromSensor); - mHandlerSensorCalibration.postDelayed(getCalibrationFromSensor, pumpPeriod); - } - } - - } - }; -} diff --git a/app/src/main/java/info/nightscout/android/medtronic/MedtronicCNLReader.java b/app/src/main/java/info/nightscout/android/medtronic/MedtronicCNLReader.java index 68b71af..cd1b6bb 100644 --- a/app/src/main/java/info/nightscout/android/medtronic/MedtronicCNLReader.java +++ b/app/src/main/java/info/nightscout/android/medtronic/MedtronicCNLReader.java @@ -2,8 +2,21 @@ package info.nightscout.android.medtronic; import android.util.Log; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.math.BigDecimal; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Locale; +import java.util.TimeZone; +import java.util.concurrent.TimeoutException; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + import info.nightscout.android.USB.UsbHidDriver; -import info.nightscout.android.dexcom.USB.HexDump; import info.nightscout.android.medtronic.message.BeginEHSMMessage; import info.nightscout.android.medtronic.message.ChannelNegotiateMessage; import info.nightscout.android.medtronic.message.ChecksumException; @@ -24,20 +37,7 @@ import info.nightscout.android.medtronic.message.UnexpectedMessageException; import info.nightscout.android.medtronic.service.MedtronicCNLService; import info.nightscout.android.upload.MedtronicNG.CGMRecord; import info.nightscout.android.upload.MedtronicNG.PumpStatusRecord; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.math.BigDecimal; -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Locale; -import java.util.TimeZone; -import java.util.concurrent.TimeoutException; -import java.util.regex.Matcher; -import java.util.regex.Pattern; +import info.nightscout.android.utils.HexDump; /** * Created by lgoedhart on 24/03/2016. @@ -161,11 +161,11 @@ public class MedtronicCNLReader implements ContourNextLinkMessageHandler { if (response1[0] == ASCII.EOT.value) { // response 1 is the ASTM message checkControlMessage(response2, ASCII.ENQ.value); - extractStickSerial( new String( response1 ) ); + extractStickSerial(new String(response1)); } else { // response 2 is the ASTM message checkControlMessage(response1, ASCII.ENQ.value); - extractStickSerial( new String( response2 ) ); + extractStickSerial(new String(response2)); } } catch (TimeoutException e) { // Terminate comms with the pump, then try again @@ -178,10 +178,10 @@ public class MedtronicCNLReader implements ContourNextLinkMessageHandler { } } - private void extractStickSerial( String astmMessage ) { - Pattern pattern = Pattern.compile( ".*?\\^(\\d{4}-\\d{7})\\^.*" ); - Matcher matcher = pattern.matcher( astmMessage ); - if( matcher.find() ) { + private void extractStickSerial(String astmMessage) { + Pattern pattern = Pattern.compile(".*?\\^(\\d{4}-\\d{7})\\^.*"); + Matcher matcher = pattern.matcher(astmMessage); + if (matcher.find()) { mStickSerial = matcher.group(1); } } @@ -194,7 +194,7 @@ public class MedtronicCNLReader implements ContourNextLinkMessageHandler { checkControlMessage(readMessage(), ASCII.EOT.value); new ContourNextLinkCommandMessage(ASCII.ENQ.value).send(this); checkControlMessage(readMessage(), ASCII.ACK.value); - } catch( UnexpectedMessageException e2 ) { + } catch (UnexpectedMessageException e2) { // Terminate comms with the pump, then try again new ContourNextLinkCommandMessage(ASCII.EOT.value).send(this); doRetry = true; @@ -232,8 +232,8 @@ public class MedtronicCNLReader implements ContourNextLinkMessageHandler { long linkMAC = infoBuffer.getLong(0); long pumpMAC = infoBuffer.getLong(8); - this.getPumpSession().setLinkMAC( linkMAC ); - this.getPumpSession().setPumpMAC( pumpMAC ); + this.getPumpSession().setLinkMAC(linkMAC); + this.getPumpSession().setPumpMAC(pumpMAC); } public byte negotiateChannel() throws IOException, ChecksumException, TimeoutException { @@ -320,11 +320,11 @@ public class MedtronicCNLReader implements ContourNextLinkMessageHandler { // Read the data into the record long rawActiveInsulin = statusBuffer.getShort(0x33) & 0x0000ffff; - Medtronic640gActivity.pumpStatusRecord.activeInsulin = new BigDecimal( rawActiveInsulin / 10000f ).setScale(3, BigDecimal.ROUND_HALF_UP); + Medtronic640gActivity.pumpStatusRecord.activeInsulin = new BigDecimal(rawActiveInsulin / 10000f).setScale(3, BigDecimal.ROUND_HALF_UP); cgmRecord.sgv = statusBuffer.getShort(0x35) & 0x0000ffff; // In mg/DL. 0 means no CGM reading long rtc; long offset; - if( ( cgmRecord.sgv & 0x200 ) == 0x200 ) { + if ((cgmRecord.sgv & 0x200) == 0x200) { // Sensor error. Let's reset. FIXME - solve this more elegantly later cgmRecord.sgv = 0; rtc = 0; @@ -333,14 +333,14 @@ public class MedtronicCNLReader implements ContourNextLinkMessageHandler { } else { rtc = statusBuffer.getInt(0x37) & 0x00000000ffffffffL; offset = statusBuffer.getInt(0x3b); - cgmRecord.setTrend(CGMRecord.fromMessageByte( statusBuffer.get(0x40))); + cgmRecord.setTrend(CGMRecord.fromMessageByte(statusBuffer.get(0x40))); } cgmRecord.sgvDate = MessageUtils.decodeDateTime(rtc, offset); Medtronic640gActivity.pumpStatusRecord.recentBolusWizard = statusBuffer.get(0x48) != 0; Medtronic640gActivity.pumpStatusRecord.bolusWizardBGL = statusBuffer.getShort(0x49); // In mg/DL - long rawReservoirAmount = statusBuffer.getInt(0x2b) & 0xffffffff; - Medtronic640gActivity.pumpStatusRecord.reservoirAmount = new BigDecimal( rawReservoirAmount / 10000f ).setScale(3, BigDecimal.ROUND_HALF_UP); - Medtronic640gActivity.pumpStatusRecord.batteryPercentage = ( statusBuffer.get(0x2a) ); + long rawReservoirAmount = statusBuffer.getInt(0x2b) & 0xffffffff; + Medtronic640gActivity.pumpStatusRecord.reservoirAmount = new BigDecimal(rawReservoirAmount / 10000f).setScale(3, BigDecimal.ROUND_HALF_UP); + Medtronic640gActivity.pumpStatusRecord.batteryPercentage = (statusBuffer.get(0x2a)); } public void endEHSMSession() throws EncryptionException, IOException, TimeoutException { diff --git a/app/src/main/java/info/nightscout/android/medtronic/MedtronicCalibration.java b/app/src/main/java/info/nightscout/android/medtronic/MedtronicCalibration.java deleted file mode 100644 index e44e6c4..0000000 --- a/app/src/main/java/info/nightscout/android/medtronic/MedtronicCalibration.java +++ /dev/null @@ -1,5 +0,0 @@ -package info.nightscout.android.medtronic; - -public class MedtronicCalibration { - -} diff --git a/app/src/main/java/info/nightscout/android/medtronic/MedtronicConstants.java b/app/src/main/java/info/nightscout/android/medtronic/MedtronicConstants.java index 1919da9..3ed4732 100644 --- a/app/src/main/java/info/nightscout/android/medtronic/MedtronicConstants.java +++ b/app/src/main/java/info/nightscout/android/medtronic/MedtronicConstants.java @@ -1,139 +1,7 @@ package info.nightscout.android.medtronic; public class MedtronicConstants { - - //Answer types - public static final int DATA_ANSWER = 0; - public static final int COMMAND_ANSWER = 1; - public static final int FILTER_COMMAND = 2; - public static final int UNKNOWN_ANSWER = 3; - public static final int CRC_ERROR = 4; - - //General constants - public static final int DEVICE_ID_LENGTH = 3; - public static final int NUMBER_OF_RETRIES = 5; - public static final int NUMBER_OF_EGVRECORDS = 20; - public static final int TIMEOUT = 3000; - public static final int WAIT_ANSWER = 5000; - public static final int FIVE_SECONDS__MS = 5000; - public static final int TIME_5_MIN_IN_MS = 300000; - public static final int TIME_15_MIN_IN_MS = 900000; - public static final int TIME_10_MIN_IN_MS = 600000; - public static final int TIME_20_MIN_IN_MS = 1200000; - public static final int TIME_23_MIN_IN_MS = 1380000; - public static final int TIME_30_MIN_IN_MS = 1800000; + public static final String PREFS_NAME = "MyPrefsFile"; + public static final int TIME_60_MIN_IN_MS = 3600000; - public static final int TIME_90_MIN_IN_MS = 5400000; - public static final int TIME_12_HOURS_IN_MS = 43200000; - public static final String PREFS_NAME = "MyPrefsFile"; - public static final float SENSOR_CONVERSION_CONSTANT_VALUE = 160.72f; - public static final float SENSOR_CONVERSION_CONSTANT_VALUE2 = Float.valueOf("5.8E-4").floatValue(); - public static final float SENSOR_CONVERSION_CONSTANT_VALUE3 = Float.valueOf("6.25E-6").floatValue(); - public static final float SENSOR_CONVERSION_CONSTANT_VALUE4 = Float.valueOf("1.5E-6").floatValue(); - public static final int SENSOR_CONVERSION_CONSTANT_VALUE5 = 65536; - - public static final String MONGO_URI = "https://api.mongolab.com/api/1/databases/"; - - public static final int CALIBRATION_SENSOR = 0; - public static final int CALIBRATION_GLUCOMETER = 1; - public static final int CALIBRATION_MANUAL = 2; - - - //Calibration status - public static final int WITHOUT_ANY_CALIBRATION = 0; - public static final int CALIBRATED = 1; - public static final int CALIBRATION_MORE_THAN_12H_OLD = 2; - public static final int LAST_CALIBRATION_FAILED_USING_PREVIOUS = 3; - public static final int CALIBRATED_IN_15MIN = 4; - public static final int CALIBRATING = 5; - public static final int CALIBRATING2 = 6; - - //Calibration status string - public static final String WITHOUT_ANY_CALIBRATION_STR = "Not calibrated"; - public static final String CALIBRATED_STR = "Calibrated"; - public static final String CALIBRATION_MORE_THAN_12H_OLD_STR = "Last Calibration > 12H"; - public static final String LAST_CALIBRATION_FAILED_USING_PREVIOUS_STR = "Using Prev. Calibration"; - public static final String CALIBRATED_IN_15MIN_STR = "Calibrated between 15min. and 20min."; - public static final String CALIBRATING_STR = "Calibrating, wait 15 to 20min."; - public static final String CALIBRATING2_STR = "Calibrating, 2 values received wait 5min. more"; - - //Medtronic commands - public static final byte MEDTRONIC_WAKE_UP = (byte)0x5d; - public static final byte MEDTRONIC_GET_PUMP_MODEL = (byte)0x8d; - public static final byte MEDTRONIC_GET_ALARM_MODE = (byte)0x75; - public static final byte MEDTRONIC_GET_PUMP_STATE = (byte)0x83; - public static final byte MEDTRONIC_GET_TEMPORARY_BASAL = (byte)0x98; - public static final byte MEDTRONIC_READ_PAGE_COMMAND = (byte)0x9a; - public static final byte MEDTRONIC_GET_BATTERY_STATUS = (byte)0x72; - public static final byte MEDTRONIC_GET_REMAINING_INSULIN = (byte)0x73; - public static final byte MEDTRONIC_GET_REMOTE_CONTROL_IDS = (byte)0x76; - public static final byte MEDTRONIC_GET_PARADIGM_LINK_IDS = (byte)0x95; - public static final byte MEDTRONIC_GET_SENSORID = (byte)0xcf; - public static final byte MEDTRONIC_GET_LAST_PAGE = (byte)0xcd; - public static final byte MEDTRONIC_GET_CALIBRATION_FACTOR = (byte)0x9c; - public static final byte MEDTRONIC_ACK = (byte)0x06; - public static final byte MEDTRONIC_INIT = (byte)0xff; - //Device class - public static final byte MEDTRONIC_PUMP = (byte)0xa7; - public static final byte MEDTRONIC_SENSOR1 = (byte)0xaa; - public static final byte MEDTRONIC_SENSOR2 = (byte)0xab; - public static final byte MEDTRONIC_GL = (byte)0xa5; - - //Messages - public static final int MSG_REGISTER_CLIENT = 0; - public static final int MSG_UNREGISTER_CLIENT = 1; - public static final int MSG_MEDTRONIC_CGM_MESSAGE_RECEIVED = 2; - public static final int MSG_MEDTRONIC_CGM_TEST_MESSAGE_REQUEST = 3; - public static final int MSG_MEDTRONIC_CGM_CLEAR_DISPLAY = 4; - public static final int MSG_MEDTRONIC_CGM_NO_PERMISSION = 5; - public static final int MSG_MEDTRONIC_CGM_USB_GRANTED = 6; - public static final int MSG_MEDTRONIC_CGM_REQUEST_PERMISSION = 7; - public static final int MSG_MEDTRONIC_CGM_ERROR_RECEIVED = 8; - public static final int MSG_MEDTRONIC_SEND_MANUAL_CALIB_VALUE = 9; - public static final int MSG_MEDTRONIC_SEND_GET_SENSORCAL_FACTOR = 10; - public static final int MSG_MEDTRONIC_SEND_GET_PUMP_INFO = 11; - public static final int MSG_MEDTRONIC_SEND_INSTANT_CALIB_VALUE = 12; - public static final int MSG_MEDTRONIC_SEND_INSTANT_GLUC_VALUE = 13; - public static final int MSG_MEDTRONIC_CALIBRATION_DONE = 14; - public static final int MSG_MEDTRONIC_GLUCMEASURE_DETECTED = 15; - public static final int MSG_MEDTRONIC_GLUCMEASURE_APPROVED = 16; - public static final int MSG_REFRESH_DB_CONNECTION = 17; - - - public static String getCalibrationStrValue(int val){ - switch(val){ - case CALIBRATED: - return CALIBRATED_STR; - case LAST_CALIBRATION_FAILED_USING_PREVIOUS: - return LAST_CALIBRATION_FAILED_USING_PREVIOUS_STR; - case CALIBRATED_IN_15MIN: - return CALIBRATED_IN_15MIN_STR; - case CALIBRATION_MORE_THAN_12H_OLD: - return CALIBRATION_MORE_THAN_12H_OLD_STR; - case CALIBRATING: - return CALIBRATING_STR; - case CALIBRATING2: - return CALIBRATING2_STR; - default: - return WITHOUT_ANY_CALIBRATION_STR; - } - } - public static String getWidgetCalAppend(int val){ - switch(val){ - case CALIBRATED: - return ""; - case LAST_CALIBRATION_FAILED_USING_PREVIOUS: - return "?!"; - case CALIBRATED_IN_15MIN: - return "!"; - case CALIBRATION_MORE_THAN_12H_OLD: - return "?"; - case CALIBRATING: - return "*"; - case CALIBRATING2: - return "+"; - default: - return "NC"; - } - } } diff --git a/app/src/main/java/info/nightscout/android/medtronic/MedtronicReader.java b/app/src/main/java/info/nightscout/android/medtronic/MedtronicReader.java deleted file mode 100644 index 0e5726a..0000000 --- a/app/src/main/java/info/nightscout/android/medtronic/MedtronicReader.java +++ /dev/null @@ -1,3119 +0,0 @@ -package info.nightscout.android.medtronic; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.ObjectOutputStream; -import java.nio.ByteBuffer; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Calendar; -import java.util.Date; -import java.util.List; -import java.util.Locale; - -import org.slf4j.LoggerFactory; - -import android.content.Context; -import android.content.SharedPreferences; -import android.os.Bundle; -import android.os.Handler; -import android.os.Message; -import android.os.Messenger; -import android.os.RemoteException; -import android.preference.PreferenceManager; -import android.util.Log; - -import ch.qos.logback.classic.Logger; - -import info.nightscout.android.dexcom.USB.HexDump; -import info.nightscout.android.upload.GlucometerRecord; -import info.nightscout.android.upload.MedtronicPumpRecord; -import info.nightscout.android.upload.MedtronicSensorRecord; -import info.nightscout.android.upload.Record; -import com.physicaloid.lib.Physicaloid; - -/** - * Class: MedtronicReader This class manages all read operations over all the - * medtronic devices which are registered in Medtronic's pump. This class also - * holds the shared variables to know when the application is commanding or it - * has finished a request. - * - * @author lmmarguenda - * - */ -public class MedtronicReader { - private Logger log = (Logger) LoggerFactory.getLogger(MedtronicReader.class - .getName()); - private static final String TAG = MedtronicReader.class.getSimpleName(); - public Physicaloid mSerialDevice; - - protected Context context = null; - protected byte[] idPump = null; - protected byte[] idGluc = null; - protected byte[] idSensor = null; - protected byte[] notFinishedRead = null; - - public String bGValue; - public String displayTime; - public String trend; - public MedtronicPumpRecord lastMedtronicPumpRecord = null;// last medtronic - // pump info - // received - public int crcErrorBytesToDiscard = 0; - public boolean isCalibrating = false; - public int calibrationStatus = MedtronicConstants.WITHOUT_ANY_CALIBRATION; - public float calibrationIsigValue = -1f; - public float calibrationFactor = -1f; - public long lastCalibrationDate = 0; - public long lastGlucometerDate = 0; - public long lastGlucometerMessageDate = 0; - public long lastSensorValueDate = 0; - public float lastGlucometerValue = -1f; - public float[] glucoseFilter = { 0.3f, 0.6f, 0.1f }; - public byte[] expectedSensorSortNumberForCalibration = { (byte) 0xff, - (byte) 0xff }; // expected indexes of the next sensor reading for - // correct calibration - public GlucometerRecord lastGlucometerRecord = null;// last glucometer - // record read - public byte expectedSensorSortNumber = (byte) 0xff; // expected index of the - // next sensor reading - public Boolean expectedSensorSortNumberLock = false; // expectedSensorSortNumber - // Lock for - // synchronize - public float previousValue = -1f; // last sensor value read - public MedtronicSensorRecord previousRecord = null; // last sensor record - public Byte lastCommandSend = null; // last command sent from this - // application to the pump. - public Boolean sendingCommand = false;// shared variable, It tells us that - public Object sendingCommandLock = new Object(); - // the receptor is sending a command - // and we have no received the ACK - public Boolean processingCommand = false;// shared variable, It tells us - public Object processingCommandLock = new Object(); - // that our service is launching - // a set of commands, and it has - // not ended yet. - public Boolean waitingCommand = false; // shared variable, It tells us that - public Object waitingCommandLock = new Object(); - // the receptor has sent a message - // but we do not have the answer - // yet. - public CircleList<Record> lastRecordsInMemory = new CircleList<Record>(10);// array - private Object lastRecordsListLock = new Object(); - // to - // store - // last - // Records - public ArrayList<String> knownDevices = null; // list of devices that we - // are going to listen (pump - // included). - public int lastElementsAdded = 0; // last records read from sensor - ArrayList<Messenger> mClients = new ArrayList<Messenger>(); - private byte[] lastGlucometerMessage = null; // last glucometer message - // received - SharedPreferences settings = null; - SharedPreferences prefs = null; - Integer calibrationSelected = MedtronicConstants.CALIBRATION_GLUCOMETER; - Object calibrationSelectedLock = new Object(); - HistoricGetterThread hGetter = null; - int historicPageIndex = -1; - int historicPageShift = 0; - DataLog datalog = new DataLog(); - Handler mHandlerCheckLastRead = null; - Runnable checkLastRead = null; - Handler mHandlerSensorCalibration = null; - Runnable getCalibrationFromSensor = null; - - /** - * Constructor - * - * @param device - * @param context - */ - public MedtronicReader(Physicaloid device, Context context, - ArrayList<Messenger> mClients, HistoricGetterThread hGetter) { - this.settings = context.getSharedPreferences( - MedtronicConstants.PREFS_NAME, 0); - this.context = context; - this.mClients = mClients; - this.hGetter = hGetter; - knownDevices = new ArrayList<String>(); - mSerialDevice = device; - prefs = PreferenceManager.getDefaultSharedPreferences(context); - synchronized (calibrationSelectedLock) { - if (prefs.contains("calibrationType")) { - String type = prefs.getString("calibrationType", "3"); - if ("3".equalsIgnoreCase(type)) - calibrationSelected = MedtronicConstants.CALIBRATION_MANUAL; - else if ("2".equalsIgnoreCase(type)) { - calibrationSelected = MedtronicConstants.CALIBRATION_SENSOR; - } else - calibrationSelected = MedtronicConstants.CALIBRATION_GLUCOMETER; - } - } - if (prefs.contains("medtronic_cgm_id")) { - if (prefs.getString("medtronic_cgm_id", "").length() > 0) { - knownDevices.add(prefs.getString("medtronic_cgm_id", "")); - idPump = HexDump.hexStringToByteArray(prefs.getString( - "medtronic_cgm_id", "")); - } - } - if (prefs.contains("glucometer_cgm_id")) { - if (prefs.getString("glucometer_cgm_id", "").length() > 0) { - knownDevices.add(prefs.getString("glucometer_cgm_id", "")); - idGluc = HexDump.hexStringToByteArray(prefs.getString( - "glucometer_cgm_id", "")); - } - } - if (prefs.contains("sensor_cgm_id")) { - if (prefs.getString("sensor_cgm_id", "").length() > 0) { - String sensorID = HexDump.toHexString(Integer.parseInt(prefs - .getString("sensor_cgm_id", "0"))); - while (sensorID != null && sensorID.length() > 6) { - sensorID = sensorID.substring(1); - } - log.debug("SensorID inserted " - + prefs.getString("sensor_cgm_id", "0") - + " transformed to " + sensorID); - knownDevices.add(sensorID); - idSensor = HexDump.hexStringToByteArray(sensorID); - } - } - String listPrevKnownDevices = ""; - - if (settings.contains("knownDevices")) { - listPrevKnownDevices = settings.getString("knownDevices", ""); - String[] splitted = listPrevKnownDevices.split(","); - for (int i = 0; i < splitted.length; i++) { - // log.debug("splitted["+i+"]= "+splitted[i]); - if (splitted[i] != null - && splitted[i].replaceAll(" ", "").length() > 0) { - if (!knownDevices.contains(splitted[i])) - knownDevices.add(splitted[i]); - } - } - } - storeKnownDevices(); - /*long currentTime = System.currentTimeMillis(); - long diff = currentTime - settings.getLong("lastDestroy", 0); - if (diff > (2 * MedtronicConstants.TIME_12_HOURS_IN_MS)) { - Log.i("Medtronic", "BORRA TODO"); - log.debug("REMOVE ALL PREFERENCES TOO MUCH TIME WITHOUT READING; DATA IS OBSOLETE"); - SharedPreferences.Editor editor = settings.edit(); - editor.remove("lastGlucometerMessage"); - editor.remove("previousValue"); - editor.remove("expectedSensorSortNumber"); - editor.remove("isCalibrating"); - if (settings.contains("calibrationStatus")) - calibrationStatus = settings.getInt("calibrationStatus", - MedtronicConstants.WITHOUT_ANY_CALIBRATION); - if (settings.contains("calibrationFactor")) - calibrationFactor = (float) settings.getFloat( - "calibrationFactor", (float) this.calibrationFactor); - if (settings.contains("lastCalibrationDate")) - lastCalibrationDate = settings - .getLong("lastCalibrationDate", 0); - checkCalibrationOutOfTime(); - editor.remove("lastGlucometerValue"); - editor.remove("lastGlucometerDate"); - editor.remove("expectedSensorSortNumber"); - editor.remove("expectedSensorSortNumberForCalibration0"); - editor.remove("expectedSensorSortNumberForCalibration1"); - editor.remove("lastSensorValueDate"); - editor.remove("last_read"); - editor.commit(); - return; - }*/ - - if (settings.contains("lastSensorValueDate")) - lastSensorValueDate = settings.getLong("lastSensorValueDate", 0); - if (settings.contains("calibrationStatus")) - calibrationStatus = settings.getInt("calibrationStatus", - MedtronicConstants.WITHOUT_ANY_CALIBRATION); - if (settings.contains("isCalibrating")) - isCalibrating = settings.getBoolean("isCalibrating", false); - if (settings.contains("lastGlucometerMessage") - && settings.getString("lastGlucometerMessage", "").length() > 0) - lastGlucometerMessage = HexDump.hexStringToByteArray(settings - .getString("lastGlucometerMessage", "")); - if (settings.contains("calibrationFactor")) - calibrationFactor = (float) settings.getFloat("calibrationFactor", - (float) this.calibrationFactor); - if (settings.contains("lastCalibrationDate")) - lastCalibrationDate = settings.getLong("lastCalibrationDate", 0); - if (settings.contains("previousValue")) - previousValue = (float) settings.getFloat("previousValue", - (float) this.previousValue); - if (settings.contains("expectedSensorSortNumber") - && settings.getString("expectedSensorSortNumber", "").length() > 0) { - expectedSensorSortNumber = HexDump.hexStringToByteArray(settings - .getString("expectedSensorSortNumber", ""))[0]; - - } - if (settings.contains("lastGlucometerValue") - && settings.getFloat("lastGlucometerValue", -1) > 0) { - lastGlucometerValue = settings.getFloat("lastGlucometerValue", -1); - } - if (settings.contains("lastGlucometerDate") - && settings.getLong("lastGlucometerDate", -1) > 0) - lastGlucometerDate = settings.getLong("lastGlucometerDate", -1); - if ((settings.contains("expectedSensorSortNumberForCalibration0") && settings - .getString("expectedSensorSortNumberForCalibration0", "") - .length() > 0) - && settings.contains("expectedSensorSortNumberForCalibration1") - && settings.getString( - "expectedSensorSortNumberForCalibration1", "").length() > 0) { - expectedSensorSortNumberForCalibration[0] = HexDump - .hexStringToByteArray(settings.getString( - "expectedSensorSortNumberForCalibration0", ""))[0]; - expectedSensorSortNumberForCalibration[1] = HexDump - .hexStringToByteArray(settings.getString( - "expectedSensorSortNumberForCalibration1", ""))[0]; - } else { - if (isCalibrating) { - expectedSensorSortNumberForCalibration[0] = (byte) 0x00; - expectedSensorSortNumberForCalibration[1] = (byte) 0x71; - } - } - checkCalibrationOutOfTime(); - if (settings.contains("last_read")) { - String lastRead = settings.getString("lastRead", ""); - if (lastRead.length() > 0) { - byte[] last_read = HexDump.hexStringToByteArray(lastRead); - ArrayList<byte[]> bufferedMessages = parseMessageData( - last_read, last_read.length); - if (bufferedMessages != null && bufferedMessages.size() > 0) - processBufferedMessages(bufferedMessages); - } - } - } - - /** - * This method checks if the message received has its source in one of the - * devices registered. - * - * @param readData - * @return true, if I "know" the source of this message. - */ - private boolean isMessageFromMyDevices(byte[] readData) { - int initByte = firstByteOfDeviceId(readData); - if (initByte < 0 || readData.length < initByte){ - log.error("Error checking initByte and received length, I can't check If is from 'My devices'"); - return false; - } - for (String knownDevice : knownDevices) { - int nBytes = knownDevice.length() / 2; - if (knownDevice.length() % 2 > 0 && knownDevice.length() > 2) { - nBytes++; - } - if (readData.length < (nBytes + initByte)){ - log.error("Error checking received length, I can't check If is from 'My devices'"); - return false; - } - String deviceCode = HexDump.toHexString(readData, initByte, nBytes); - - if (knownDevice.equals(deviceCode)) - return true; - else - log.error("Current Known Device "+knownDevice+" Message Received From "+deviceCode); - } - return false; - } - - /** - * Sends a message glucMessage - * message. - * - * @param valuetosend - * @param clear - * , if true, the display is cleared before printing - * "valuetosend" - */ - private void sendGlucMessageToUI(float valuetosend, boolean calibration, boolean isCalFactorFromPump) { - // log.debug("MedtronicReader Sends to UI "+valuetosend); - if (mClients != null && mClients.size() > 0) { - for (int i = mClients.size() - 1; i >= 0; i--) { - try { - Message mSend = null; - - mSend = Message - .obtain(null, - MedtronicConstants.MSG_MEDTRONIC_GLUCMEASURE_DETECTED); - Bundle b = new Bundle(); - b.putFloat("data", valuetosend); - b.putBoolean("calibrating", calibration); - b.putBoolean("isCalFactorFromPump", isCalFactorFromPump); - mSend.setData(b); - mClients.get(i).send(mSend); - - } catch (RemoteException e) { - // The client is dead. Remove it from the list; we are going - // through the list from back to front so this is safe to do - // inside the loop. - mClients.remove(i); - } - } - } /* - * else { displayMessage(valuetosend); } - */ - } - private void sendMessageToUI(String valuetosend, boolean clear) { - Log.i("medtronicReader", valuetosend); - // log.debug("MedtronicReader Sends to UI "+valuetosend); - if (mClients != null && mClients.size() > 0) { - for (int i = mClients.size() - 1; i >= 0; i--) { - try { - Message mSend = null; - if (clear) { - mSend = Message - .obtain(null, - MedtronicConstants.MSG_MEDTRONIC_CGM_CLEAR_DISPLAY); - mClients.get(i).send(mSend); - continue; - } - mSend = Message - .obtain(null, - MedtronicConstants.MSG_MEDTRONIC_CGM_MESSAGE_RECEIVED); - Bundle b = new Bundle(); - b.putString("data", valuetosend); - mSend.setData(b); - mClients.get(i).send(mSend); - - } catch (RemoteException e) { - // The client is dead. Remove it from the list; we are going - // through the list from back to front so this is safe to do - // inside the loop. - mClients.remove(i); - } - } - } /* - * else { displayMessage(valuetosend); } - */ - } - /** - * - * @param readData - * @return index of the first byte which contains the ID of the device. - */ - private int firstByteOfDeviceId(byte[] readData) { - if (readData.length < 3) - return -1; - switch (readData[2]) { - case MedtronicConstants.MEDTRONIC_PUMP: - case MedtronicConstants.MEDTRONIC_GL: - return 3; - case MedtronicConstants.MEDTRONIC_SENSOR1: - case MedtronicConstants.MEDTRONIC_SENSOR2: - return 4; - default: - return -1; - } - } - - /** - * - * @param readData - * @return index of the first byte after device ID - */ - private int firstByteAfterDeviceId(byte[] readData) { - int initByte = firstByteOfDeviceId(readData); - if (initByte < 0 || readData.length < initByte) - return -1; - for (String knownDevice : knownDevices) { - if (knownDevice == null - || knownDevice.replaceAll(" ", "").length() == 0) - continue; - - int nBytes = knownDevice.length() / 2; - if (knownDevice.length() % 2 > 0 && knownDevice.length() > 2) { - nBytes++; - } - - if (readData.length < (nBytes + initByte)) - return -1; - String deviceCode = HexDump.toHexString(readData, initByte, nBytes); - - if (knownDevice.equals(deviceCode)) - return (nBytes + initByte); - } - return -1; - } - - /** - * This function checks that the first byte of the received message is - * correct. - * - * @param first - * @return true, if the first byte is one of the send/receive values - */ - private boolean checkFirstByte(byte first) { - return (first == (byte) 0x02) || (first == (byte) 0x81) - || (first == (byte) 0x01) || (first == (byte) 0xC1) - || (first == (byte) 0x03) || (first == (byte) 0x13); - } - - /** - * - * @param first - * @return A constant which tell us the kind of answer received. - */ - private int getAnswerType(byte first) { - if (first == (byte) 0x02) - return MedtronicConstants.DATA_ANSWER; - else if ((first == (byte) 0x81) || (first == (byte) 0x01) - || (first == (byte) 0xC1)) - return MedtronicConstants.COMMAND_ANSWER; - else if ((first == (byte) 0x03) || (first == (byte) 0x13)) - return MedtronicConstants.FILTER_COMMAND; - else if (first == (byte) 0x82) - return MedtronicConstants.CRC_ERROR; - else - return MedtronicConstants.UNKNOWN_ANSWER; - } - - /** - * This method checks if the calibration has got too old (over 12 hours) - */ - private void checkCalibrationOutOfTime() { - if ((calibrationFactor > 0) - && (calibrationStatus != MedtronicConstants.WITHOUT_ANY_CALIBRATION) - && calibrationStatus != MedtronicConstants.LAST_CALIBRATION_FAILED_USING_PREVIOUS - && calibrationStatus != MedtronicConstants.CALIBRATION_MORE_THAN_12H_OLD) { - if (lastCalibrationDate > 0 - && (System.currentTimeMillis() - lastCalibrationDate) > MedtronicConstants.TIME_12_HOURS_IN_MS) { - calibrationStatus = MedtronicConstants.CALIBRATION_MORE_THAN_12H_OLD; - SharedPreferences.Editor editor = settings.edit(); - editor.putInt("calibrationStatus", calibrationStatus); - editor.commit(); - } - } - - } - - /** - * This method reads from the serial device, and process the answer - * - * @param context - * @return String, for debug or notification purposes - */ - public ArrayList<byte[]> readFromReceiver(Context context, int size) { - ArrayList<byte[]> bufferedMessages = null; - byte[] readFromDevice = new byte[1024]; - int read = 0; - if (size >= 0) { - log.debug("readFromReceiver!! a leer " + size + " bytes!!"); - try { - read = mSerialDevice.read(readFromDevice); - } catch (Exception e) { - Log.e(TAG, "Unable to read from serial device", e); - log.error("Unable to read from serial device", e); - return null; - } - } - if (read > 0) { - Log.d("medtronic", "READ " + read); - - log.debug("Stream Received; bytes read: " + read);// +" "+HexDump.toHexString(Arrays.copyOfRange(readFromDevice,0,read))); - } else - log.debug("NOTHING TO READ"); - if (read > 0) { - SharedPreferences.Editor editor = settings.edit(); - editor.putLong("lastDestroy", System.currentTimeMillis()); - editor.commit(); - try { - - bufferedMessages = parseMessageData( - Arrays.copyOfRange(readFromDevice, 0, read), read); - checkCalibrationOutOfTime(); - } catch (Exception e) { - StringBuffer sb1 = new StringBuffer(""); - sb1.append("EXCEPTION!!!!!! " + e.getMessage() + " " - + e.getCause()); - for (StackTraceElement st : e.getStackTrace()) { - sb1.append(st.toString()); - } - sendMessageToUI(sb1.toString(), false); - bufferedMessages = new ArrayList<byte[]>(); - } - } - return bufferedMessages; - } - - /** - * This method process all the parsed messages got using "readFromReceiver" - * function - * - * @param bufferedMessages - * , List of parsed messages. - */ - public String processBufferedMessages(ArrayList<byte[]> bufferedMessages) { - StringBuffer sResponse = new StringBuffer(""); - int calibrationSelectedAux = 0; - log.debug("processBufferedMessages"); - synchronized (calibrationSelectedLock) { - calibrationSelectedAux = calibrationSelected; - } - try { - for (byte[] readData : bufferedMessages) { - if (checkFirstByte(readData[0])) { - switch (getAnswerType(readData[0])) { - case MedtronicConstants.DATA_ANSWER: - log.debug("IS DATA ANSWER"); - if (isMessageFromMyDevices(readData)) { - log.debug("IS FROM MY DEVICES"); - switch (readData[2]) { - case MedtronicConstants.MEDTRONIC_PUMP: - log.debug("IS A PUMP MESSAGE"); - sResponse.append( - processPumpDataMessage(readData, - calibrationSelectedAux)) - .append("\n"); - if (lastMedtronicPumpRecord == null) { - lastMedtronicPumpRecord = new MedtronicPumpRecord(); - calculateDate(lastMedtronicPumpRecord, - new Date(), 0); - lastMedtronicPumpRecord.deviceId = prefs - .getString("medtronic_cgm_id", ""); - } - lastMedtronicPumpRecord.isWarmingUp = prefs - .getBoolean("isWarmingUp", false); - break; - case MedtronicConstants.MEDTRONIC_GL: { - //if (calibrationSelectedAux == MedtronicConstants.CALIBRATION_GLUCOMETER) { - log.debug("GLUCOMETER DATA RECEIVED"); - if (lastGlucometerMessage == null - || lastGlucometerMessage.length == 0) { - lastGlucometerMessage = Arrays - .copyOfRange(readData, 0, - readData.length); - SharedPreferences.Editor editor = settings - .edit(); - editor.putString( - "lastGlucometerMessage", - HexDump.toHexString(lastGlucometerMessage)); - editor.commit(); - } else { - boolean isEqual = Arrays - .equals(lastGlucometerMessage, - readData); - if (isEqual - && (System.currentTimeMillis() - - lastGlucometerDate < MedtronicConstants.TIME_15_MIN_IN_MS)) { - continue; - } - lastGlucometerDate = System - .currentTimeMillis(); - lastGlucometerMessage = Arrays - .copyOfRange(readData, 0, - readData.length); - } - sResponse.append( - processGlucometerDataMessage( - readData, false)).append( - "\n"); // Cambiado a false - if (lastGlucometerValue > 0) { - isCalibrating = calibrationSelectedAux == MedtronicConstants.CALIBRATION_GLUCOMETER; - if (previousRecord == null) { - MedtronicSensorRecord auxRecord = new MedtronicSensorRecord(); - - auxRecord.isCalibrating = calibrationSelectedAux == MedtronicConstants.CALIBRATION_GLUCOMETER; - log.debug("1"); - writeLocalCSV(auxRecord, context); - } else { - previousRecord.isCalibrating = calibrationSelectedAux == MedtronicConstants.CALIBRATION_GLUCOMETER; - log.debug("2"); - writeLocalCSV(previousRecord, - context); - } - SharedPreferences.Editor editor = settings - .edit(); - - editor.putBoolean("isCalibrating", calibrationSelectedAux == MedtronicConstants.CALIBRATION_GLUCOMETER); - if (calibrationSelectedAux == MedtronicConstants.CALIBRATION_GLUCOMETER) - sendMessageToUI("isCalibrating", false); - sendMessageToUI("glucometer data received", false); - - editor.commit(); - } - /*} else if (calibrationSelectedAux == MedtronicConstants.CALIBRATION_SENSOR) { - if (lastGlucometerMessage == null - || lastGlucometerMessage.length == 0) { - lastGlucometerMessage = Arrays - .copyOfRange(readData, 0, - readData.length); - lastGlucometerMessageDate = System - .currentTimeMillis(); - SharedPreferences.Editor editor = settings - .edit(); - editor.putString( - "lastGlucometerMessage", - HexDump.toHexString(lastGlucometerMessage)); - - editor.commit(); - } else { - boolean isEqual = Arrays - .equals(lastGlucometerMessage, - readData); - if (isEqual - && (System.currentTimeMillis() - - lastGlucometerMessageDate < MedtronicConstants.TIME_15_MIN_IN_MS)) { - continue; - } - lastGlucometerMessageDate = System - .currentTimeMillis(); - lastGlucometerMessage = Arrays - .copyOfRange(readData, 0, - readData.length); - } - sResponse - .append("Glucomenter Deteted!! \n") - .append(processGlucometerDataMessage( - readData, false)); - } else { - isCalibrating = false; - if (lastGlucometerMessage == null - || lastGlucometerMessage.length == 0) { - lastGlucometerMessage = Arrays - .copyOfRange(readData, 0, - readData.length); - lastGlucometerMessageDate = System - .currentTimeMillis(); - SharedPreferences.Editor editor = settings - .edit(); - editor.putString( - "lastGlucometerMessage", - HexDump.toHexString(lastGlucometerMessage)); - - editor.commit(); - } else { - boolean isEqual = Arrays - .equals(lastGlucometerMessage, - readData); - if (isEqual - && (System.currentTimeMillis() - - lastGlucometerMessageDate < MedtronicConstants.TIME_15_MIN_IN_MS)) { - continue; - } - lastGlucometerMessageDate = System - .currentTimeMillis(); - lastGlucometerMessage = Arrays - .copyOfRange(readData, 0, - readData.length); - } - sResponse - .append("Glucomenter Deteted!! \n") - .append(processGlucometerDataMessage( - readData, false)); - }*/ - break; - } - case MedtronicConstants.MEDTRONIC_SENSOR1: { - if (prefs.getString("glucSrcTypes", "1") - .equals("2")) { - log.debug("Sensor value received, but value is took only by pump logs"); - break; - } - log.debug("WARMING_UP"); - SharedPreferences.Editor editor = settings - .edit(); - editor.remove("lastGlucometerMessage"); - editor.remove("previousValue"); - editor.remove("expectedSensorSortNumber"); - editor.remove("isCalibrating"); - calibrationStatus = MedtronicConstants.WITHOUT_ANY_CALIBRATION; - editor.putInt( - "calibrationStatus", - MedtronicConstants.WITHOUT_ANY_CALIBRATION); - editor.remove("calibrationFactor"); - log.debug("remove lastCalibrationDate"); - editor.remove("lastCalibrationDate"); - editor.remove("lastGlucometerValue"); - editor.remove("lastGlucometerDate"); - editor.remove("expectedSensorSortNumber"); - editor.remove("expectedSensorSortNumberForCalibration0"); - editor.remove("expectedSensorSortNumberForCalibration1"); - editor.remove("isCheckedWUP"); - if (!prefs.getBoolean("isWarmingUp", false)) { - if (lastMedtronicPumpRecord == null) { - lastMedtronicPumpRecord = new MedtronicPumpRecord(); - calculateDate(lastMedtronicPumpRecord, - new Date(), 0); - lastMedtronicPumpRecord.deviceId = prefs - .getString("medtronic_cgm_id", - ""); - } - - editor.putBoolean("isWarmingUp", true); - - lastMedtronicPumpRecord.isWarmingUp = true; - } - - if (previousRecord == null) { - MedtronicSensorRecord auxRecord = new MedtronicSensorRecord(); - calculateDate(auxRecord, new Date(), 0); - log.debug("3"); - writeLocalCSV(auxRecord, context); - } else { - calculateDate(previousRecord, new Date(), 0); - log.debug("4"); - writeLocalCSV(previousRecord, context); - } - sendMessageToUI("sensor data wUp.", false); - editor.commit(); - break; - } - case MedtronicConstants.MEDTRONIC_SENSOR2: - - if (lastMedtronicPumpRecord != null) - lastMedtronicPumpRecord.isWarmingUp = false; - if (prefs.getString("glucSrcTypes", "1") - .equals("2")) { - if (prefs.getBoolean("isWarmingUp", false)) { - if (lastMedtronicPumpRecord == null) { - lastMedtronicPumpRecord = new MedtronicPumpRecord(); - calculateDate( - lastMedtronicPumpRecord, - new Date(), 0); - lastMedtronicPumpRecord.deviceId = prefs - .getString( - "medtronic_cgm_id", - ""); - } - lastMedtronicPumpRecord.isWarmingUp = false; - SharedPreferences.Editor editor1 = prefs - .edit(); - editor1.putBoolean("isWarmingUp", false); - editor1.commit(); - } - log.debug("Sensor value received, but value is took only by pump logs"); - break; - } - Log.i("MEdtronic", "process sensor2"); - log.debug("SENSOR DATA RECEIVED"); - if (prefs.getBoolean("isWarmingUp", false)) { - if (lastMedtronicPumpRecord == null) { - lastMedtronicPumpRecord = new MedtronicPumpRecord(); - calculateDate(lastMedtronicPumpRecord, - new Date(), 0); - lastMedtronicPumpRecord.deviceId = prefs - .getString("medtronic_cgm_id", - ""); - } - lastMedtronicPumpRecord.isWarmingUp = false; - SharedPreferences.Editor editor = prefs - .edit(); - editor.remove("isWarmingUp"); - editor.commit(); - } - boolean calculateCalibration = false; - if (isCalibrating) { - calculateCalibration = true; - } - sResponse.append( - processSensorDataMessage(readData)) - .append("\n"); - if (calculateCalibration && !isCalibrating) { - SharedPreferences.Editor editor = settings - .edit(); - editor.putBoolean("isCalibrating", false); - editor.commit(); - } - sendMessageToUI("sensor data value received", - false); - break; - default: - Log.i("MEdtronic", "No Match"); - log.debug("I can't understand this message"); - sResponse - .append("I can't process this message, no device match.") - .append("\n"); - break; - } - } else { - Log.i("Medtronic", - "I dont have to listen to this. This message comes from another source."); - log.debug("I don't have to listen to this message. This message comes from another source."); - sResponse - .append("I don't have to listen to this. This message comes from another source.") - .append("\n"); - } - break; - case MedtronicConstants.COMMAND_ANSWER: - log.debug("ACK Received"); - synchronized (sendingCommandLock) { - sendingCommand = false; - } - break; - case MedtronicConstants.FILTER_COMMAND: - if (readData[0] == (byte) 0x13) - sResponse.append("FILTER DEACTIVATED").append("\n"); - else - sResponse.append("FILTER ACTIVATED").append("\n"); - break; - default: { - log.debug("I don't understand this message " - + HexDump.toHexString(readData)); - sResponse.append( - "I don't understand the received message ") - .append("\n"); - } - } - } else { - sResponse.append("CRC Error ").append("\n"); - log.debug("CRC ERROR!!! " + HexDump.dumpHexString(readData)); - } - } - } catch (Exception ex2) { - StringBuffer sb1 = new StringBuffer(""); - sb1.append("EXCEPTION!!!!!! " + ex2.getMessage() + " " - + ex2.getCause()); - for (StackTraceElement st : ex2.getStackTrace()) { - sb1.append(st.toString()); - } - sendMessageToUI(sb1.toString(), false); - } - SharedPreferences.Editor editor = settings.edit(); - editor.remove("last_read"); - editor.commit(); - return sResponse.toString(); - } - - /** - * This function parses the raw bytes to correct messages or discards the - * wrong bytes. - * - * @param readData - * , array of bytes read - * @param read - * , length of bytes read - * @return ArrayList of parsed messages. - */ - private ArrayList<byte[]> parseMessageData(byte[] readData, int read) { - byte[] readBuffer = null; - log.debug("PARSE MESSAGE"); - ArrayList<byte[]> messageList = new ArrayList<byte[]>(); - if (notFinishedRead == null || notFinishedRead.length <= 0) { - readBuffer = Arrays.copyOf(readData, read); - } else { - readBuffer = Arrays.copyOf(notFinishedRead, notFinishedRead.length - + read); - for (int i = 0; i < read; i++) { - readBuffer[notFinishedRead.length + i] = readData[i]; - } - notFinishedRead = null; - } - SharedPreferences.Editor editor = settings.edit(); - editor.putString("last_read", HexDump.toHexString(Arrays.copyOfRange( - readBuffer, 0, readBuffer.length))); - editor.commit(); - int i = 0; - if (crcErrorBytesToDiscard > 0) - i = crcErrorBytesToDiscard; - crcErrorBytesToDiscard = 0; - while (i < readBuffer.length) { - int answer = getAnswerType(readBuffer[i]); - if (answer == MedtronicConstants.COMMAND_ANSWER) { - log.debug("COMMAND"); - if (readBuffer.length >= i + 3) - messageList.add(Arrays.copyOfRange(readBuffer, i, i + 3)); - else { - notFinishedRead = Arrays.copyOfRange(readBuffer, i, - readBuffer.length); - return messageList; - } - i += 3; - } else if (answer == MedtronicConstants.FILTER_COMMAND) { - log.debug("FILTERCOMMAND"); - messageList.add(Arrays.copyOfRange(readBuffer, i, i + 1)); - i++; - } else if (answer == MedtronicConstants.CRC_ERROR) { - log.debug("CRC ERROR"); - if (hGetter != null && hGetter.isWaitingNextLine) { - if (hGetter.timeout >= 2) { - hGetter.timeout = 0; - log.debug("too much retries"); - sendMessageToUI( - "historic log read aborted! too much crc errors, waiting to retry.", - false); - } else { - sendMessageToUI( - "CRC error reading historic log line, reinitializating read...", - false); - hGetter.timeout++; - hGetter.commandList = Arrays.copyOf( - hGetter.commandList, - hGetter.commandList.length + 1); - hGetter.commandList[hGetter.commandList.length - 1] = MedtronicConstants.MEDTRONIC_READ_PAGE_COMMAND; - hGetter.firstReadPage = true; - hGetter.isWaitingNextLine = true; - hGetter.withoutConfirmation = 0; - hGetter.currentLine = -1; - hGetter.historicPage.clear(); - synchronized (waitingCommandLock) { - waitingCommand = false; - lastCommandSend = null; - } - } - } - if (readBuffer.length <= i + 1) { - notFinishedRead = Arrays.copyOfRange(readBuffer, i, - readBuffer.length); - return messageList; - } - int length = HexDump.unsignedByte(readBuffer[i + 1]); - if (length <= 0) { - i++; - continue; - } - - if (readBuffer.length >= i + length + 2) { - i = i + length + 2; - } else { - crcErrorBytesToDiscard = (i + length + 2) - - readBuffer.length; - return messageList; - } - } else if (answer == MedtronicConstants.DATA_ANSWER) { - log.debug("DATA_ANSWER"); - if (readBuffer.length <= i + 1) { - notFinishedRead = Arrays.copyOfRange(readBuffer, i, - readBuffer.length); - return messageList; - } - int length = HexDump.unsignedByte(readBuffer[i + 1]); - if (length <= 0) { - i++; - continue; - } - if (readBuffer.length >= i + length + 2) { - messageList.add(Arrays.copyOfRange(readBuffer, i, i - + length + 2)); - i = i + length + 2;// I have to add 2 bytes CTRL byte and - // SIZE byte - } else { - notFinishedRead = Arrays.copyOfRange(readBuffer, i, - readBuffer.length); - return messageList; - } - } else { - i++; - } - } - return messageList; - } - - /** - * This method process the pump answers - * - * @param readData - * @param calibrationSelected - * @return String, for debug or notification purposes - */ - public String processPumpDataMessage(byte[] readData, - int calibrationSelected) { - int commandByte = firstByteAfterDeviceId(readData); - String sResult = "I do nothing"; - if (commandByte < 0) - return "Error, I can not identify the command byte"; - if (lastCommandSend == null) - return "lastCommand == null"; - switch (readData[commandByte]) { - case MedtronicConstants.MEDTRONIC_GET_LAST_PAGE: { - if (lastCommandSend != null) { - synchronized (waitingCommandLock) { - waitingCommand = false; - lastCommandSend = null; - } - byte[] modelArray = Arrays.copyOfRange(readData, - commandByte + 2, (commandByte + 6)); - historicPageIndex = HexDump.byteArrayToInt(modelArray); - hGetter.historicPageIndex = historicPageIndex; - hGetter.lastHistoricPage = modelArray; - String sModel = new String(HexDump.toHexString(modelArray)); - sResult = "Command " + commandByte + " Read Data " - + HexDump.toHexString(readData) - + " Pump last historic page......: " + sModel; - } - log.debug(sResult); - return sResult; - } - case MedtronicConstants.MEDTRONIC_READ_PAGE_COMMAND: { - log.debug("READ_PAGE"); - - if (lastCommandSend != null) { - try { - log.debug("lcommand send != null"); - if (!hGetter.firstReadPage) { - hGetter.isWaitingNextLine = false; - int currentLineAux = HexDump - .unsignedByte(readData[commandByte + 1]); - log.debug("!first page "); - if (!(currentLineAux == HexDump - .unsignedByte((byte) 0x90) - || (currentLineAux == hGetter.currentLine + 1) || hGetter.currentLine < 1 - && currentLineAux == 1)) { - log.debug("Error"); - hGetter.commandList = Arrays.copyOf( - hGetter.commandList, - hGetter.commandList.length + 1); - hGetter.commandList[hGetter.commandList.length - 1] = MedtronicConstants.MEDTRONIC_READ_PAGE_COMMAND; - hGetter.wThread.isRequest = true; - hGetter.firstReadPage = false; - hGetter.withoutConfirmation = 0; - hGetter.isWaitingNextLine = true; - hGetter.currentLine = -1; - synchronized (waitingCommandLock) { - waitingCommand = false; - lastCommandSend = null; - } - hGetter.historicPage.clear(); - return "Error currentLine is " - + hGetter.currentLine + " next line is " - + currentLineAux - + " is not the order expected"; - } - hGetter.currentLine = currentLineAux; - byte[] modelArray = Arrays.copyOfRange(readData, - commandByte + 2, (commandByte + 2 + (4 * 16))); - hGetter.historicPage.add(modelArray); - if (hGetter.currentLine != HexDump - .unsignedByte((byte) 0x90)) { - log.debug("is correct line"); - hGetter.commandList = Arrays.copyOf( - hGetter.commandList, - hGetter.commandList.length + 1); - hGetter.commandList[hGetter.commandList.length - 1] = MedtronicConstants.MEDTRONIC_ACK; - hGetter.withoutConfirmation = 0; - hGetter.wThread.isRequest = true; - hGetter.wThread.postCommandBytes = null; - // String sModel = new - // String(HexDump.toHexString(modelArray)); - sResult = "Pump last historic page (" - + hGetter.currentLine + ")......: Ok.";// + - // sModel; - hGetter.isWaitingNextLine = true; - } else { - log.debug("All lines read."); - processHistoricPage(); - } - } - } finally { - synchronized (waitingCommandLock) { - waitingCommand = false; - lastCommandSend = null; - } - } - } - - log.debug(sResult); - return sResult; - } - case MedtronicConstants.MEDTRONIC_GET_PUMP_MODEL: - log.debug("Pump Model Received"); - sendMessageToUI("Pump Model Received...", false); - if (lastMedtronicPumpRecord == null) { - lastMedtronicPumpRecord = new MedtronicPumpRecord(); - calculateDate(lastMedtronicPumpRecord, new Date(), 0); - lastMedtronicPumpRecord.deviceId = prefs.getString( - "medtronic_cgm_id", ""); - } - if (lastCommandSend != null) { - synchronized (waitingCommandLock) { - waitingCommand = false; - lastCommandSend = null; - } - byte[] modelArray = Arrays.copyOfRange(readData, - commandByte + 2, - (commandByte + 2 + (readData[commandByte + 1]))); - String sModel = new String(modelArray); - sResult = "Pump model......: " + sModel; - lastMedtronicPumpRecord.model = sModel; - } - return sResult; - case MedtronicConstants.MEDTRONIC_GET_ALARM_MODE: - log.debug("Pump Alarm Mode Received"); - if (lastMedtronicPumpRecord == null) { - lastMedtronicPumpRecord = new MedtronicPumpRecord(); - calculateDate(lastMedtronicPumpRecord, new Date(), 0); - lastMedtronicPumpRecord.deviceId = prefs.getString( - "medtronic_cgm_id", ""); - } - if (lastCommandSend != null) { - synchronized (waitingCommandLock) { - waitingCommand = false; - lastCommandSend = null; - } - int status = readData[commandByte + 2]; - if (status == 0) - sResult = "Ok"; - else - sResult = "Unknown (by now)"; - lastMedtronicPumpRecord.alarm = sResult; - } - return sResult; - case MedtronicConstants.MEDTRONIC_GET_PUMP_STATE: - log.debug("Pump Status Received"); - sendMessageToUI("Pump Status Received...", false); - if (lastMedtronicPumpRecord == null) { - lastMedtronicPumpRecord = new MedtronicPumpRecord(); - calculateDate(lastMedtronicPumpRecord, new Date(), 0); - lastMedtronicPumpRecord.deviceId = prefs.getString( - "medtronic_cgm_id", ""); - } - if (lastCommandSend != null) { - synchronized (waitingCommandLock) { - waitingCommand = false; - lastCommandSend = null; - } - sResult = "Pump state...........: " - + HexDump.toHexString(readData[commandByte + 2]); - lastMedtronicPumpRecord.status = HexDump - .toHexString(readData[commandByte + 2]); - } - - return sResult; - case MedtronicConstants.MEDTRONIC_GET_TEMPORARY_BASAL: - log.debug("Pump Temporary Basal Received"); - if (lastMedtronicPumpRecord == null) { - lastMedtronicPumpRecord = new MedtronicPumpRecord(); - calculateDate(lastMedtronicPumpRecord, new Date(), 0); - lastMedtronicPumpRecord.deviceId = prefs.getString( - "medtronic_cgm_id", ""); - } - if (lastCommandSend != null) { - synchronized (waitingCommandLock) { - waitingCommand = false; - lastCommandSend = null; - } - byte[] tempBasalArray = Arrays.copyOfRange(readData, - commandByte + 2, - (commandByte + 2 + (readData[commandByte + 2]))); - String sTempBasalArray = HexDump.toHexString(tempBasalArray); - - sResult = "Temporary basal......: " + sTempBasalArray; - lastMedtronicPumpRecord.status = sTempBasalArray; - } - return sResult; - case MedtronicConstants.MEDTRONIC_GET_BATTERY_STATUS: - log.debug("Pump Battery Status Received"); - sendMessageToUI("Pump Battery Status Received...", false); - if (lastMedtronicPumpRecord == null) { - lastMedtronicPumpRecord = new MedtronicPumpRecord(); - calculateDate(lastMedtronicPumpRecord, new Date(), 0); - lastMedtronicPumpRecord.deviceId = prefs.getString( - "medtronic_cgm_id", ""); - } - if (lastCommandSend != null) { - synchronized (waitingCommandLock) { - waitingCommand = false; - lastCommandSend = null; - } - int status = readData[commandByte + 3]; - float voltage = (((float) HexDump - .unsignedByte(readData[commandByte + 3])) * 256f + (float) HexDump - .unsignedByte(readData[commandByte + 4])) / 100; - if (status == 0) { - sResult = "Battery status.......: Normal\n"; - lastMedtronicPumpRecord.batteryStatus = "Normal"; - } else { - sResult = "Battery status.......: Low\n"; - lastMedtronicPumpRecord.batteryStatus = "Low"; - } - - sResult += "Battery voltage......: " + voltage + " Volts"; - lastMedtronicPumpRecord.batteryVoltage = "" + voltage; - } - return sResult; - case MedtronicConstants.MEDTRONIC_GET_REMAINING_INSULIN: - log.debug("Pump Remaining Insulin Received"); - sendMessageToUI("Pump Remaining Insulin Received...", false); - if (lastMedtronicPumpRecord == null) { - lastMedtronicPumpRecord = new MedtronicPumpRecord(); - calculateDate(lastMedtronicPumpRecord, new Date(), 0); - lastMedtronicPumpRecord.deviceId = prefs.getString( - "medtronic_cgm_id", ""); - } - if (lastCommandSend != null) { - synchronized (waitingCommandLock) { - waitingCommand = false; - lastCommandSend = null; - } - float insulinLeft = (HexDump - .unsignedByte(readData[commandByte + 4]) * 256f + (float) HexDump - .unsignedByte(readData[commandByte + 5])) / 40f; - sResult = "Remaining insulin....: " + insulinLeft + " Units"; - lastMedtronicPumpRecord.insulinLeft = insulinLeft; - } - return sResult; - case MedtronicConstants.MEDTRONIC_GET_REMOTE_CONTROL_IDS: - log.debug("Pump Remote Control Ids Received"); - sendMessageToUI("Pump Remote Control Ids Received...", false); - if (lastCommandSend != null) { - synchronized (waitingCommandLock) { - waitingCommand = false; - lastCommandSend = null; - } - - byte[] remoteControlID1 = Arrays.copyOfRange(readData, - commandByte + 2, commandByte + 8); - String sRemoteControlID1 = new String(remoteControlID1); - if (HexDump.isHexaNumber(sRemoteControlID1)) { - if (!knownDevices.contains(sRemoteControlID1)) - knownDevices.add(sRemoteControlID1); - } - - byte[] remoteControlID2 = Arrays.copyOfRange(readData, - commandByte + 8, commandByte + 14); - String sRemoteControlID2 = new String(remoteControlID2); - if (HexDump.isHexaNumber(sRemoteControlID2)) { - if (!knownDevices.contains(sRemoteControlID2)) - knownDevices.add(sRemoteControlID2); - } - - byte[] remoteControlID3 = Arrays.copyOfRange(readData, - commandByte + 14, commandByte + 20); - String sRemoteControlID3 = new String(remoteControlID3); - if (HexDump.isHexaNumber(sRemoteControlID3)) { - if (!knownDevices.contains(sRemoteControlID3)) - knownDevices.add(sRemoteControlID3); - } - storeKnownDevices(); - sResult = "Remote Control IDs...: " + sRemoteControlID1 + " " - + sRemoteControlID2 + " " + sRemoteControlID3; - - } - return sResult; - case MedtronicConstants.MEDTRONIC_GET_PARADIGM_LINK_IDS: - log.debug("Pump Paradigm Link Ids Received"); - sendMessageToUI("Pump Paradigm Link Ids Received...", false); - if (lastCommandSend != null) { - synchronized (waitingCommandLock) { - waitingCommand = false; - lastCommandSend = null; - } - - byte[] glucID1 = Arrays.copyOfRange(readData, commandByte + 2, - commandByte + 8); - String sGlucID1 = new String(glucID1); - if (HexDump.isHexaNumber(sGlucID1)) { - if (!knownDevices.contains(sGlucID1)) - knownDevices.add(sGlucID1); - } - - byte[] glucID2 = Arrays.copyOfRange(readData, commandByte + 8, - commandByte + 14); - String sGlucID2 = new String(glucID2); - if (HexDump.isHexaNumber(sGlucID2)) { - if (!knownDevices.contains(sGlucID2)) - knownDevices.add(sGlucID2); - } - - byte[] glucID3 = Arrays.copyOfRange(readData, commandByte + 14, - commandByte + 20); - String sGlucID3 = new String(glucID3); - if (HexDump.isHexaNumber(sGlucID3)) { - if (!knownDevices.contains(sGlucID3)) - knownDevices.add(sGlucID3); - } - storeKnownDevices(); - sResult = "Paradigm Link IDs....: " + sGlucID1 + " " - + sGlucID2 + " " + sGlucID3; - } - return sResult; - case MedtronicConstants.MEDTRONIC_GET_SENSORID: - log.debug("Pump Sensor Id Received"); - sendMessageToUI("Pump Sensor Id Received...", false); - if (lastCommandSend != null) { - synchronized (waitingCommandLock) { - waitingCommand = false; - lastCommandSend = null; - } - if (readData.length >= HexDump.unsignedByte(readData[1]) - && HexDump.unsignedByte(readData[1]) > 0) { - byte[] sensorId = Arrays.copyOfRange(readData, - commandByte + 58, commandByte + 61); - String sSensorId = HexDump.toHexString(sensorId); - sResult = "Sensor ID...: " + sSensorId; - if (!knownDevices.contains(sSensorId)) - knownDevices.add(sSensorId); - storeKnownDevices(); - } else - sResult = readData.length + " Not enough length"; - } - return sResult; - case MedtronicConstants.MEDTRONIC_GET_CALIBRATION_FACTOR: - log.debug("Pump Calibration Factor Received"); - sendMessageToUI("Pump Cal. Factor Received...", false); - if (lastCommandSend != null) { - synchronized (waitingCommandLock) { - waitingCommand = false; - lastCommandSend = null; - } - float factor = ((float) HexDump - .unsignedByte(readData[commandByte + 2]) * 256f + (float) HexDump - .unsignedByte(readData[commandByte + 3])); - if (calibrationSelected == MedtronicConstants.CALIBRATION_SENSOR) { - if (factor > 0) { - calibrationStatus = MedtronicConstants.CALIBRATED; - calibrationFactor = factor / 1126; - } else { - if (calibrationStatus != MedtronicConstants.WITHOUT_ANY_CALIBRATION) { - calibrationStatus = MedtronicConstants.LAST_CALIBRATION_FAILED_USING_PREVIOUS; - } - } - SharedPreferences.Editor editor = settings.edit(); - editor.putFloat("calibrationFactor", - (float) calibrationFactor); - editor.putInt("calibrationStatus", calibrationStatus); - editor.commit(); - if (previousRecord == null) { - MedtronicSensorRecord auxRecord = new MedtronicSensorRecord(); - auxRecord.calibrationStatus = calibrationStatus; - auxRecord.calibrationFactor = calibrationFactor; - log.debug("5"); - writeLocalCSV(auxRecord, context); - } else { - previousRecord.calibrationStatus = calibrationStatus; - previousRecord.calibrationFactor = calibrationFactor; - log.debug("6"); - writeLocalCSV(previousRecord, context); - } - if (lastMedtronicPumpRecord == null) { - lastMedtronicPumpRecord = new MedtronicPumpRecord(); - calculateDate(lastMedtronicPumpRecord, new Date(), 0); - lastMedtronicPumpRecord.deviceId = prefs.getString( - "medtronic_cgm_id", ""); - } - // sendMessageToUI("Is In RANGE CALIBRATION SUCCESS "+currentMeasure+ - // " Factor "+calibrationFactor, false); - - } - sResult = "Calibration Factor...: " + factor; - } - return sResult; - case MedtronicConstants.MEDTRONIC_ACK: - log.debug("Pump Ack Received"); - if (lastCommandSend != null) { - synchronized (sendingCommandLock) { - sendingCommand = false; - } - synchronized (waitingCommandLock) { - waitingCommand = false; - lastCommandSend = null; - } - } - return "ACK RECEIVED! "; - default: - log.error("Undecoded Command"); - return "I do not understand this command " - + HexDump.toHexString(readData[commandByte]); - } - } - - /** - * method to check the Medtronic log page received. - */ - private void processHistoricPage() { - ArrayList<Byte> page = new ArrayList<Byte>(); - ArrayList<Byte> crcPage = new ArrayList<Byte>(); - int substract = 3; - for (int i = 0; i < hGetter.historicPage.size(); i++) { - byte[] hPage = hGetter.historicPage.get(i); - for (int j = 0; j < hPage.length; j++) { - crcPage.add(hPage[j]); - } - } - byte crc2 = crcPage.get(crcPage.size() - 1);// remove crc - crcPage.remove(crcPage.size() - 1);// remove crc - byte crc1 = crcPage.get(crcPage.size() - 1);// remove crc - crcPage.remove(crcPage.size() - 1);// remove crc - // CALCULA EL CRC - byte[] crcReceived = { crc1, crc2 }; - short sCrcReceived = HexDump.byteArrayToShort(crcReceived); - Byte[] finalCrcPage = crcPage.toArray(new Byte[crcPage.size()]); - // crc16Init(); - short sCrcCalculated = (short) crc16(finalCrcPage); - if (sCrcCalculated != sCrcReceived) { - log.debug("Error page crc --> crcReceived " + sCrcReceived - + " crcCalculated " + sCrcCalculated); - if (hGetter.timeout >= 2) { - hGetter.timeout = 0; - log.debug("too much retries"); - sendMessageToUI( - "historic log read aborted! too much crc errors, waiting to retry", - false); - return; - } - sendMessageToUI( - "Crc error in page read, reinitializing page read...", - false); - hGetter.timeout++; - hGetter.commandList = Arrays.copyOf(hGetter.commandList, - hGetter.commandList.length + 1); - hGetter.commandList[hGetter.commandList.length - 1] = MedtronicConstants.MEDTRONIC_READ_PAGE_COMMAND; - hGetter.wThread.isRequest = true; - hGetter.firstReadPage = false; - hGetter.withoutConfirmation = 0; - /* - * byte[] lastHistoricPage = HexDump.toByteArray(historicPageIndex - - * historicPageShift); hGetter.wThread.postCommandBytes = new - * byte[64]; Arrays.fill(hGetter.wThread.postCommandBytes, - * (byte)0x00); hGetter.wThread.postCommandBytes[0] = 0x04; - * hGetter.wThread.postCommandBytes[1] = lastHistoricPage[0]; - * hGetter.wThread.postCommandBytes[2] = lastHistoricPage[1]; - * hGetter.wThread.postCommandBytes[3] = lastHistoricPage[2]; - * hGetter.wThread.postCommandBytes[4] = lastHistoricPage[3]; - */ - hGetter.isWaitingNextLine = true; - hGetter.currentLine = -1; - hGetter.historicPage.clear(); - return; - } - log.debug("Success!! page crc --> crcReceived " + sCrcReceived - + " crcCalculated " + sCrcCalculated); - // invertpage and remove 0 - StringBuffer buf = new StringBuffer(); - for (int i = hGetter.historicPage.size() - 1; i >= 0; i--) { - byte[] hPage = hGetter.historicPage.get(i); - for (int j = hPage.length - substract; j >= 0; j--) { - if (hPage[j] == (byte) 0x00 && (substract == 3)) { - continue; - } - substract = 1; - page.add(hPage[j]); - buf = buf.append(HexDump.toHexString(hPage[j])); - } - buf.append("\n"); - } - Byte[] invertedPage = page.toArray(new Byte[page.size()]); - // log.debug("InvertedPage \n"+buf.toString()); - readHistoricPage(invertedPage); - } - - /** - * Read and translate the Medtronic log page received. - * - * @param invertedPage - */ - private void readHistoricPage(Byte[] invertedPage) { - boolean glucoseDataRead = false; - boolean sensorTimeStampRead = false; - int glucoseVal = 0; - StringBuffer sb = null; - for (int i = 0; i < invertedPage.length; i++) { - sb = new StringBuffer(); - byte opCommand = HexDump.bUnsignedByte(invertedPage[i]); - if ((opCommand > 0) && (opCommand < 20)) { - // Other data - switch (opCommand) { - case 0x0001: - log.debug(" - Data End"); - i += 0; - break; - case 0x0002: - log.debug(" - Sensor Weak Signal"); - i += 0; - break; - case 0x0003: - sb.append(" - Sensor Calibration : "); - datalog.numEntries++; - if ((invertedPage[i + 1] & 0x00FF) == 0x00) { - sb.append(" Not Calibrated"); - datalog.entryType[datalog.numEntries] = 0x03; - } else { - sb.append(" Calibrating"); - datalog.entryType[datalog.numEntries] = 0x04; - } - log.debug(sb.toString()); - i += 1; - break; - case 0x0008: - int year = 2000 + (invertedPage[i + 4] & 0x00FF); - int day = (invertedPage[i + 3] & 0x001F); - int minute = (invertedPage[i + 2] & 0x003F); - int hour = (invertedPage[i + 1] & 0x001F); - int month = (((invertedPage[i + 1] >> 6) & 0x0003) << 2) - + ((invertedPage[i + 2] >> 6) & 0x0003); - log.debug(" - Sensor Timestamp: " + day + "-" + month - + "-" + year + " " + hour + ":" + minute); - if (glucoseDataRead) - sensorTimeStampRead = true; - i += 4; - - datalog.numEntries++; - datalog.entryType[datalog.numEntries] = 0x08; - Calendar cal = Calendar.getInstance(); - cal.set(year, month, day, hour, minute); - datalog.dateField[datalog.numEntries] = cal.getTime(); - break; - case 0x000B: - sb.append(" - Sensor Status : "); - year = 2000 + (invertedPage[i + 4] & 0x000F); - day = (invertedPage[i + 3] & 0x001F); - minute = (invertedPage[i + 2] & 0x003F); - hour = (invertedPage[i + 1] & 0x001F); - month = (((invertedPage[i + 1] >> 6) & 0x0003) << 2) - + ((invertedPage[i + 2] >> 6) & 0x0003); - sb.append(day + "-" + month + "-" + year + " " + hour + ":" - + minute); - log.debug(sb.toString()); - i += 4; - break; - case 0x000C: - sb.append(" - Date Time Change : "); - for (int j = 14; j > 0; j--) - sb.append(HexDump - .toHexString(invertedPage[i + j] & 0x00FF)); - log.debug(sb.toString()); - i += 14; - break; - case 0x000D: - sb.append(" - Sensor Sync : "); - year = 2000 + (invertedPage[i + 4] & 0x000F); - day = (invertedPage[i + 3] & 0x001F); - minute = (invertedPage[i + 2] & 0x003F); - hour = (invertedPage[i + 1] & 0x001F); - month = (((invertedPage[i + 1] >> 6) & 0x0003) << 2) - + ((invertedPage[i + 2] >> 6) & 0x0003); - sb.append(day + "-" + month + "-" + year + " " + hour + ":" - + minute); - log.debug(sb.toString()); - i += 4; - break; - case 0x000E: - glucoseVal = HexDump.unsignedByte(invertedPage[i + 5]); - year = 2000 + (invertedPage[i + 4] & 0x000F); - day = (invertedPage[i + 3] & 0x001F); - minute = (invertedPage[i + 2] & 0x003F); - hour = (invertedPage[i + 1] & 0x001F); - month = (((invertedPage[i + 1] >> 6) & 0x0003) << 2) - + ((invertedPage[i + 2] >> 6) & 0x0003); - sb.append(" - Calibration BG: " + glucoseVal - + " mg/dl - "); - sb.append(day + "-" + month + "-" + year + " " + hour + ":" - + minute); - log.debug(sb.toString()); - i += 5; - break; - case 0x000F: - sb.append(" - Sensor Calibration Factor : "); - byte[] value = new byte[2]; - value[0] = 0x00; - value[1] = 0x00; - int index = 1; - for (int j = 6; j > 4; j--) { - value[index] = invertedPage[i + j]; - index--; - } - sb.append("" + HexDump.byteArrayToShort(value)); - year = 2000 + (invertedPage[i + 4] & 0x000F); - day = (invertedPage[i + 3] & 0x001F); - minute = (invertedPage[i + 2] & 0x003F); - hour = (invertedPage[i + 1] & 0x001F); - month = (((invertedPage[i + 1] >> 6) & 0x0003) << 2) - + ((invertedPage[i + 2] >> 6) & 0x0003); - sb.append("\n" + day + "-" + month + "-" + year + " " - + hour + ":" + minute); - datalog.numEntries++; - datalog.entryType[datalog.numEntries] = 0x0F; - cal = Calendar.getInstance(); - cal.set(year, month, day, hour, minute); - datalog.dateField[datalog.numEntries] = cal.getTime(); - datalog.calFactor[datalog.numEntries] = HexDump - .byteArrayToShort(value); - log.debug(sb.toString()); - i += 6; - break; - case 0x0010: - sb.append(" - Bolus : "); - // for (j=7;j>4;j--) - // log.debug("%.2X",(invertedPage[i+j]&0x00FF)); - year = 2000 + (invertedPage[i + 4] & 0x00FF); - day = (invertedPage[i + 3] & 0x001F); - minute = (invertedPage[i + 2] & 0x003F); - hour = (invertedPage[i + 1] & 0x001F); - month = (((invertedPage[i + 1] >> 6) & 0x0003) << 2) - + ((invertedPage[i + 2] >> 6) & 0x0003); - sb.append(day + "-" + month + "-" + year + " " + hour + ":" - + minute); - log.debug(sb.toString()); - i += 7; - break; - case 0x0013: - log.debug(" - Basal Profile Start\n"); - i += 0; - break; - default: - log.debug(" - Unknown (" + HexDump.toHexString(opCommand) - + ")"); - i += 0; - break; - } - } else { - // Glucose data - - glucoseVal = (HexDump.unsignedByte(invertedPage[i])) * 2; - log.debug(" - Glucose:" + glucoseVal + " mg/dl (" - + HexDump.toHexString(invertedPage[i]) + ")"); - glucoseDataRead = true; - datalog.numEntries++; - datalog.entryType[datalog.numEntries] = 0x00; - datalog.glucose[datalog.numEntries] = glucoseVal; - } - } - historicPageShift++; - hGetter.shift = historicPageShift; - Date d = new Date(); - - long lastRecordTime = 0; - if (previousRecord != null) { - - lastRecordTime = previousRecord.displayDateTime; - } else if (settings.contains("lastSensorValueDate")) { - lastRecordTime = settings.getLong("lastSensorValueDate", 0); - } - - log.debug("EVAL sensorTimeStampRead " + sensorTimeStampRead - + " timeSinceLastRecord " + lastRecordTime + " historicshift " - + historicPageShift); - if ((sensorTimeStampRead && lastRecordTime > 0) - || historicPageShift > 1) { - log.debug("shift: " + historicPageShift); - int i; - long actualTime = 0; - - // First drop everything before the first timestamp - for (i = datalog.numEntries; i > 0 && datalog.entryType[i] != 0x08; i--) - ; - datalog.numEntries = i; - log.debug("\n * Number of traceable entries: " + datalog.numEntries); - MedtronicSensorRecord record = null; - // Fill missing timestamps - boolean otherPage = false; - boolean first = true; - - for (i = datalog.numEntries; i > 0; i--) { - switch (datalog.entryType[i]) { - case 0x00: - case 0x03: - case 0x04: { - actualTime += 5 * 60000; - datalog.dateField[i] = new Date(actualTime); - // Check times to kow if This record must be uploaded. - if (lastRecordTime == 0 - || ((actualTime > lastRecordTime) && (actualTime - - lastRecordTime > 150000))) { - log.debug("OK! Upload this record"); - - if (first && historicPageShift <= 1) { - otherPage = true; - } - - record = new MedtronicSensorRecord(); - record.setBGValue(datalog.glucose[i] + ""); - calculateDate(record, datalog.dateField[i], 0); - record.isCalibrating = false; - record.calibrationStatus = MedtronicConstants.CALIBRATED; - lastRecordsInMemory.add(record); - calculateTrendAndArrow(record, lastRecordsInMemory); - } else { - log.debug("KO!, this record must not be uploaded"); - first = false; - } - break; - } - case 0x08: - actualTime = datalog.dateField[i].getTime(); - break; - default: - break; - } - } - - SharedPreferences.Editor editor = settings.edit(); - editor.putFloat("previousValue", (float) previousValue); - editor.putInt("calibrationStatus", calibrationStatus); - lastSensorValueDate = d.getTime(); - editor.putLong("lastSensorValueDate", lastSensorValueDate); - editor.commit(); - if (record != null) { - previousRecord = record; - log.debug("7"); - writeLocalCSV(previousRecord, context); - } - if (otherPage) { - sendMessageToUI("The next page must be read", false); - log.debug("The next page must be read"); - hGetter.commandList = Arrays.copyOf(hGetter.commandList, - hGetter.commandList.length + 2); - hGetter.commandList[hGetter.commandList.length - 2] = MedtronicConstants.MEDTRONIC_ACK; - hGetter.commandList[hGetter.commandList.length - 1] = MedtronicConstants.MEDTRONIC_READ_PAGE_COMMAND; - hGetter.wThread.isRequest = true; - hGetter.firstReadPage = true; - hGetter.withoutConfirmation = 1; - /* - * byte[] lastHistoricPage = - * HexDump.toByteArray(historicPageIndex - historicPageShift); - * hGetter.wThread.postCommandBytes = new byte[64]; - * Arrays.fill(hGetter.wThread.postCommandBytes, (byte)0x00); - * hGetter.wThread.postCommandBytes[0] = 0x04; - * hGetter.wThread.postCommandBytes[1] = lastHistoricPage[0]; - * hGetter.wThread.postCommandBytes[2] = lastHistoricPage[1]; - * hGetter.wThread.postCommandBytes[3] = lastHistoricPage[2]; - * hGetter.wThread.postCommandBytes[4] = lastHistoricPage[3]; - */ - hGetter.isWaitingNextLine = true; - hGetter.currentLine = -1; - hGetter.historicPage.clear(); - return; - } - hGetter.commandList = Arrays.copyOf(hGetter.commandList, - hGetter.commandList.length + 2); - hGetter.commandList[hGetter.commandList.length - 2] = MedtronicConstants.MEDTRONIC_ACK; - hGetter.commandList[hGetter.commandList.length - 1] = MedtronicConstants.MEDTRONIC_INIT; - hGetter.withoutConfirmation = 1; - hGetter.wThread.isRequest = true; - hGetter.wThread.postCommandBytes = null; - - // clear vars and EXIT!!! - sendMessageToUI("historic log has been read", false); - // hGetter.init(); - historicPageIndex = -1; - historicPageShift = 0; - datalog = new DataLog(); - SharedPreferences.Editor editor2 = prefs.edit(); - editor2.putLong("lastHistoricRead", System.currentTimeMillis()); - editor2.commit(); - if (mHandlerCheckLastRead != null && checkLastRead != null) - mHandlerCheckLastRead.postDelayed(checkLastRead, - MedtronicConstants.TIME_10_MIN_IN_MS); - - } else { - sendMessageToUI("The next page must be read", false); - log.debug("The next page must be read"); - hGetter.commandList = Arrays.copyOf(hGetter.commandList, - hGetter.commandList.length + 2); - hGetter.commandList[hGetter.commandList.length - 2] = MedtronicConstants.MEDTRONIC_ACK; - hGetter.commandList[hGetter.commandList.length - 1] = MedtronicConstants.MEDTRONIC_READ_PAGE_COMMAND; - hGetter.wThread.isRequest = true; - hGetter.firstReadPage = true; - hGetter.withoutConfirmation = 1; - hGetter.isWaitingNextLine = true; - hGetter.currentLine = -1; - hGetter.historicPage.clear(); - } - } - - /** - * This method process the glucometer messages - * - * @param readData - * @return String, for debug or notification purposes - */ - public String processGlucometerDataMessage(byte[] readData, - boolean calibrate) { - int firstMeasureByte = firstByteAfterDeviceId(readData); - if (firstMeasureByte < 0) - return "Error, I can not identify the initial byte of the glucometer measure"; - int numBytes = ByteBuffer.wrap( - new byte[] { (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) readData[1] }).getInt(); - if (firstMeasureByte > readData.length || numBytes > readData.length) - return "Error, I have detected an error in glucometer message size"; - byte[] arr = Arrays.copyOfRange(readData, firstMeasureByte, - numBytes + 1); - byte[] res = new byte[4]; - if (arr.length < 4) { - for (int j = 0; j < 4; j++) { - res[j] = (byte) 0x00; - if (j >= 4 - arr.length) - res[j] = arr[Math.abs(4 - j - arr.length)]; - } - } else - res = arr; - ByteBuffer wrapped = ByteBuffer.wrap(res); - int num = wrapped.getInt(); // 1 - if (num < 0 || num > 1535) - return "Glucometer value under 0 or over 0x5ff. Possible ACK or malfunction."; - - processManualCalibrationDataMessage(num, true, calibrate); - //int calibrationSelectedAux = 0; - //synchronized (calibrationSelectedLock) { - //calibrationSelectedAux = calibrationSelected; - //} - //sendGlucMessageToUI(num, calibrate, calibrationSelectedAux == MedtronicConstants.CALIBRATION_SENSOR); - return "Measure received " + num + " mg/dl"; - } - - - - public void approveGlucValueForCalibration(float num, boolean calibrate, boolean isSensorFactorFromPump){ - if (!isSensorFactorFromPump) - processManualCalibrationDataMessage(num, false, calibrate); - else{ - sendMessageToUI( - "Glucometer Detected!!..Waiting 15 min. to retrieve calibration factor...", - false); - log.debug("Glucometer Detected!!..Waiting 15 min. to retrieve calibration factor..."); - if (mHandlerSensorCalibration != null - && getCalibrationFromSensor != null) { - mHandlerSensorCalibration - .removeCallbacks(getCalibrationFromSensor); - mHandlerSensorCalibration - .postDelayed( - getCalibrationFromSensor, - MedtronicConstants.TIME_15_MIN_IN_MS + 120000); - } else - log.debug("glucometer handler or glucometer runnable is null"); - lastGlucometerRecord = new GlucometerRecord(); - lastGlucometerRecord.numGlucometerValue = num; - lastGlucometerValue = num; - Date d = new Date(); - lastGlucometerRecord.lastDate = d.getTime(); - lastGlucometerDate = d.getTime(); - calculateDate(lastGlucometerRecord, d, 0); - SharedPreferences.Editor editor = settings.edit(); - editor.putFloat("lastGlucometerValue", (float) lastGlucometerValue); - editor.putLong("glucometerLastDate", d.getTime()); - editor.commit(); - } - } - /** - * This method process the Manual Calibration message - * - * @param readData - * @return String, for debug or notification purposes - */ - public String processManualCalibrationDataMessage(float value, - boolean instant, boolean doCalibration) { - float mult = 1f; - //if (prefs.getBoolean("mmolxl", false)) - //mult = 1f/18f; - float num = value * mult; - lastGlucometerRecord = new GlucometerRecord(); - lastGlucometerRecord.numGlucometerValue = num; - lastGlucometerValue = num; - Date d = new Date(); - lastGlucometerRecord.lastDate = d.getTime(); - lastGlucometerDate = d.getTime(); - calculateDate(lastGlucometerRecord, d, 0); - if (!instant && doCalibration) { - if (HexDump.unsignedByte(expectedSensorSortNumber) == HexDump - .unsignedByte((byte) 0xff)) { - expectedSensorSortNumberForCalibration[0] = (byte) 0x00; - expectedSensorSortNumberForCalibration[1] = (byte) 0x71; - } else { - synchronized (expectedSensorSortNumberLock) { - byte expectedAux = expectedSensorSortNumber; - if (HexDump - .unsignedByte((byte) (expectedSensorSortNumber & (byte) 0x01)) > 0) - expectedAux = (byte) (expectedSensorSortNumber & (byte) 0xFE); - expectedSensorSortNumberForCalibration[0] = calculateNextSensorSortNameFrom( - 6, expectedAux); - expectedSensorSortNumberForCalibration[1] = calculateNextSensorSortNameFrom( - 10, expectedAux); - } - } - } - SharedPreferences.Editor editor = settings.edit(); - editor.putFloat("lastGlucometerValue", (float) num); - editor.putLong("glucometerLastDate", d.getTime()); - if (!instant && doCalibration) { - editor.putString("expectedSensorSortNumberForCalibration0", HexDump - .toHexString(expectedSensorSortNumberForCalibration[0])); - editor.putString("expectedSensorSortNumberForCalibration1", HexDump - .toHexString(expectedSensorSortNumberForCalibration[1])); - } else { - editor.remove("expectedSensorSortNumberForCalibration0"); - editor.remove("expectedSensorSortNumberForCalibration1"); - } - if (lastGlucometerValue > 0) { - isCalibrating = !instant && doCalibration; - if (previousRecord == null) { - MedtronicSensorRecord auxRecord = new MedtronicSensorRecord(); - auxRecord.isCalibrating = !instant; - log.debug("8"); - writeLocalCSV(auxRecord, context); - } else { - previousRecord.isCalibrating = !instant; - log.debug("9"); - writeLocalCSV(previousRecord, context); - } - editor.putBoolean("isCalibrating", !instant); - editor.commit(); - } - editor.commit(); - return "Measure received " + num + " mg/dl"; - } - - /** - * Apply calibration factor to a value in "index" position of the sensor - * message - * - * @param previousCalibrationFactor - * @param previousCalibrationStatus - * @param isig - * @param record - * @param added - * @param currentTime - */ - private void calibratingBackwards(float previousCalibrationFactor, - int previousCalibrationStatus, float isig, - MedtronicSensorRecord record, int added, Date currentTime) { - List<Record> auxList = null; - synchronized (lastRecordsListLock) { - auxList = lastRecordsInMemory.getListFromTail(2); - } - if (previousCalibrationFactor > 0) { - if (previousCalibrationStatus != MedtronicConstants.WITHOUT_ANY_CALIBRATION) { - record.setUnfilteredGlucose(isig * previousCalibrationFactor); - record.setBGValue((applyFilterToRecord(record, auxList)) + ""); - record.isCalibrating = false; - record.calibrationFactor = previousCalibrationFactor; - record.calibrationStatus = previousCalibrationStatus; - } else { - record.setUnfilteredGlucose(isig * previousCalibrationFactor); - record.setBGValue((applyFilterToRecord(record, auxList)) + ""); - record.isCalibrating = false; - record.calibrationFactor = previousCalibrationFactor; - record.calibrationStatus = MedtronicConstants.LAST_CALIBRATION_FAILED_USING_PREVIOUS; - } - } - calculateDate(record, currentTime, added); - } - - /** - * Apply calibration to the "current" value of the sensor message - * - * @param difference - * @param isig - * @param readData - * @param index - * @param record - * @param num - * @param currentTime - */ - private void calibratingCurrentElement(long difference, float isig, - byte[] readData, int index, MedtronicSensorRecord record, int num, - Date currentTime) { - boolean calibrated = false; - // currentMeasure = num; - if (isCalibrating) { - if (num > 0) { - calculateCalibration(difference, isig, readData[index]); - if (calibrationFactor > 0) { - if (!isCalibrating) { - if (calibrationStatus != MedtronicConstants.WITHOUT_ANY_CALIBRATION - && calibrationStatus != MedtronicConstants.LAST_CALIBRATION_FAILED_USING_PREVIOUS - && calibrationStatus != MedtronicConstants.CALIBRATION_MORE_THAN_12H_OLD) { - record.setBGValue(((int) lastGlucometerValue) + ""); - record.setUnfilteredGlucose(lastGlucometerValue); - record.calibrationFactor = calibrationFactor; - record.isCalibrating = false; - record.calibrationStatus = calibrationStatus; - lastCalibrationDate = currentTime.getTime(); - SharedPreferences.Editor editor = settings.edit(); - log.debug("change lastCalibrationDate"); - editor.putLong("lastCalibrationDate", - lastCalibrationDate); - editor.commit(); - calibrated = true; - } - } - } - } - } - if (calibrationFactor > 0 && !calibrated) { - List<Record> auxList = null; - synchronized (lastRecordsListLock) { - auxList = lastRecordsInMemory.getListFromTail(2); - } - if (calibrationStatus != MedtronicConstants.WITHOUT_ANY_CALIBRATION) { - record.setUnfilteredGlucose(isig * calibrationFactor); - record.setBGValue((applyFilterToRecord(record, auxList)) + ""); - record.isCalibrating = false; - record.calibrationFactor = calibrationFactor; - record.calibrationStatus = calibrationStatus; - } else { - record.setUnfilteredGlucose(isig * calibrationFactor); - record.setBGValue((applyFilterToRecord(record, auxList)) + ""); - record.isCalibrating = false; - record.calibrationFactor = calibrationFactor; - record.calibrationStatus = MedtronicConstants.LAST_CALIBRATION_FAILED_USING_PREVIOUS; - } - } - calculateDate(record, currentTime, 0); - previousRecord = record; - } - - public void calculateInstantCalibration(float currentMeasure) { - log.debug("Instant Calibration"); - if (previousRecord != null && previousRecord.isig != 0) { - log.debug("I have isig " + previousRecord.isig); - calibrationFactor = currentMeasure / previousRecord.isig; - log.debug("Instant Calibration result " + calibrationFactor); - if (calibrationFactor > 0) { - previousRecord.bGValue = "" + ((int) currentMeasure); - log.debug("Instant Calibration Success!! "); - calibrationStatus = MedtronicConstants.CALIBRATED; - lastCalibrationDate = System.currentTimeMillis(); - isCalibrating = false; - previousRecord.isCalibrating = false; - previousRecord.calibrationStatus = calibrationStatus; - log.debug("10"); - writeLocalCSV(previousRecord, context); - SharedPreferences.Editor editor = settings.edit(); - log.debug("change instant lastCalibrationDate"); - editor.putLong("lastCalibrationDate", lastCalibrationDate); - editor.putBoolean("isCalibrating", false); - editor.putFloat("calibrationFactor", (float) calibrationFactor); - editor.putInt("calibrationStatus", - calibrationStatus); - editor.commit(); - } - return; - } else{ - sendErrorMessageToUI("I can't calibrate, I don't have any ISIG stored yet."); - log.debug("I dont have isig"); - } - if (previousRecord == null) - previousRecord = new MedtronicSensorRecord(); - if (calibrationStatus != MedtronicConstants.WITHOUT_ANY_CALIBRATION - && calibrationFactor != -1f) { - calibrationStatus = MedtronicConstants.LAST_CALIBRATION_FAILED_USING_PREVIOUS; - } else { - calibrationStatus = MedtronicConstants.WITHOUT_ANY_CALIBRATION; - } - previousRecord.calibrationStatus = calibrationStatus; - log.debug("11"); - writeLocalCSV(previousRecord, context); - log.debug("Instant Calibration Failure!! "); - } - - /** - * This method process the sensor answers - * - * @param readData - * @return String, for debug or notification purposes - */ - public String processSensorDataMessage(byte[] readData) { - Date d = new Date(); - long difference = 0; - if (isCalibrating && lastGlucometerDate > 0) { - difference = d.getTime() - lastGlucometerDate; - } - - int added = 8; - int firstMeasureByte = firstByteAfterDeviceId(readData); - int currentMeasure = -1; - float isig = 0; - StringBuffer sResult = new StringBuffer(""); - if (firstMeasureByte < 0) - return "Error, I can not identify the initial byte of the sensor measure"; - int numBytes = HexDump.unsignedByte(readData[1]); - if (firstMeasureByte > readData.length || numBytes > readData.length - || numBytes <= 0) - return "Error, I have detected an error in sensor message size"; - int previousCalibrationStatus = calibrationStatus; - float previousCalibrationFactor = calibrationFactor; - short adjustement = (short) readData[firstMeasureByte + 2]; - long firstTimeOut = d.getTime() - lastSensorValueDate; - if (HexDump.unsignedByte(expectedSensorSortNumber) == HexDump - .unsignedByte((byte) 0xff) - || firstTimeOut == d.getTime() - || (firstTimeOut > MedtronicConstants.TIME_10_MIN_IN_MS - + MedtronicConstants.TIME_30_MIN_IN_MS)) { - Log.i("Medtronic", "First"); - log.debug("SENSOR MEASURE, First Time, retrieving all previous measures"); - lastElementsAdded = 0; - // I must read ALL THE MEASURES - synchronized (expectedSensorSortNumberLock) { - expectedSensorSortNumber = readData[firstMeasureByte + 3]; - } - - for (int i = 20; i >= 0; i -= 2) { - if (i >= 4 && i < 8) { - continue; - } - lastElementsAdded++; - byte[] arr = Arrays.copyOfRange(readData, firstMeasureByte + 4 - + i, firstMeasureByte + 6 + i); - byte[] res = new byte[4]; - if (arr.length < 4) { - for (int j = 0; j < 4; j++) { - res[j] = (byte) 0x00; - if (j >= 4 - arr.length) - res[j] = arr[Math.abs(4 - j - arr.length)]; - } - } else - res = arr; - ByteBuffer wrapped = ByteBuffer.wrap(res); - int num = wrapped.getInt(); // 1 - MedtronicSensorRecord record = new MedtronicSensorRecord(); - record.isCalibrating = isCalibrating; - isig = calculateISIG(num, adjustement); - record.setIsig(isig); - if (i == 0) { - currentMeasure = num; - calibratingCurrentElement(difference, isig, readData, - firstMeasureByte + 3, record, num, d); - } else { - calibratingBackwards(previousCalibrationFactor, - previousCalibrationStatus, isig, record, added, d); - } - added--; - lastRecordsInMemory.add(record); - calculateTrendAndArrow(record, lastRecordsInMemory); - sResult.append("Measure(").append(((i + 2) / 2)).append("): ") - .append(num); - } - - } else { - log.debug("Estoy Esperando " - + HexDump.toHexString(expectedSensorSortNumber) - + " He recibido " - + HexDump.toHexString(readData[firstMeasureByte + 3])); - if (HexDump.unsignedByte(expectedSensorSortNumber) == HexDump - .unsignedByte(readData[firstMeasureByte + 3]) - || HexDump.unsignedByte(calculateNextSensorSortNameFrom(1, - expectedSensorSortNumber)) == HexDump - .unsignedByte(readData[firstMeasureByte + 3])) { - Log.i("Medtronic", "Expected sensor number received!!"); - log.debug("SENSOR MEASURE, Expected sensor measure received!!"); - lastElementsAdded = 0; - // I must read only the first value except if byte ends in "1" - // then I skip this value - if (!isSensorRepeatedMessage(readData[firstMeasureByte + 3]) - || HexDump - .unsignedByte((byte) ((byte) expectedSensorSortNumber & (byte) 0x01)) < 1 - && HexDump - .unsignedByte((byte) ((byte) readData[firstMeasureByte + 3] & (byte) 0x01)) == 1) { - byte[] arr = Arrays.copyOfRange(readData, - firstMeasureByte + 4, firstMeasureByte + 6); - byte[] res = new byte[4]; - if (arr.length < 4) { - for (int j = 0; j < 4; j++) { - res[j] = (byte) 0x00; - if (j >= 4 - arr.length) - res[j] = arr[Math.abs(4 - j - arr.length)]; - } - } else - res = arr; - ByteBuffer wrapped = ByteBuffer.wrap(res); - int num = wrapped.getInt(); // 1 - MedtronicSensorRecord record = new MedtronicSensorRecord(); - isig = calculateISIG(num, adjustement); - record.setIsig(isig); - record.isCalibrating = isCalibrating; - currentMeasure = num; - calibratingCurrentElement(difference, isig, readData, - firstMeasureByte + 3, record, num, d); - lastRecordsInMemory.add(record); - calculateTrendAndArrow(record, lastRecordsInMemory); - sResult.append("last measure: ").append(num); - lastElementsAdded++; - } else { - // sendMessageToUI("ES REPETIDO NO LO EVALUO ", false); - synchronized (expectedSensorSortNumberLock) { - expectedSensorSortNumber = calculateNextSensorSortNameFrom( - 1, expectedSensorSortNumber); - } - return sResult.toString(); - } - } else { - Log.i("Medtronic", "NOT Expected sensor number received!!"); - log.debug("SENSOR MEASURE, NOT Expected sensor measure received!!"); - int dataLost = -1; - if (previousRecord != null || lastSensorValueDate > 0) { - long timeDiff = 0; - if (previousRecord != null) - timeDiff = d.getTime() - previousRecord.displayDateTime; - else - timeDiff = d.getTime() - lastSensorValueDate; - if (timeDiff > (MedtronicConstants.TIME_30_MIN_IN_MS + MedtronicConstants.TIME_10_MIN_IN_MS)) { - dataLost = 10; - added = 8; - } else { - int valPrev = transformSequenceToIndex(expectedSensorSortNumber); - int currentVal = transformSequenceToIndex(readData[firstMeasureByte + 3]); - if (valPrev > currentVal) - currentVal = 8 + currentVal; - dataLost = (currentVal - (valPrev)) % 9; - if (dataLost < 0) - dataLost *= -1; - dataLost--; - added = dataLost; - Log.i("medtronic", " valPrev " + valPrev - + " currentVal " + currentVal + " dataLost " - + dataLost + " added " + added); - } - } else { - dataLost = 10; - added = 8; - } - Log.i("Medtronic", "Data Lost " + dataLost); - if (dataLost >= 0) { - if (dataLost >= 2) - dataLost += 2; - if (dataLost > 10) { - dataLost = 10; - added = 8; - } - log.debug("SENSOR MEASURE, I am going to retrieve " - + (dataLost) + " previous values"); - dataLost *= 2; - lastElementsAdded = 0; - // I must read ALL THE MEASURES - if (dataLost == 20 || dataLost == 0) { - synchronized (expectedSensorSortNumberLock) { - expectedSensorSortNumber = readData[firstMeasureByte + 3]; - } - } - - for (int i = dataLost; i >= 0; i -= 2) { - if (i >= 4 && i < 8) { - continue; - } - lastElementsAdded++; - byte[] arr = Arrays.copyOfRange(readData, - firstMeasureByte + 4 + i, firstMeasureByte + 6 - + i); - byte[] res = new byte[4]; - if (arr.length < 4) { - for (int j = 0; j < 4; j++) { - res[j] = (byte) 0x00; - if (j >= 4 - arr.length) - res[j] = arr[Math.abs(4 - j - arr.length)]; - } - } else - res = arr; - ByteBuffer wrapped = ByteBuffer.wrap(res); - int num = wrapped.getInt(); // 1 - MedtronicSensorRecord record = new MedtronicSensorRecord(); - record.isCalibrating = isCalibrating; - isig = calculateISIG(num, adjustement); - record.setIsig(isig); - if (i == 0) { - currentMeasure = num; - calibratingCurrentElement(difference, isig, - readData, firstMeasureByte + 3, record, - num, d); - } else { - calibratingBackwards(previousCalibrationFactor, - previousCalibrationStatus, isig, record, - added, d); - } - added--; - lastRecordsInMemory.add(record); - calculateTrendAndArrow(record, lastRecordsInMemory); - sResult.append("Measure(").append(((i + 2) / 2)) - .append("): ").append(num); - } - } else { - byte[] arr = Arrays.copyOfRange(readData, - firstMeasureByte + 4, firstMeasureByte + 6); - byte[] res = new byte[4]; - if (arr.length < 4) { - for (int j = 0; j < 4; j++) { - res[j] = (byte) 0x00; - if (j >= 4 - arr.length) - res[j] = arr[Math.abs(4 - j - arr.length)]; - } - } else - res = arr; - ByteBuffer wrapped = ByteBuffer.wrap(res); - int num = wrapped.getInt(); // 1 - MedtronicSensorRecord record = new MedtronicSensorRecord(); - isig = calculateISIG(num, adjustement); - record.setIsig(isig); - record.isCalibrating = isCalibrating; - currentMeasure = num; - calibratingCurrentElement(difference, isig, readData, - firstMeasureByte + 3, record, num, d); - lastRecordsInMemory.add(record); - calculateTrendAndArrow(record, lastRecordsInMemory); - sResult.append("last measure: ").append(num); - lastElementsAdded++; - } - } - Log.i("Medtronic", "Fill next expected"); - expectedSensorSortNumber = readData[firstMeasureByte + 3]; - } - previousValue = currentMeasure; - // I must recalculate next message!!!! - synchronized (expectedSensorSortNumberLock) { - expectedSensorSortNumber = calculateNextSensorSortNameFrom(1, - expectedSensorSortNumber); - } - - SharedPreferences.Editor editor = settings.edit(); - editor.putFloat("previousValue", (float) previousValue); - editor.putString("expectedSensorSortNumber", - HexDump.toHexString(expectedSensorSortNumber)); - editor.putInt("calibrationStatus", calibrationStatus); - lastSensorValueDate = d.getTime(); - editor.putLong("lastSensorValueDate", lastSensorValueDate); - editor.commit(); - log.debug("12"); - writeLocalCSV(previousRecord, context); - Log.i("Medtronic", "BYE!!!!"); - log.debug("sensorprocessed end expected " - + HexDump.toHexString(expectedSensorSortNumber)); - return sResult.toString(); - } - - /** - * This method saves a file with the last Record read from the device - * - * @param mostRecentData - * , Record to save. - * @param context - * , Application context. - */ - private void writeLocalCSV(MedtronicSensorRecord mostRecentData, - Context context) { - - // Write EGV Binary of last (most recent) data - try { - if (mostRecentData == null || mostRecentData.bGValue == null) - log.debug("writeLocalCSV SAVING EMPTY!!"); - else - log.debug("writeLocalCSV SAVING --> " + mostRecentData.bGValue); - ObjectOutputStream oos = new ObjectOutputStream( - new FileOutputStream(new File(context.getFilesDir(), - "save.bin"))); // Select where you wish to save the - // file... - oos.writeObject(mostRecentData); // write the class as an 'object' - oos.flush(); // flush the stream to insure all of the information - // was written to 'save.bin' - oos.close();// close the stream - } catch (Exception e) { - Log.e(TAG, "write to OutputStream failed", e); - log.error("write to OutputStream failed", e); - } - } - - /** - * Checks if the message received is the expected redundant message. - * - * @param sortID - * @return true, if is the redundant message - */ - private boolean isSensorRepeatedMessage(byte sortID) { - String sExpected = HexDump.toHexString(expectedSensorSortNumber); - String sSortId = HexDump.toHexString(sortID); - if (sExpected != null && sSortId != null - && sExpected.length() == sSortId.length() - && sExpected.length() >= 2) { - return (sExpected.charAt(0) == sSortId.charAt(0)) - && (sSortId.charAt(1) == '1'); - } else - return false; - } - - /** - * The messages emitted from the sensor are sorted following the pattern: - * order byte - content ================================= 00 - message 01 - - * same message as 00 10 - message2 11 - same message2 as 10 20 - message3 - * 21 - same message3 as 20 ... ... 60 - message6 61 - same message6 as 60 - * 70 - message7 71 - same message7 as 70 00 - message8 01 - same message8 - * as 00 ... ... - * - * @return next order to be expected - */ - private byte calculateNextSensorSortNameFrom(int shift, - byte expectedSensorSortNumber) { - // sendMessageToUI("calculating FROM "+HexDump.toHexString(expectedSensorSortNumber), - // false); - byte aux = expectedSensorSortNumber; - String sExpected = HexDump.toHexString(aux); - if (sExpected != null && sExpected.length() >= 2) { - - while (shift > 0) { - sExpected = HexDump.toHexString(aux); - char sort1 = sExpected.charAt(0); - - boolean repeated = sExpected.charAt(1) == '1'; - switch (sort1) { - case '0': - aux = (byte) 0x10; - if (!repeated) - aux = (byte) 0x01; - break; - case '1': - aux = (byte) 0x20; - if (!repeated) - aux = (byte) 0x11; - break; - case '2': - aux = (byte) 0x30; - if (!repeated) - aux = (byte) 0x21; - break; - case '3': - aux = (byte) 0x40; - if (!repeated) - aux = (byte) 0x31; - break; - case '4': - aux = (byte) 0x50; - if (!repeated) - aux = (byte) 0x41; - break; - case '5': - aux = (byte) 0x60; - if (!repeated) - aux = (byte) 0x51; - break; - case '6': - aux = (byte) 0x70; - if (!repeated) - aux = (byte) 0x61; - break; - case '7': - aux = (byte) 0x00; - if (!repeated) - aux = (byte) 0x71; - break; - default: - aux = (byte) 0xff; - } - shift--; - } - return aux; - } else - return (byte) 0xff; - } - - private int transformSequenceToIndex(byte aux) { - String sExpected = HexDump.toHexString(aux); - char sort1 = sExpected.charAt(0); - int result = Integer.parseInt("" + sort1); - if (result == 0) - result = 8; - return result; - } - - /** - * This function checks if the measure index is between a range of indexes - * previously stored. - * - * @param measureIndex - * , index to check - * @param range - * , - * @return true if the measure index is between a range of indexes - * previously stored. - */ - private boolean isSensorMeasureInRange(byte measureIndex, byte[] range) { - byte minRange = range[0]; - byte maxRange = range[1]; - if (HexDump.unsignedByte(maxRange) < HexDump.unsignedByte(minRange)) { - return ((HexDump.unsignedByte(measureIndex) >= HexDump - .unsignedByte(minRange)) && (HexDump - .unsignedByte(measureIndex) <= HexDump - .unsignedByte((byte) 0x71))) - || (HexDump.unsignedByte(measureIndex) <= HexDump - .unsignedByte(maxRange)) - && (HexDump.unsignedByte(measureIndex) >= HexDump - .unsignedByte((byte) 0x00)); - } else { - return (HexDump.unsignedByte(measureIndex) >= HexDump - .unsignedByte(minRange)) - && (HexDump.unsignedByte(measureIndex) <= HexDump - .unsignedByte(maxRange)); - } - } - - /** - * method to store the current status of my known devices. this info will be - * used to restore status. - */ - public void storeKnownDevices() { - StringBuffer listKnownDevices = new StringBuffer(); - boolean first = true; - for (String id : knownDevices) { - if (id.length() > 0) { - if (!first) - listKnownDevices = listKnownDevices.append(","); - else - first = false; - listKnownDevices = listKnownDevices.append(id); - } - } - SharedPreferences.Editor editor = settings.edit(); - editor.putString("knownDevices", listKnownDevices.toString()); - editor.commit(); - } - - /** - * This method calculates the date of the sensor readings - * - * @param record - * , current sensor reading - * @param initTime - * , time of the first (most actual) reading in this row - * @param substract - * , index of this reading respectively the initTime reading. - * Each increment subtracts 5 minutes to "initTime" - */ - public void calculateDate(Record record, Date initTime, int subtract) { - Date d = initTime; - - long milliseconds = d.getTime(); - - if (subtract > 0) { - milliseconds -= subtract * MedtronicConstants.TIME_5_MIN_IN_MS;// record - // was - // read - // (subtract - // * - // 5 - // minutes) before the initTime - } - - long timeAdd = milliseconds; - - /* - * TimeZone tz = TimeZone.getDefault(); - * - * if (!tz.inDaylightTime(new Date())) timeAdd = timeAdd - 3600000L; - */ - Date display = new Date(timeAdd); - String displayTime = new SimpleDateFormat("MM/dd/yyy hh:mm:ss aa", - Locale.getDefault()).format(display); - record.displayTime = displayTime; - if (record instanceof MedtronicSensorRecord) { - ((MedtronicSensorRecord) record).displayDateTime = display - .getTime(); - } - } - - /** - * This method checks if a calibration is valid. - * - * @param difference - * @param currentMeasure - * @param currentIndex - */ - private void calculateCalibration(long difference, float currentMeasure, - byte currentIndex) { - if (difference >= MedtronicConstants.TIME_15_MIN_IN_MS - && difference < MedtronicConstants.TIME_20_MIN_IN_MS) { - if (isSensorMeasureInRange(currentIndex, - expectedSensorSortNumberForCalibration)) { - isCalibrating = false; - calibrationStatus = MedtronicConstants.CALIBRATED; - calibrationIsigValue = currentMeasure; - SharedPreferences.Editor editor = settings.edit(); - calibrationFactor = lastGlucometerValue / calibrationIsigValue; - editor.remove("expectedSensorSortNumberForCalibration0"); - editor.remove("expectedSensorSortNumberForCalibration1"); - editor.putFloat("calibrationFactor", (float) calibrationFactor); - editor.putInt("calibrationStatus", - calibrationStatus); - editor.commit(); - } else { - if (calibrationStatus != MedtronicConstants.WITHOUT_ANY_CALIBRATION - && currentIndex != expectedSensorSortNumber) { - calibrationStatus = MedtronicConstants.LAST_CALIBRATION_FAILED_USING_PREVIOUS; - isCalibrating = false; - } else { - calibrationStatus = MedtronicConstants.WITHOUT_ANY_CALIBRATION; - } - SharedPreferences.Editor editor = settings.edit(); - editor.remove("expectedSensorSortNumberForCalibration0"); - editor.remove("expectedSensorSortNumberForCalibration1"); - editor.commit(); - } - } else if (difference >= MedtronicConstants.TIME_20_MIN_IN_MS) { - if (isSensorMeasureInRange(currentIndex, - expectedSensorSortNumberForCalibration)) { - calibrationStatus = MedtronicConstants.CALIBRATED_IN_15MIN; - calibrationIsigValue = currentMeasure; - SharedPreferences.Editor editor = settings.edit(); - calibrationFactor = lastGlucometerValue / calibrationIsigValue; - editor.remove("expectedSensorSortNumberForCalibration0"); - editor.remove("expectedSensorSortNumberForCalibration1"); - editor.putFloat("calibrationFactor", (float) calibrationFactor); - editor.putInt("calibrationStatus", - calibrationStatus); - editor.commit(); - } else { - if (calibrationStatus != MedtronicConstants.WITHOUT_ANY_CALIBRATION) - calibrationStatus = MedtronicConstants.LAST_CALIBRATION_FAILED_USING_PREVIOUS; - else { - calibrationStatus = MedtronicConstants.WITHOUT_ANY_CALIBRATION; - } - SharedPreferences.Editor editor = settings.edit(); - editor.remove("expectedSensorSortNumberForCalibration0"); - editor.remove("expectedSensorSortNumberForCalibration1"); - editor.commit(); - } - isCalibrating = false; - } else { - if (isCalibrating){ - if (difference < MedtronicConstants.TIME_5_MIN_IN_MS) { - calibrationStatus = MedtronicConstants.CALIBRATING; - } else if (difference >= MedtronicConstants.TIME_5_MIN_IN_MS - && difference <= MedtronicConstants.TIME_15_MIN_IN_MS) - calibrationStatus = MedtronicConstants.CALIBRATING2; - else - calibrationStatus = MedtronicConstants.CALIBRATING; - }else{ - if (calibrationStatus != MedtronicConstants.WITHOUT_ANY_CALIBRATION) - calibrationStatus = MedtronicConstants.LAST_CALIBRATION_FAILED_USING_PREVIOUS; - else { - calibrationStatus = MedtronicConstants.WITHOUT_ANY_CALIBRATION; - } - SharedPreferences.Editor editor = settings.edit(); - editor.remove("expectedSensorSortNumberForCalibration0"); - editor.remove("expectedSensorSortNumberForCalibration1"); - editor.putInt("calibrationStatus", - calibrationStatus); - editor.commit(); - } - } - } - - /** - * Function which helps to calculate the difference of Glucose. - * - * @param size - * , amount of records to use (aprox. 5 min between records) - * @param list - * , list of records. - * @return, Total Glucose variation. - */ - public Float getGlucoseDifferentialIn(int size, CircleList<Record> list) { - List<Record> auxList = list.getListFromTail(size); - SimpleDateFormat formatter = new SimpleDateFormat( - "MM/dd/yyyy hh:mm:ss a", Locale.getDefault()); - if (auxList.size() == size) { - log.debug("I Have the correct size"); - for (int i = 1; i < size; i++) { - if (!(auxList.get(i) instanceof MedtronicSensorRecord)) { - log.debug("but not the correct records"); - return null; - } - } - float diff = 0; - long dateDif = 0; - for (int i = 1; i < size; i++) { - log.debug("Start calculate diff"); - MedtronicSensorRecord prevRecord = (MedtronicSensorRecord) auxList - .get(i - 1); - MedtronicSensorRecord record = (MedtronicSensorRecord) auxList - .get(i); - Date prevDate = null; - Date date = null; - try { - prevDate = formatter.parse(prevRecord.displayTime); - date = formatter.parse(record.displayTime); - dateDif += (prevDate.getTime() - date.getTime()); - log.debug("DATE_diff " + dateDif); - } catch (ParseException e1) { - e1.printStackTrace(); - } - - float prevRecordValue = 0; - float recordValue = 0; - try { - prevRecordValue = Float.parseFloat(prevRecord.bGValue); - } catch (Exception e) { - - } - try { - recordValue = Float.parseFloat(record.bGValue); - } catch (Exception e) { - - } - - if (prevRecordValue > 0 && recordValue <= 0) { - log.debug("AdjustRecordValue prev " + prevRecordValue - + " record " + recordValue); - recordValue = prevRecordValue; - } - diff += prevRecordValue - recordValue; - log.debug("VALUEDIFF " + diff); - } - if (dateDif > MedtronicConstants.TIME_20_MIN_IN_MS) { - log.debug("EXIT BY TIME "); - return null; - } else { - log.debug("CORRECT EXIT "); - return diff; - } - } else { - log.debug("I DO NOT Have the correct size " + auxList.size()); - return null; - } - } - - /** - * Function to calculate ISIG value - * - * @param value - * , Raw Value - * @param adjustment - * , - * @return ISIG value - */ - public float calculateISIG(int value, short adjustment) { - float isig = (float) value - / (MedtronicConstants.SENSOR_CONVERSION_CONSTANT_VALUE - ((float) value * (float) MedtronicConstants.SENSOR_CONVERSION_CONSTANT_VALUE2)); - isig += ((float) adjustment * (float) value * (MedtronicConstants.SENSOR_CONVERSION_CONSTANT_VALUE3 + (MedtronicConstants.SENSOR_CONVERSION_CONSTANT_VALUE4 - * (float) value / (float) MedtronicConstants.SENSOR_CONVERSION_CONSTANT_VALUE5))); - return isig; - } - - /** - * This function calculates the SVG to upload applying a filter to the - * Unfiltered glucose data - * - * @param prevRecord - * @param auxList - * @return - */ - public int applyFilterToRecord(MedtronicSensorRecord currentRecord, - List<Record> auxList) { - /* - * if (auxList.size() >= 2) { - * - * if (!(auxList.get(0) instanceof MedtronicSensorRecord)) return -1; - * MedtronicSensorRecord record = (MedtronicSensorRecord) auxList - * .get(0); MedtronicSensorRecord record2 = (MedtronicSensorRecord) - * auxList .get(1); return (int) ((currentRecord.unfilteredGlucose * - * glucoseFilter[0]) + (record.unfilteredGlucose * glucoseFilter[1]) + - * (record2.unfilteredGlucose * glucoseFilter[2])); } else if - * (auxList.size() == 1) { MedtronicSensorRecord record = - * (MedtronicSensorRecord) auxList .get(0); return (int) - * ((currentRecord.unfilteredGlucose * glucoseFilter[0]) + - * (currentRecord.unfilteredGlucose * glucoseFilter[1]) + - * (record.unfilteredGlucose * glucoseFilter[2])); }else{ return (int) - * ((currentRecord.unfilteredGlucose * glucoseFilter[0]) + - * (currentRecord.unfilteredGlucose * glucoseFilter[1])+ - * (currentRecord.unfilteredGlucose * glucoseFilter[2])); } - */ - return (int) currentRecord.unfilteredGlucose; - - } - - /** - * calculates crc16 - * - * @param bytes - * @return crc - */ - public int crc16(Byte[] bytes) { - int crc = 0xFFFF; // initial value - int polynomial = 0x1021; // 0001 0000 0010 0001 (0, 5, 12) - // byte[] testBytes = "123456789".getBytes("ASCII"); - for (byte b : bytes) { - for (int i = 0; i < 8; i++) { - boolean bit = ((b >> (7 - i) & 1) == 1); - boolean c15 = ((crc >> 15 & 1) == 1); - crc <<= 1; - if (c15 ^ bit) - crc ^= polynomial; - } - } - crc &= 0xffff; - return crc; - } - - /** - * This function tries to calculate the trend of the glucose values. - * - * @param record - * @param list - */ - public void calculateTrendAndArrow(MedtronicSensorRecord record, - CircleList<Record> list) { - String trend = "Not Calculated"; - String trendA = "--X"; - Float diff = getGlucoseDifferentialIn(3, list);// most Recent first - if (diff != null) { - diff /= 5f; - diff *= 0.0555f;// convierto a mmol/l - int trendArrow = 0; - if (diff >= -0.06f && diff <= 0.06f) - trendArrow = 4; - else if ((diff > 0.06f) && (diff <= 0.11f)) { - trendArrow = 3; - } else if ((diff < -0.06f) && (diff >= -0.11f)) { - trendArrow = 5; - } else if ((diff > 0.11f) && (diff <= 0.17f)) { - trendArrow = 2; - } else if ((diff < -0.11f) && (diff >= -0.17f)) { - trendArrow = 6; - } else if ((diff > 0.17f)) { - trendArrow = 1; - } else if ((diff < -0.17f)) { - trendArrow = 7; - } else { - trendArrow = 0; - } - - switch (trendArrow) { - case (0): - trendA = "\u2194"; - trend = "NONE"; - break; - case (1): - trendA = "\u21C8"; - trend = "DoubleUp"; - break; - case (2): - trendA = "\u2191"; - trend = "SingleUp"; - break; - case (3): - trendA = "\u2197"; - trend = "FortyFiveUp"; - break; - case (4): - trendA = "\u2192"; - trend = "Flat"; - break; - case (5): - trendA = "\u2198"; - trend = "FortyFiveDown"; - break; - case (6): - trendA = "\u2193"; - trend = "SingleDown"; - break; - case (7): - trendA = "\u21CA"; - trend = "DoubleDown"; - break; - case (8): - trendA = "\u2194"; - trend = "NOT COMPUTABLE"; - break; - case (9): - trendA = "\u2194"; - trend = "RATE OUT OF RANGE"; - break; - } - } else { - trendA = "\u2194"; - trend = "RATE OUT OF RANGE"; - } - - record.trend = trend; - record.trendArrow = trendA; - } - - /** - * Sends an error message to be printed in the display (DEBUG) if it is repeated, It is not printed again. If UI is not visible, It will launch a pop-up message. - * @param valuetosend - * @param clear, if true, the display is cleared before printing "valuetosend" - */ - private void sendErrorMessageToUI(String valuetosend) { - Log.e("medtronicCGMService", valuetosend); - log.error("Send Error Message to UI "+ valuetosend); - if (mClients != null && mClients.size() > 0) { - for (int i = mClients.size() - 1; i >= 0; i--) { - try { - Message mSend = null; - mSend = Message - .obtain(null, - MedtronicConstants.MSG_MEDTRONIC_CGM_ERROR_RECEIVED); - Bundle b = new Bundle(); - b.putString("data", valuetosend); - mSend.setData(b); - mClients.get(i).send(mSend); - - } catch (RemoteException e) { - // The client is dead. Remove it from the list; we are going - // through the list from back to front so this is safe to do - // inside the loop. - mClients.remove(i); - } - } - } - } - - - /** - * Class to manage the circular aspect of the sensor readings - * - * @author lmmarguenda - * - * @param <E> - */ - class CircleList<E> { - private int size; - private int capacity; - private int endOffset; - private int startOffset; - ArrayList<E> list = new ArrayList<E>(); - private Object listLock = new Object(); - - /** - * Constructor - * - * @param capacity - */ - public CircleList(int capacity) { - size = 0; - this.capacity = capacity; - endOffset = 0; - startOffset = 0; - list = new ArrayList<E>(); - } - - /** - * add - * - * @param item - */ - public void add(E item) { - synchronized (listLock) { - if (endOffset == capacity) { - endOffset = 0; - startOffset = 1; - } - if (endOffset >= list.size()) - list.add(endOffset, item); - else - list.set(endOffset, item); - endOffset++; - if (endOffset <= startOffset) - startOffset++; - if (startOffset == capacity) - startOffset = 0; - size = list.size(); - } - } - - /** - * clear - */ - public void clear() { - synchronized (listLock) { - size = 0; - endOffset = 0; - startOffset = 0; - list.clear(); - } - } - - /** - * @param size - * , maximum number of elements to get. - * @return a list sorted from the "startOffset" to the "endOffset". - */ - public List<E> getList(int size) { - List<E> result = new ArrayList<E>(); - List<E> aux = null; - int auxEndOffset = 0; - int auxStartOffset = 0; - synchronized (listLock) { - auxEndOffset = endOffset; - auxStartOffset = startOffset; - aux = new ArrayList<E>(); - aux.addAll(list); - - } - int auxSize = size; - if (auxSize > aux.size()) - auxSize = aux.size(); - if (auxEndOffset > auxStartOffset) { - for (int i = auxStartOffset; i < auxEndOffset && auxSize > 0; i++) { - result.add(aux.get(i)); - auxSize--; - } - } else { - for (int i = auxStartOffset; i < capacity && auxSize > 0; i++) { - result.add(aux.get(i)); - auxSize--; - } - for (int i = 0; i < auxEndOffset && auxSize > 0; i++) { - result.add(aux.get(i)); - auxSize--; - } - } - return result; - } - - /** - * @param size - * , maximum number of elements to get. - * @return a list sorted from the "endOffset" to the "startOffset". - */ - public List<E> getListFromTail(int size) { - List<E> result = new ArrayList<E>(); - List<E> aux = null; - int auxEndOffset = 0; - int auxStartOffset = 0; - synchronized (listLock) { - auxEndOffset = endOffset; - auxStartOffset = startOffset; - aux = new ArrayList<E>(); - aux.addAll(list); - - } - int auxSize = size; - if (auxSize > aux.size()) - auxSize = aux.size(); - - if (auxEndOffset > auxStartOffset) { - for (int i = auxEndOffset - 1; i >= auxStartOffset - && auxSize > 0; i--) { - result.add(aux.get(i)); - auxSize--; - } - } else { - for (int i = auxEndOffset - 1; i >= 0 && auxSize > 0; i--) { - result.add(aux.get(i)); - auxSize--; - } - if (auxSize > 0) { - for (int i = capacity - 1; i >= auxStartOffset - && auxSize > 0; i--) { - result.add(aux.get(i)); - auxSize--; - } - } - } - return result; - } - - /** - * - * @return items allocated. - */ - public int size() { - synchronized (listLock) { - return size; - } - } - } - - /** - * Runnable to check how old is the last calibration, and to manage the time - * out of the current calibration process - * - * @author lmmarguenda - * - */ - class CalibrationStatusChecker implements Runnable { - public Handler mHandlerReviewParameters = null; - - public CalibrationStatusChecker(Handler mHandlerReviewParameters) { - this.mHandlerReviewParameters = mHandlerReviewParameters; - } - - public void run() { - checkCalibrationOutOfTime(); - mHandlerReviewParameters.postDelayed(this, - MedtronicConstants.TIME_5_MIN_IN_MS); - } - } - -} diff --git a/app/src/main/java/info/nightscout/android/medtronic/service/MedtronicCNLService.java b/app/src/main/java/info/nightscout/android/medtronic/service/MedtronicCNLService.java index 9130afa..3668744 100644 --- a/app/src/main/java/info/nightscout/android/medtronic/service/MedtronicCNLService.java +++ b/app/src/main/java/info/nightscout/android/medtronic/service/MedtronicCNLService.java @@ -115,13 +115,13 @@ public class MedtronicCNLService extends AbstractService { CGMRecord cgmRecord = loadData(); PumpStatusRecord pumpRecord = Medtronic640gActivity.pumpStatusRecord; - send(Message.obtain(null, Medtronic640gActivity.DexcomG4ActivityHandler.MSG_DATA, cgmRecord)); + send(Message.obtain(null, Medtronic640gActivity.Medtronic640gActivityHandler.MSG_DATA, cgmRecord)); if (mHidDevice == null) { String title = "USB connection error"; String msg = "Is the Bayer Contour NextLink plugged in?"; //showNotification(title, msg); - send(Message.obtain(null, Medtronic640gActivity.DexcomG4ActivityHandler.MSG_ERROR, title + "\n" + msg)); + send(Message.obtain(null, Medtronic640gActivity.Medtronic640gActivityHandler.MSG_ERROR, title + "\n" + msg)); } else { try { mHidDevice.open(); @@ -134,7 +134,7 @@ public class MedtronicCNLService extends AbstractService { MedtronicCNLReader cnlReader = new MedtronicCNLReader(mHidDevice); try { - send(Message.obtain(null, Medtronic640gActivity.DexcomG4ActivityHandler.MSG_STATUS, "Connecting to the Contour Next Link...")); + send(Message.obtain(null, Medtronic640gActivity.Medtronic640gActivityHandler.MSG_STATUS, "Connecting to the Contour Next Link...")); cnlReader.requestDeviceInfo(); // Is the device already configured? @@ -147,7 +147,7 @@ public class MedtronicCNLService extends AbstractService { Medtronic640gActivity.pumpStatusRecord.setDeviceName(deviceName); if (hmac.equals("") || key.equals("")) { - send(Message.obtain(null, Medtronic640gActivity.DexcomG4ActivityHandler.MSG_ERROR, String.format("Before you can use the Contour Next Link, you need to register it with the app. Select '%s' from the menu.", getString(R.string.register_contour_next_link)))); + send(Message.obtain(null, Medtronic640gActivity.Medtronic640gActivityHandler.MSG_ERROR, String.format("Before you can use the Contour Next Link, you need to register it with the app. Select '%s' from the menu.", getString(R.string.register_contour_next_link)))); return; } @@ -161,10 +161,10 @@ public class MedtronicCNLService extends AbstractService { cnlReader.requestReadInfo(); byte radioChannel = cnlReader.negotiateChannel(); if (radioChannel == 0) { - send(Message.obtain(null, Medtronic640gActivity.DexcomG4ActivityHandler.MSG_ERROR, "Could not communicate with the 640g. Are you near the pump?")); + send(Message.obtain(null, Medtronic640gActivity.Medtronic640gActivityHandler.MSG_ERROR, "Could not communicate with the 640g. Are you near the pump?")); Log.i(TAG, "Could not communicate with the 640g. Are you near the pump?"); } else { - send(Message.obtain(null, Medtronic640gActivity.DexcomG4ActivityHandler.MSG_STATUS, String.format("Connected to Contour Next Link on channel %d.", (int) radioChannel))); + send(Message.obtain(null, Medtronic640gActivity.Medtronic640gActivityHandler.MSG_STATUS, String.format("Connected to Contour Next Link on channel %d.", (int) radioChannel))); Log.d(TAG, String.format("Connected to Contour Next Link on channel %d.", (int) radioChannel)); cnlReader.beginEHSMSession(); @@ -174,32 +174,32 @@ public class MedtronicCNLService extends AbstractService { long pumpToUploaderTimeOffset = (new java.util.Date()).getTime() - Medtronic640gActivity.pumpStatusRecord.pumpDate.getTime(); writeData(cgmRecord); - send(Message.obtain(null, Medtronic640gActivity.DexcomG4ActivityHandler.MSG_DATA, cgmRecord)); + send(Message.obtain(null, Medtronic640gActivity.Medtronic640gActivityHandler.MSG_DATA, cgmRecord)); cnlReader.endEHSMSession(); } cnlReader.closeConnection(); } catch (UnexpectedMessageException e) { Log.e(TAG, "Unexpected Message", e); - send(Message.obtain(null, Medtronic640gActivity.DexcomG4ActivityHandler.MSG_ERROR, "Communication Error: " + e.getMessage())); + send(Message.obtain(null, Medtronic640gActivity.Medtronic640gActivityHandler.MSG_ERROR, "Communication Error: " + e.getMessage())); } finally { cnlReader.endPassthroughMode(); cnlReader.endControlMode(); } } catch (IOException e) { Log.e(TAG, "Error getting SGVs", e); - send(Message.obtain(null, Medtronic640gActivity.DexcomG4ActivityHandler.MSG_ERROR, "Error connecting to Contour Next Link.")); + send(Message.obtain(null, Medtronic640gActivity.Medtronic640gActivityHandler.MSG_ERROR, "Error connecting to Contour Next Link.")); } catch (ChecksumException e) { Log.e(TAG, "Checksum error", e); - send(Message.obtain(null, Medtronic640gActivity.DexcomG4ActivityHandler.MSG_ERROR, "Checksum error getting message from the Contour Next Link.")); + send(Message.obtain(null, Medtronic640gActivity.Medtronic640gActivityHandler.MSG_ERROR, "Checksum error getting message from the Contour Next Link.")); } catch (EncryptionException e) { Log.e(TAG, "Encryption exception", e); - send(Message.obtain(null, Medtronic640gActivity.DexcomG4ActivityHandler.MSG_ERROR, "Error decrypting messages from Contour Next Link.")); + send(Message.obtain(null, Medtronic640gActivity.Medtronic640gActivityHandler.MSG_ERROR, "Error decrypting messages from Contour Next Link.")); } catch (TimeoutException e) { Log.e(TAG, "Timeout communicating with Contour", e); - send(Message.obtain(null, Medtronic640gActivity.DexcomG4ActivityHandler.MSG_ERROR, "Timeout communicating with the Contour Next Link.")); + send(Message.obtain(null, Medtronic640gActivity.Medtronic640gActivityHandler.MSG_ERROR, "Timeout communicating with the Contour Next Link.")); } catch (UnexpectedMessageException e) { Log.e(TAG, "Unexpected Message", e); - send(Message.obtain(null, Medtronic640gActivity.DexcomG4ActivityHandler.MSG_ERROR, "Could not close connection: " + e.getMessage())); + send(Message.obtain(null, Medtronic640gActivity.Medtronic640gActivityHandler.MSG_ERROR, "Could not close connection: " + e.getMessage())); } // TODO - add retries. @@ -207,7 +207,7 @@ public class MedtronicCNLService extends AbstractService { String title = "Cannot upload data"; String msg = "Please check that you're connected to the Internet"; //showNotification(title, msg); - send(Message.obtain(null, Medtronic640gActivity.DexcomG4ActivityHandler.MSG_ERROR, title + "\n" + msg)); + send(Message.obtain(null, Medtronic640gActivity.Medtronic640gActivityHandler.MSG_ERROR, title + "\n" + msg)); } else { mUploader.execute(cgmRecord); } diff --git a/app/src/main/java/info/nightscout/android/medtronic/service/TestService.java b/app/src/main/java/info/nightscout/android/medtronic/service/TestService.java deleted file mode 100644 index 0450bd1..0000000 --- a/app/src/main/java/info/nightscout/android/medtronic/service/TestService.java +++ /dev/null @@ -1,87 +0,0 @@ -package info.nightscout.android.medtronic.service; - -import android.app.Notification; -import android.app.NotificationManager; -import android.app.PendingIntent; -import android.content.Intent; -import android.os.Message; -import android.util.Log; - -import info.nightscout.android.R; -import info.nightscout.android.medtronic.Medtronic640gActivity; -import info.nightscout.android.service.AbstractService; - -import java.util.Timer; -import java.util.TimerTask; - -/** - * Created by lgoedhart on 25/03/2016. - */ -public class TestService extends AbstractService { - public static final int MSG_INCREMENT = 1; - public static final int MSG_COUNTER = 2; - public static final int MSG_STATUS = 3; - - private NotificationManager nm; - private Timer timer = new Timer(); - private int counter = 0, incrementby = 1; - - @Override - public void onStartService() { - showNotification(); - timer.scheduleAtFixedRate(new TimerTask() { - public void run() { - onTimerTick(); - } - }, 0, 250L); - } - - @Override - public void onStopService() { - if (timer != null) { - timer.cancel(); - } - counter = 0; - nm.cancel(getClass().getSimpleName().hashCode()); - Log.i("MyService", "Service Stopped."); - } - - @Override - public void onReceiveMessage(Message msg) { - if (msg.what == MSG_INCREMENT) { - incrementby = msg.arg1; - } - } - - private void showNotification() { - nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); - - // In this sample, we'll use the same text for the ticker and the expanded notification - // Set the icon, scrolling text and timestamp - // The PendingIntent to launch our activity if the user selects this notification - // Set the info for the views that show in the notification panel. - - String text = "Test service, yo"; - Notification notification = new Notification(R.drawable.ic_launcher, text, System.currentTimeMillis()); - PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, Medtronic640gActivity.class), 0); - notification.setLatestEventInfo(this, getClass().getSimpleName(), text, contentIntent); - - // Send the notification. - // We use a layout id because it is a unique number. We use it later to cancel. - - nm.notify(getClass().getSimpleName().hashCode(), notification); - } - - private void onTimerTick() { - //Log.i("TimerTick", "Timer doing work." + counter); - - try { - counter += incrementby; - - // Send data as simple integer - send(Message.obtain(null, MSG_COUNTER, counter, 0)); - } catch (Throwable t) { //you should always ultimately catch all exceptions in timer tasks. - Log.e("TimerTick", "Timer Tick Failed.", t); - } - } -} diff --git a/app/src/main/java/info/nightscout/android/upload/MedtronicPumpRecord.java b/app/src/main/java/info/nightscout/android/upload/MedtronicPumpRecord.java deleted file mode 100644 index 64c28c3..0000000 --- a/app/src/main/java/info/nightscout/android/upload/MedtronicPumpRecord.java +++ /dev/null @@ -1,250 +0,0 @@ -package info.nightscout.android.upload; - -import java.io.Serializable; - -import org.bson.Document; -import org.json.JSONException; -import org.json.JSONObject; - -public class MedtronicPumpRecord extends DeviceRecord implements Serializable{ - - /** - * - */ - private static final long serialVersionUID = -1857687174963206840L; - public float insulinLeft = -1; - public String status = "---"; - public String alarm = "---"; - public String temporaryBasal = "---"; - public String batteryStatus = "---"; - public String batteryVoltage = "---"; - public String model = "---"; - public String sRemoteControlID1 = "---";//Not used yet, I don not see the point of uploading this info. - public String sRemoteControlID2 = "---";//Not used yet, I don not see the point of uploading this info. - public String sRemoteControlID3 = "---";//Not used yet, I don not see the point of uploading this info. - public String sParadigmLink1 = "---";//Not used yet, I don not see the point of uploading this info. - public String sParadigmLink2 = "---";//Not used yet, I don not see the point of uploading this info. - public String sParadigmLink3 = "---";//Not used yet, I don not see the point of uploading this info. - public String sSensorID = "---";//Not used yet, I don not see the point of uploading this info. - public boolean isWarmingUp = false; - public void setWarmingUp(boolean isWarmingUp) { - this.isWarmingUp = isWarmingUp; - } - - public void setBatteryStatus(String batteryStatus) { - this.batteryStatus = batteryStatus; - } - public void setBatteryVoltage(String batteryVoltage) { - this.batteryVoltage = batteryVoltage; - } - public MedtronicPumpRecord(){ - this.deviceName = "Medtronic pump"; - } - public void setStatus(String status) { - this.status = status; - } - - public void setAlarm(String alarm) { - this.alarm = alarm; - } - - public void setTemporaryBasal(String temporaryBasal) { - this.temporaryBasal = temporaryBasal; - } - - public void setInsulinLeft(float insulinLeft) { - this.insulinLeft = insulinLeft; - } - - public void setModel(String model) { - this.model = model; - } - - public void setsRemoteControlID1(String sRemoteControlID1) { - this.sRemoteControlID1 = sRemoteControlID1; - } - public void setsRemoteControlID2(String sRemoteControlID2) { - this.sRemoteControlID2 = sRemoteControlID2; - } - public void setsRemoteControlID3(String sRemoteControlID3) { - this.sRemoteControlID3 = sRemoteControlID3; - } - public void setsParadigmLink1(String sParadigmLink1) { - this.sParadigmLink1 = sParadigmLink1; - } - public void setsParadigmLink2(String sParadigmLink2) { - this.sParadigmLink2 = sParadigmLink2; - } - public void setsParadigmLink3(String sParadigmLink3) { - this.sParadigmLink3 = sParadigmLink3; - } - public void setsSensorID(String sSensorID) { - this.sSensorID = sSensorID; - } - public void mergeCurrentWithDBObject(Document previousRecord){ - if (!previousRecord.containsKey("insulinLeft") || insulinLeft > 0){ - previousRecord.put("insulinLeft", insulinLeft); - } - if (!previousRecord.containsKey("status") || !("---".equals(status))){ - previousRecord.put("status", status); - } - if (!previousRecord.containsKey("alarm") || !("---".equals(alarm))){ - previousRecord.put("alarm", alarm); - } - if (!previousRecord.containsKey("temporaryBasal") || !("---".equals(temporaryBasal))){ - previousRecord.put("temporaryBasal", temporaryBasal); - } - if (!previousRecord.containsKey("batteryStatus") || !("---".equals(batteryStatus))){ - previousRecord.put("batteryStatus", batteryStatus); - } - if (!previousRecord.containsKey("batteryVoltage") || !("---".equals(batteryVoltage))){ - previousRecord.put("batteryVoltage", batteryVoltage); - } - if (!previousRecord.containsKey("model") || !("---".equals(model))){ - previousRecord.put("model", model); - } - if (!previousRecord.containsKey("sRemoteControlID1") || !("---".equals(sRemoteControlID1))){ - previousRecord.put("sRemoteControlID1", sRemoteControlID1); - } - if (!previousRecord.containsKey("sRemoteControlID2") || !("---".equals(sRemoteControlID2))){ - previousRecord.put("sRemoteControlID2", sRemoteControlID2); - } - if (!previousRecord.containsKey("sRemoteControlID3") || !("---".equals(sRemoteControlID3))){ - previousRecord.put("sRemoteControlID3", sRemoteControlID3); - } - if (!previousRecord.containsKey("sParadigmLink1") || !("---".equals(sParadigmLink1))){ - previousRecord.put("sParadigmLink1", sParadigmLink1); - } - if (!previousRecord.containsKey("sParadigmLink2") || !("---".equals(sParadigmLink2))){ - previousRecord.put("sParadigmLink2", sParadigmLink2); - } - if (!previousRecord.containsKey("sParadigmLink3") || !("---".equals(sParadigmLink3))){ - previousRecord.put("sParadigmLink3", sParadigmLink3); - } - if (!("---".equals(sSensorID)) || (!previousRecord.containsKey("sSensorID"))){ - previousRecord.put("sSensorID", sSensorID); - } - previousRecord.put("isWarmingUp", isWarmingUp); - } - public void mergeCurrentWithDBObject(JSONObject previousRecord){ - try { - if (!previousRecord.has("insulinLeft") || insulinLeft > 0){ - previousRecord.put("insulinLeft", insulinLeft); - } - }catch (Exception e) { - - } - if (!previousRecord.has("status") || !("---".equals(status))){ - try { - previousRecord.put("status", status); - } catch (JSONException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - if (!previousRecord.has("alarm") || !("---".equals(alarm))){ - try { - previousRecord.put("alarm", alarm); - } catch (JSONException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - if (!previousRecord.has("temporaryBasal") || !("---".equals(temporaryBasal))){ - try { - previousRecord.put("temporaryBasal", temporaryBasal); - } catch (JSONException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - if (!previousRecord.has("batteryStatus") || !("---".equals(batteryStatus))){ - try { - previousRecord.put("batteryStatus", batteryStatus); - } catch (JSONException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - if (!previousRecord.has("batteryVoltage") || !("---".equals(batteryVoltage))){ - try { - previousRecord.put("batteryVoltage", batteryVoltage); - } catch (JSONException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - if (!previousRecord.has("model") || !("---".equals(model))){ - try { - previousRecord.put("model", model); - } catch (JSONException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - if (!previousRecord.has("sRemoteControlID1") || !("---".equals(sRemoteControlID1))){ - try { - previousRecord.put("sRemoteControlID1", sRemoteControlID1); - } catch (JSONException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - if (!previousRecord.has("sRemoteControlID2") || !("---".equals(sRemoteControlID2))){ - try { - previousRecord.put("sRemoteControlID2", sRemoteControlID2); - } catch (JSONException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - if (!previousRecord.has("sRemoteControlID3") || !("---".equals(sRemoteControlID3))){ - try { - previousRecord.put("sRemoteControlID3", sRemoteControlID3); - } catch (JSONException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - if (!previousRecord.has("sParadigmLink1") || !("---".equals(sParadigmLink1))){ - try { - previousRecord.put("sParadigmLink1", sParadigmLink1); - } catch (JSONException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - if (!previousRecord.has("sParadigmLink2") || !("---".equals(sParadigmLink2))){ - try { - previousRecord.put("sParadigmLink2", sParadigmLink2); - } catch (JSONException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - if (!previousRecord.has("sParadigmLink3") || !("---".equals(sParadigmLink3))){ - try { - previousRecord.put("sParadigmLink3", sParadigmLink3); - } catch (JSONException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - if (!("---".equals(sSensorID)) || (!previousRecord.has("sSensorID"))){ - try { - previousRecord.put("sSensorID", sSensorID); - } catch (JSONException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - try { - previousRecord.put("isWarmingUp", isWarmingUp); - } catch (JSONException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - -} diff --git a/app/src/main/java/info/nightscout/android/upload/MedtronicSensorRecord.java b/app/src/main/java/info/nightscout/android/upload/MedtronicSensorRecord.java deleted file mode 100644 index 29d5546..0000000 --- a/app/src/main/java/info/nightscout/android/upload/MedtronicSensorRecord.java +++ /dev/null @@ -1,35 +0,0 @@ -package info.nightscout.android.upload; - -import info.nightscout.android.dexcom.EGVRecord; -import info.nightscout.android.medtronic.MedtronicConstants; - -public class MedtronicSensorRecord extends EGVRecord { - /** - * - */ - private static final long serialVersionUID = 7653259513544666489L; - - public float isig = 0; - public float calibrationFactor = 0; - public int calibrationStatus = MedtronicConstants.WITHOUT_ANY_CALIBRATION; - public float unfilteredGlucose = 0; - public boolean isCalibrating = false; - public long displayDateTime = 0; - - - public void setIsig(float isig) { - this.isig = isig; - } - public void setCalibrationFactor(float calibrationFactor) { - this.calibrationFactor = calibrationFactor; - } - public void setCalibrationStatus(int calibrationStatus) { - this.calibrationStatus = calibrationStatus; - } - public void setUnfilteredGlucose(float unfilteredGlucose) { - this.unfilteredGlucose = unfilteredGlucose; - } - public long getDisplayDateTime() { - return displayDateTime; - } -} diff --git a/app/src/main/java/info/nightscout/android/upload/UploadHelper.java b/app/src/main/java/info/nightscout/android/upload/UploadHelper.java index 3fd0917..f5b720c 100644 --- a/app/src/main/java/info/nightscout/android/upload/UploadHelper.java +++ b/app/src/main/java/info/nightscout/android/upload/UploadHelper.java @@ -3,29 +3,10 @@ package info.nightscout.android.upload; import android.content.Context; import android.content.SharedPreferences; import android.os.AsyncTask; -import android.os.Bundle; -import android.os.Message; import android.os.Messenger; -import android.os.RemoteException; import android.preference.PreferenceManager; import android.util.Log; -import com.mongodb.MongoClient; -import com.mongodb.MongoClientOptions; -import com.mongodb.MongoClientOptions.Builder; -import com.mongodb.MongoCredential; -import com.mongodb.ServerAddress; -import com.mongodb.client.MongoCollection; -import com.mongodb.client.MongoCursor; -import com.mongodb.client.MongoDatabase; - -import info.nightscout.android.R; -import info.nightscout.android.medtronic.Medtronic640gActivity; -import info.nightscout.android.dexcom.EGVRecord; -import info.nightscout.android.medtronic.MedtronicConstants; -import info.nightscout.android.medtronic.MedtronicReader; -import info.nightscout.android.upload.MedtronicNG.CGMRecord; - import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; @@ -39,7 +20,6 @@ import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; -import org.bson.Document; import org.json.JSONArray; import org.json.JSONObject; import org.slf4j.LoggerFactory; @@ -51,24 +31,23 @@ import java.io.InputStreamReader; import java.net.URI; import java.net.URISyntaxException; import java.security.MessageDigest; -import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; -import java.util.HashMap; -import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern; import ch.qos.logback.classic.Logger; - -import static com.mongodb.client.model.Filters.eq; +import info.nightscout.android.R; +import info.nightscout.android.medtronic.Medtronic640gActivity; +import info.nightscout.android.medtronic.MedtronicConstants; +import info.nightscout.android.upload.MedtronicNG.CGMRecord; public class UploadHelper extends AsyncTask<Record, Integer, Long> { - private Logger log = (Logger) LoggerFactory.getLogger(MedtronicReader.class.getName()); + private Logger log = (Logger) LoggerFactory.getLogger(UploadHelper.class.getName()); private static final String TAG = "DexcomUploadHelper"; private SharedPreferences settings = null;// common application preferences private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss aa", Locale.getDefault()); @@ -76,31 +55,19 @@ public class UploadHelper extends AsyncTask<Record, Integer, Long> { private static final int CONNECTION_TIMEOUT = 30 * 1000; Context context; - private int cgmSelected = Medtronic640gActivity.DEXCOMG4; - private ArrayList<Messenger> mClients; + private int cgmSelected = Medtronic640gActivity.CNL_24; private List<JSONObject> recordsNotUploadedList = new ArrayList<JSONObject>(); private List<JSONObject> recordsNotUploadedListJson = new ArrayList<JSONObject>(); - public String dbURI = null; - public String collectionName = null; - public String dsCollectionName = null; - public String gdCollectionName = null; - public String devicesCollectionName = "devices"; - public MongoDatabase db = null; - public MongoCollection<Document> dexcomData = null; - public MongoCollection<Document> glucomData = null; - public MongoCollection<Document> deviceData = null; - public MongoCollection<Document> dsCollection = null; - public static Boolean isModifyingRecords = false; + public static final Object isModifyingRecordsLock = new Object(); - private MongoClient client = null; + public UploadHelper(Context context) { - this(context, Medtronic640gActivity.DEXCOMG4); + this(context, Medtronic640gActivity.CNL_24); } public UploadHelper(Context context, int cgmSelected) { this.context = context; - this.cgmSelected = cgmSelected; - this.mClients = null; + this.cgmSelected = cgmSelected; settings = context.getSharedPreferences(MedtronicConstants.PREFS_NAME, 0); synchronized (isModifyingRecordsLock) { try { @@ -151,87 +118,7 @@ public class UploadHelper extends AsyncTask<Record, Integer, Long> { public UploadHelper(Context context, int cgmSelected, ArrayList<Messenger> mClients) { this(context, cgmSelected); - this.mClients = mClients; } - /** - * Sends a message to reconnect to mongo - */ - private void sendRefreshDBConnToUI() { - if (mClients != null && mClients.size() > 0){ - for (int i=mClients.size()-1; i>=0; i--) { - try { - Message mSend = null; - mSend = Message.obtain(null, MedtronicConstants.MSG_REFRESH_DB_CONNECTION); - mClients.get(i).send(mSend); - } catch (RemoteException e) { - // The client is dead. Remove it from the list; we are going through the list from back to front so this is safe to do inside the loop. - mClients.remove(i); - } - } - } - } - - - - /** - * Sends a message to be printed in the display (DEBUG) - * @param valuetosend - * @param clear, if true, the display is cleared before printing "valuetosend" - */ - private void sendMessageToUI(String valuetosend, boolean clear) { - if (mClients != null && mClients.size() > 0){ - for (int i=mClients.size()-1; i>=0; i--) { - try { - Message mSend = null; - if (clear){ - mSend = Message.obtain(null, MedtronicConstants.MSG_MEDTRONIC_CGM_CLEAR_DISPLAY); - mClients.get(i).send(mSend); - continue; - } - mSend = Message.obtain(null, MedtronicConstants.MSG_MEDTRONIC_CGM_MESSAGE_RECEIVED); - Bundle b = new Bundle(); - b.putString("data", valuetosend); - mSend.setData(b); - mClients.get(i).send(mSend); - - } catch (RemoteException e) { - // The client is dead. Remove it from the list; we are going through the list from back to front so this is safe to do inside the loop. - mClients.remove(i); - } - } - } - } - - /** - * Sends an error message to be printed in the display (DEBUG) if it is repeated, It is not printed again. If UI is not visible, It will launch a pop-up message. - * @param valuetosend - */ - private void sendErrorMessageToUI(String valuetosend) { - Log.e("medtronicCGMService", valuetosend); - log.error("Send Error Message to UI "+ valuetosend); - if (mClients != null && mClients.size() > 0) { - for (int i = mClients.size() - 1; i >= 0; i--) { - try { - Message mSend = null; - mSend = Message - .obtain(null, - MedtronicConstants.MSG_MEDTRONIC_CGM_ERROR_RECEIVED); - Bundle b = new Bundle(); - b.putString("data", valuetosend); - mSend.setData(b); - mClients.get(i).send(mSend); - - } catch (RemoteException e) { - // The client is dead. Remove it from the list; we are going - // through the list from back to front so this is safe to do - // inside the loop. - mClients.remove(i); - } - } - } - } - - private JSONArray doGetRequest(HttpClient client, String url, String filter, String sort, String limit, String apiKey){ JSONArray result = null; @@ -339,19 +226,7 @@ public class UploadHelper extends AsyncTask<Record, Integer, Long> { } return true; } - - /** - * - * @return constant String to identify the selected Device - */ - private String getSelectedDeviceName(){ - switch (cgmSelected){ - case Medtronic640gActivity.MEDTRONIC_CGM: - return "Medtronic_CGM"; - default: - return "dexcom"; - } - } + /** * doInBackground */ @@ -359,7 +234,6 @@ public class UploadHelper extends AsyncTask<Record, Integer, Long> { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this.context); Boolean enableRESTUpload = prefs.getBoolean("EnableRESTUpload", false); - Boolean enableMongoUpload = prefs.getBoolean("EnableMongoUpload", false); try{ if (enableRESTUpload) { long start = System.currentTimeMillis(); @@ -368,23 +242,7 @@ public class UploadHelper extends AsyncTask<Record, Integer, Long> { doRESTUpload(prefs, records); Log.i(TAG, String.format("Finished upload of %s record using a REST API in %s ms", records.length, System.currentTimeMillis() - start)); log.info(String.format("Finished upload of %s record using a REST API in %s ms", records.length, System.currentTimeMillis() - start)); - }else if (enableMongoUpload) { - if (!prefs.getBoolean("isMongoRest", false)){ - long start = System.currentTimeMillis(); - Log.i(TAG, String.format("Starting upload of %s record using Mongo", records.length)); - log.info(String.format("Starting upload of %s record using Mongo "+dbURI, records.length)); - doMongoUpload(prefs, records); - Log.i(TAG, String.format("Finished upload of %s record using a Mongo in %s ms", records.length, System.currentTimeMillis() - start)); - log.info(String.format("Finished upload of %s record using a Mongo in %s ms", records.length, System.currentTimeMillis() - start)); - } else { - long start = System.currentTimeMillis(); - Log.i(TAG, String.format("Starting upload of %s record using Mongo", records.length)); - log.info(String.format("Starting upload of %s record using Mongo "+dbURI, records.length)); - doMongoRestUpload(prefs, records); - Log.i(TAG, String.format("Finished upload of %s record using a Mongo in %s ms", records.length, System.currentTimeMillis() - start)); - log.info(String.format("Finished upload of %s record using a Mongo in %s ms", records.length, System.currentTimeMillis() - start)); - } - } + } }catch(Exception e){ log.error("ERROR uploading data!!!!!", e); } @@ -437,7 +295,7 @@ public class UploadHelper extends AsyncTask<Record, Integer, Long> { log.error("Unable to do REST API Upload to: " + uploadUrl, e); } } - @SuppressWarnings({ "rawtypes", "unchecked" }) + private void doRESTUploadTo(String baseURI, Record[] records) { Integer typeSaved = null; try { @@ -555,9 +413,6 @@ public class UploadHelper extends AsyncTask<Record, Integer, Long> { if (record instanceof GlucometerRecord){ typeSaved = 0; postURL += "entries"; - }else if (record instanceof MedtronicPumpRecord){ - typeSaved = 3; - postURL += "deviceentries"; }else{ typeSaved = 0; postURL += "entries"; @@ -593,10 +448,7 @@ public class UploadHelper extends AsyncTask<Record, Integer, Long> { JSONObject json = new JSONObject(); try { - if (apiVersion >= 1) - populateV1APIEntry(json, record); - else - populateLegacyAPIEntry(json, record); + populateV1APIEntry(json, record); } catch (Exception e) { Log.w(TAG, "Unable to populate entry, apiVersion: " + apiVersion, e); log.warn("Unable to populate entry, apiVersion: " + apiVersion, e); @@ -679,7 +531,6 @@ public class UploadHelper extends AsyncTask<Record, Integer, Long> { } } - @SuppressWarnings({ "rawtypes", "unchecked" }) private void postDeviceStatus(String baseURL, DefaultHttpClient httpclient) throws Exception { String devicestatusURL = baseURL + "devicestatus"; Log.i(TAG, "devicestatusURL: " + devicestatusURL); @@ -726,75 +577,15 @@ public class UploadHelper extends AsyncTask<Record, Integer, Long> { json.put("date", date.getTime()); } - if (oRecord instanceof GlucometerRecord) { - json.put("gdValue", ((GlucometerRecord) oRecord).numGlucometerValue); - json.put("device", getSelectedDeviceName()); - json.put("type", "mbg"); - json.put("mbg", ((GlucometerRecord) oRecord).numGlucometerValue); - }else if (oRecord instanceof CGMRecord){ + if (oRecord instanceof CGMRecord){ CGMRecord pumpRecord = (CGMRecord) oRecord; json.put("sgv", pumpRecord.sgv); json.put("direction", pumpRecord.direction); json.put("device", pumpRecord.getDeviceName()); json.put("type", "sgv"); - }else if (oRecord instanceof EGVRecord){ - EGVRecord record = (EGVRecord) oRecord; - json.put("device", getSelectedDeviceName()); - json.put("sgv", Integer.parseInt(record.bGValue)); - json.put("direction", record.trend); - if (cgmSelected == Medtronic640gActivity.MEDTRONIC_CGM && (oRecord instanceof MedtronicSensorRecord)){ - json.put("isig", ((MedtronicSensorRecord)record).isig); - json.put("calibrationFactor", ((MedtronicSensorRecord)record).calibrationFactor); - json.put("calibrationStatus", ((MedtronicSensorRecord)record).calibrationStatus); - json.put("unfilteredGlucose", ((MedtronicSensorRecord)record).unfilteredGlucose); - json.put("isCalibrating", ((MedtronicSensorRecord)record).isCalibrating); - } - }else if (oRecord instanceof MedtronicPumpRecord){ - MedtronicPumpRecord pumpRecord = (MedtronicPumpRecord) oRecord; - json.put("name", pumpRecord.getDeviceName()); - json.put("deviceId", pumpRecord.deviceId); - json.put("insulinLeft", pumpRecord.insulinLeft); - json.put("alarm", pumpRecord.alarm); - json.put("status", pumpRecord.status); - json.put("temporaryBasal", pumpRecord.temporaryBasal); - json.put("batteryStatus", pumpRecord.batteryStatus); - json.put("batteryVoltage", pumpRecord.batteryVoltage); - json.put("isWarmingUp", pumpRecord.isWarmingUp); } - } - private void populateLegacyAPIEntry(JSONObject json, Record oRecord) throws Exception { - Date date = DATE_FORMAT.parse(oRecord.displayTime); - json.put("timestamp", date.getTime()); - - if (oRecord instanceof GlucometerRecord){ - json.put("gdValue", ((GlucometerRecord)oRecord).numGlucometerValue); - }else if (oRecord instanceof EGVRecord){ - EGVRecord record = (EGVRecord) oRecord; - json.put("device", getSelectedDeviceName()); - json.put("sgv", Integer.parseInt(record.bGValue)); - json.put("direction", record.trend); - if (cgmSelected == Medtronic640gActivity.MEDTRONIC_CGM && (oRecord instanceof MedtronicSensorRecord)){ - json.put("isig", ((MedtronicSensorRecord)record).isig); - json.put("calibrationFactor", ((MedtronicSensorRecord)record).calibrationFactor); - json.put("calibrationStatus", ((MedtronicSensorRecord)record).calibrationStatus); - json.put("unfilteredGlucose", ((MedtronicSensorRecord)record).unfilteredGlucose); - json.put("isCalibrating", ((MedtronicSensorRecord)record).isCalibrating); - } - }else if (oRecord instanceof MedtronicPumpRecord){ - MedtronicPumpRecord pumpRecord = (MedtronicPumpRecord) oRecord; - json.put("name", pumpRecord.getDeviceName()); - json.put("deviceId", pumpRecord.deviceId); - json.put("insulinLeft", pumpRecord.insulinLeft); - json.put("alarm", pumpRecord.alarm); - json.put("status", pumpRecord.status); - json.put("temporaryBasal", pumpRecord.temporaryBasal); - json.put("batteryStatus", pumpRecord.batteryStatus); - json.put("batteryVoltage", pumpRecord.batteryVoltage); - json.put("isWarmingUp", pumpRecord.isWarmingUp); - } - } private static String convertStreamToString(InputStream is) { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); @@ -816,712 +607,5 @@ public class UploadHelper extends AsyncTask<Record, Integer, Long> { } return sb.toString(); } - - private void doMongoRestUpload(SharedPreferences prefs, Record...records) { - HttpParams params = new BasicHttpParams(); - //HttpConnectionParams.setSoTimeout(params, 60000); - HttpConnectionParams.setConnectionTimeout(params, 60000); - DefaultHttpClient httpclient = new DefaultHttpClient(params); - String dbName = ""; - String[] splitted = dbURI.split(":"); - if (splitted.length >= 4 ){ - dbName = prefs.getString("dbName", ""); - } - String entriesUrl = "/api/1/databases/"+dbName + "/collections/"+collectionName; - String deviceStatusUrl = "/api/1/databases/"+dbName + "/collections/"+devicesCollectionName; - String gdCollectionUrl = "/api/1/databases/"+dbName + "/collections/"+gdCollectionName; - String dsCollectioncUrl = "/api/1/databases/"+dbName + "/collections/"+dsCollectionName; - String apiKey = prefs.getString("apiKey", "aaaaa"); - String filter = "q={'type':{$ne:'mbg'}}&"; - String sort = "s={'date':-1}&"; - String limit = "l=1&"; - JSONObject testData = null; - URI nUri = null; - try { - nUri = new URI("https", null, "api.mongolab.com", 443, entriesUrl, filter + sort + limit + "apiKey="+apiKey,null); - } catch (URISyntaxException e2) { - // TODO Auto-generated catch block - e2.printStackTrace(); - } - //URIUtils. - HttpGet getRequest = new HttpGet(nUri); - HttpPost postRequest = null; - if (recordsNotUploadedList.size() > 0){ - Log.i(TAG, "The number of not uploaded EGV records to retry " + recordsNotUploadedList.size()); - log.warn("The number of not uploaded EGV records to retry " + recordsNotUploadedList.size()); - List<JSONObject> auxList = new ArrayList<JSONObject>(recordsNotUploadedList); - recordsNotUploadedList = new ArrayList<JSONObject>(); - for (int i = 0; i < auxList.size(); i++){ - try{ - JSONObject ob = auxList.get(i); - if (ob != null){ - Iterator<String> keys = ob.keys(); - boolean atLeastOne= false; - testData = new JSONObject(); - while (keys.hasNext()){ - String key = keys.next(); - if (ob.get(key) != null){ - testData.put(key, ob.get(key)); - atLeastOne = true; - } - } - if (atLeastOne){ - doPostRequest(httpclient, entriesUrl, apiKey, testData); - } - } - }catch(IllegalArgumentException ex){ - log.error("UploaderHelper", "Illegal record"); - }catch (Exception e){ - Log.e("UploaderHelper", "The retried can't be uploaded"); - log.error("The retried record can't be uploaded ", e); - sendErrorMessageToUI("Error retrying the upload of a stored mongo record "+ e.getLocalizedMessage()); - try { - if (recordsNotUploadedList.size() > 49){ - recordsNotUploadedList.remove(0); - recordsNotUploadedList.add(49, new JSONObject(testData.toString())); - }else{ - recordsNotUploadedList.add(new JSONObject(testData.toString())); - } - } catch (Exception e2) { - // TODO: handle exception - } - - } - } - } - - Log.i(TAG, "The number of EGV records being sent to MongoDB is " + records.length); - log.info("The number of EGV records being sent to MongoDB is " + records.length); - Boolean isWarmingUp = false; - Boolean recordsTry = false; - Integer typeSaved = 0; - for (Record oRecord : records) { - recordsTry = true; - try{ - testData = new JSONObject(); - Date date = DATE_FORMAT.parse(oRecord.displayTime); - testData.put("date", date.getTime()); - testData.put("dateString", oRecord.displayTime); - typeSaved = null; - if (oRecord instanceof EGVRecord){ - EGVRecord record = (EGVRecord) oRecord; - // make db object - testData.put("device", getSelectedDeviceName()); - testData.put("sgv", record.bGValue); - testData.put("type", "sgv"); - testData.put("direction", record.trend); - typeSaved = 0; - if (cgmSelected == Medtronic640gActivity.MEDTRONIC_CGM && (oRecord instanceof MedtronicSensorRecord)){ - typeSaved = 1; - testData.put("isig", ((MedtronicSensorRecord)record).isig); - testData.put("calibrationFactor", ((MedtronicSensorRecord)record).calibrationFactor); - testData.put("calibrationStatus", ((MedtronicSensorRecord)record).calibrationStatus); - testData.put("unfilteredGlucose", ((MedtronicSensorRecord)record).unfilteredGlucose); - testData.put("isCalibrating", ((MedtronicSensorRecord)record).isCalibrating); - log.info("Testing isCheckedWUP -->", prefs.getBoolean("isCheckedWUP", false)); - if (!prefs.getBoolean("isCheckedWUP", false)){ - log.info("Testing isCheckedWUP -->GET INTO"); - MedtronicPumpRecord pumpRecord = new MedtronicPumpRecord(); - JSONArray previousRecordCursor = doGetRequest(httpclient, deviceStatusUrl, "q={'deviceId':{$eq:'"+prefs.getString("medtronic_cgm_id", "")+"'}}", null, null, apiKey); - if (previousRecordCursor != null && previousRecordCursor.length() > 0){ - JSONObject previousRecord = previousRecordCursor.getJSONObject(0); - previousRecord.put("date", testData.get("date")); - previousRecord.put("dateString", testData.get("dateString")); - JSONObject job = new JSONObject(previousRecord.toString()); - isWarmingUp = job.getBoolean("isWarmingUp"); - log.info("Testing isCheckedWUP -->NEXT -->ISWUP?? "+ isWarmingUp); - if (isWarmingUp){ - pumpRecord.mergeCurrentWithDBObject(previousRecord); - log.info("Uploading a DeviceRecord"); - filter = "q={'_id':{$eq:'"+previousRecord.get("_id")+"'}}"; - doPutRequest(httpclient, deviceStatusUrl, filter, apiKey, previousRecord); - prefs.edit().putBoolean("isCheckedWUP", true).commit(); - } - } - } - } - log.info("Uploading a EGVRecord"); - boolean result = doPostRequest(httpclient, entriesUrl, apiKey, testData); - if (!result) { - throw new Exception("Error uploading record "); - } - }else if (oRecord instanceof GlucometerRecord){ - typeSaved = 2; - GlucometerRecord gdRecord = (GlucometerRecord) oRecord; - - testData.put("gdValue", gdRecord.numGlucometerValue); - log.info("Uploading a GlucometerRecord"); - if (gdCollectionName != null && gdCollectionName.length() > 0) - doPostRequest(httpclient, gdCollectionUrl, apiKey, testData); - - testData.put("device", getSelectedDeviceName()); - testData.put("type", "mbg"); - testData.put("mbg", gdRecord.numGlucometerValue); - log.info("Uploading a Glucometer Record!"); - doPostRequest(httpclient, entriesUrl, apiKey, testData); - - }else if (oRecord instanceof MedtronicPumpRecord){ - typeSaved = 3; - MedtronicPumpRecord pumpRecord = (MedtronicPumpRecord) oRecord; - filter = "q={'deviceId':{$eq:'"+pumpRecord.deviceId+"'}}"; - JSONArray previousRecordCursor = doGetRequest(httpclient, deviceStatusUrl, filter, null, "1", apiKey); - if (previousRecordCursor != null && previousRecordCursor.length() > 0){ - JSONObject previousRecord = previousRecordCursor.getJSONObject(0); - previousRecord.put("date", testData.get("date")); - previousRecord.put("dateString", testData.get("dateString")); - isWarmingUp = pumpRecord.isWarmingUp; - pumpRecord.mergeCurrentWithDBObject(previousRecord); - log.info("Uploading a DeviceRecord"); - filter = "q={'_id':{$eq:'"+previousRecord.get("_id")+"'}}"; - doPutRequest(httpclient, deviceStatusUrl, filter, apiKey, previousRecord); - }else{ - testData.put("name", pumpRecord.getDeviceName()); - testData.put("deviceId", pumpRecord.deviceId); - testData.put("insulinLeft", pumpRecord.insulinLeft); - testData.put("alarm", pumpRecord.alarm); - testData.put("status", pumpRecord.status); - testData.put("temporaryBasal", pumpRecord.temporaryBasal); - testData.put("batteryStatus", pumpRecord.batteryStatus); - testData.put("batteryVoltage", pumpRecord.batteryVoltage); - isWarmingUp = pumpRecord.isWarmingUp; - testData.put("isWarmingUp", pumpRecord.isWarmingUp); - log.info("Uploading a DeviceRecord"); - doPostRequest(httpclient, deviceStatusUrl, apiKey, testData); - } - } - }catch(IllegalArgumentException ex){ - Log.e("UploaderHelper", "Illegal record"); - }catch(Exception ex2){ - sendErrorMessageToUI("Error uploading mongo record "+ ex2.getLocalizedMessage()); - if ((typeSaved != null && (typeSaved == 0 ||typeSaved == 1 ))){//Only EGV records are important enough. - sendErrorMessageToUI("It is a SGV record, I am going to store it and retry the upload later."); - if (isWarmingUp){ - prefs.edit().putBoolean("isCheckedWUP", false); - } - log.warn("added to records not uploaded"); - try { - if (recordsNotUploadedList.size() > 49){ - recordsNotUploadedList.remove(0); - recordsNotUploadedList.add(49, new JSONObject(testData.toString())); - }else{ - recordsNotUploadedList.add(new JSONObject(testData.toString())); - } - } catch (Exception e) { - // TODO: handle exception - } - - }else if (typeSaved == 3){ - prefs.edit().putBoolean("isWarmingUp", isWarmingUp); - } - Log.w(TAG, "Unable to upload data to mongo in loop"); - log.warn("Unable to upload data to mongo in loop"); - } - } - try{ - //Uploading devicestatus - boolean update = true; - if (prefs.contains("lastBatteryUpdated")){ - long lastTimeUpdated = prefs.getLong("lastBatteryUpdated", 0); - if (lastTimeUpdated > 0){ - long current = System.currentTimeMillis(); - long diff = current - lastTimeUpdated; - if (diff < MedtronicConstants.TIME_5_MIN_IN_MS) - update = false; - else{ - SharedPreferences.Editor editor = prefs.edit(); - editor.putLong("lastBatteryUpdated", current); - editor.commit(); - } - }else{ - SharedPreferences.Editor editor = prefs.edit(); - editor.putLong("lastBatteryUpdated", System.currentTimeMillis()); - editor.commit(); - } - }else{ - SharedPreferences.Editor editor = prefs.edit(); - editor.putLong("lastBatteryUpdated", System.currentTimeMillis()); - editor.commit(); - } - if (update){ - JSONObject devicestatus = new JSONObject(); - devicestatus.put("uploaderBattery", Medtronic640gActivity.batLevel); - devicestatus.put("created_at", new Date()); - log.debug("Update Battery"); - doPostRequest(httpclient, dsCollectioncUrl, apiKey, devicestatus); - } - - } catch (Exception e) { - if (client != null){ - client.close(); - client = null; - } - Log.e(TAG, "Unable to upload battery data to mongo", e); - log.error("Unable to upload battery data to mongo", e); - StringBuffer sb1 = new StringBuffer(""); - sb1.append("EXCEPTION!!!!!! "+ e.getMessage()+" "+e.getCause()); - for (StackTraceElement st : e.getStackTrace()){ - sb1.append(st.toString()); - } - sendMessageToUI(sb1.toString(), false); - - } - - if (client != null){ - client.close(); - client = null; - } - if (recordsNotUploadedList.size() > 0){ - synchronized (isModifyingRecordsLock) { - try { - JSONArray recordsNotUploaded = new JSONArray(settings.getString("recordsNotUploaded","[]")); - if (recordsNotUploaded.length() > 0 && recordsNotUploaded.length() < recordsNotUploadedList.size()){ - for (int i = 0; i < recordsNotUploaded.length(); i++){ - if (recordsNotUploadedList.size() > 49){ - recordsNotUploadedList.remove(0); - recordsNotUploadedList.add(49, recordsNotUploaded.getJSONObject(i)); - }else{ - recordsNotUploadedList.add(recordsNotUploaded.getJSONObject(i)); - } - } - }else{ - for (int i = 0; i < recordsNotUploadedList.size(); i++){ - recordsNotUploaded.put(recordsNotUploadedList.get(i)); - } - recordsNotUploadedList.clear(); - int start = 0; - if (recordsNotUploaded.length() > 50){ - start = recordsNotUploaded.length() - 51; - } - for (int i = start; i < recordsNotUploaded.length(); i++){ - recordsNotUploadedList.add(recordsNotUploaded.getJSONObject(i)); - } - } - log.debug("retrieving older json records -->" +recordsNotUploaded.length()); - SharedPreferences.Editor editor = settings.edit(); - editor.remove("recordsNotUploaded"); - editor.commit(); - } catch (Exception e) { - log.debug("ERROR RETRIVING OLDER LISTs, I have lost them"); - SharedPreferences.Editor editor = settings.edit(); - if (settings.contains("recordsNotUploaded")) - editor.remove("recordsNotUploaded"); - editor.commit(); - } - JSONArray jsonArray = new JSONArray(recordsNotUploadedList); - SharedPreferences.Editor editor = settings.edit(); - editor.putString("recordsNotUploaded", jsonArray.toString()); - editor.commit(); - } - } - } - private void doMongoUpload(SharedPreferences prefs, Record... records) { - Integer typeSaved = null; - boolean recordsTry = false; - boolean refreshAsked = false; - if (dbURI != null) { - MongoCursor<Document> cursor = null; - Document testData = new Document(); - try { - // connect to db - Builder b = MongoClientOptions.builder(); - b.heartbeatConnectTimeout(150000); - b.heartbeatFrequency(120000); - b.heartbeatSocketTimeout(150000); - b.maxWaitTime(150000); - b.connectTimeout(150000); - boolean bAchieved = false; - String user = ""; - String password = ""; - String source = ""; - String host = ""; - String port = ""; - int iPort = -1; - if (dbURI.length() > 0){ - String[] splitted = dbURI.split(":"); - if (splitted.length >= 4 ){ - user = splitted[1].substring(2); - if (splitted[2].indexOf("@") < 0) - bAchieved = false; - else{ - password = splitted[2].substring(0,splitted[2].indexOf("@")); - host = splitted[2].substring(splitted[2].indexOf("@")+1, splitted[2].length()); - if (splitted[3].indexOf("/") < 0) - bAchieved = false; - else{ - port = splitted[3].substring(0, splitted[3].indexOf("/")); - source = splitted[3].substring(splitted[3].indexOf("/")+1, splitted[3].length()); - try{ - iPort = Integer.parseInt(port); - }catch(Exception ne){ - iPort = -1; - } - if (iPort > -1) - bAchieved = true; - } - } - } - } - log.debug("Uri TO CHANGE user "+user+" host "+source+" password "+password); - if (bAchieved){ - log.debug("URI CHANGE Achieved"); - MongoCredential mc = MongoCredential.createMongoCRCredential(user, source , password.toCharArray()); - ServerAddress sa = new ServerAddress(host, iPort); - List<MongoCredential> lcredential = new ArrayList<MongoCredential>(); - lcredential.add(mc); - if (sa != null && sa.getHost() != null && sa.getHost().indexOf("localhost") < 0){ - client = new MongoClient(sa, lcredential, b.build()); - - } - } - - if (recordsNotUploadedList.size() > 0){ - Log.i(TAG, "The number of not uploaded EGV records to retry " + recordsNotUploadedList.size()); - log.warn("The number of not uploaded EGV records to retry " + recordsNotUploadedList.size()); - List<JSONObject> auxList = new ArrayList<JSONObject>(recordsNotUploadedList); - recordsNotUploadedList = new ArrayList<JSONObject>(); - for (int i = 0; i < auxList.size(); i++){ - try{ - JSONObject ob = auxList.get(i); - if (ob != null){ - Iterator<String> keys = ob.keys(); - boolean atLeastOne= false; - testData = new Document(); - while (keys.hasNext()){ - String key = keys.next(); - if (ob.get(key) != null){ - testData.put(key, ob.get(key)); - atLeastOne = true; - } - } - if (atLeastOne) - dexcomData.insertOne(testData); - } - }catch(IllegalArgumentException ex){ - log.error("UploaderHelper", "Illegal record"); - }catch (Exception e){ - Log.e("UploaderHelper", "The retried can't be uploaded"); - log.error("The retried record can't be uploaded ", e); - sendErrorMessageToUI("Error retrying the upload of a stored mongo record "+ e.getLocalizedMessage()); - if (recordsNotUploadedList.size() > 49){ - recordsNotUploadedList.remove(0); - recordsNotUploadedList.add(49, new JSONObject(testData.toJson())); - }else{ - recordsNotUploadedList.add(new JSONObject(testData.toJson())); - } - if (!refreshAsked){ - sendRefreshDBConnToUI(); - refreshAsked = true; - } - } - } - } - Log.i(TAG, "The number of EGV records being sent to MongoDB is " + records.length); - log.info("The number of EGV records being sent to MongoDB is " + records.length); - Boolean isWarmingUp = false; - for (Record oRecord : records) { - recordsTry = true; - try{ - testData = new Document(); - Date date = DATE_FORMAT.parse(oRecord.displayTime); - testData.put("date", date.getTime()); - testData.put("dateString", oRecord.displayTime); - typeSaved = null; - if (oRecord instanceof EGVRecord && dexcomData != null){ - EGVRecord record = (EGVRecord) oRecord; - // make db object - testData.put("device", getSelectedDeviceName()); - testData.put("sgv", record.bGValue); - testData.put("type", "sgv"); - testData.put("direction", record.trend); - typeSaved = 0; - if (cgmSelected == Medtronic640gActivity.MEDTRONIC_CGM && (oRecord instanceof MedtronicSensorRecord)){ - typeSaved = 1; - testData.put("isig", ((MedtronicSensorRecord)record).isig); - testData.put("calibrationFactor", ((MedtronicSensorRecord)record).calibrationFactor); - testData.put("calibrationStatus", ((MedtronicSensorRecord)record).calibrationStatus); - testData.put("unfilteredGlucose", ((MedtronicSensorRecord)record).unfilteredGlucose); - testData.put("isCalibrating", ((MedtronicSensorRecord)record).isCalibrating); - log.info("Testing isCheckedWUP -->", prefs.getBoolean("isCheckedWUP", false)); - if (!prefs.getBoolean("isCheckedWUP", false) && deviceData != null){ - log.info("Testing isCheckedWUP -->GET INTO"); - MedtronicPumpRecord pumpRecord = new MedtronicPumpRecord(); - cursor = deviceData.find(eq("deviceId",prefs.getString("medtronic_cgm_id", ""))).iterator(); - if (cursor.hasNext()){ - Document previousRecord = cursor.next(); - previousRecord.put("date", testData.get("date")); - previousRecord.put("dateString", testData.get("dateString")); - JSONObject job = new JSONObject(previousRecord.toJson()); - isWarmingUp = job.getBoolean("isWarmingUp"); - log.info("Testing isCheckedWUP -->NEXT -->ISWUP?? "+ isWarmingUp); - if (isWarmingUp){ - pumpRecord.mergeCurrentWithDBObject(previousRecord); - log.info("Uploading a DeviceRecord"); - deviceData.replaceOne(eq("_id", previousRecord.get("_id")), previousRecord); - prefs.edit().putBoolean("isCheckedWUP", true).commit(); - } - } - } - } - log.info("Uploading a EGVRecord"); - dexcomData.insertOne(testData); - }else if (oRecord instanceof GlucometerRecord && (glucomData != null || dexcomData != null)){ - typeSaved = 2; - GlucometerRecord gdRecord = (GlucometerRecord) oRecord; - if (glucomData != null){//To be deprecated - testData.put("gdValue", gdRecord.numGlucometerValue); - log.info("Uploading a GlucometerRecord"); - glucomData.insertOne(testData); - } - if (dexcomData != null){ - testData.put("device", getSelectedDeviceName()); - testData.put("type", "mbg"); - testData.put("mbg", gdRecord.numGlucometerValue); - log.info("Uploading a Glucometer Record!"); - dexcomData.insertOne(testData); - } - }else if (oRecord instanceof MedtronicPumpRecord && deviceData != null){ - typeSaved = 3; - MedtronicPumpRecord pumpRecord = (MedtronicPumpRecord) oRecord; - HashMap<String, Object> filter = new HashMap<String, Object>(); - filter.put("deviceId", pumpRecord.deviceId); - cursor = deviceData.find(eq("deviceId",pumpRecord.deviceId)).iterator(); - if (cursor.hasNext()){ - Document previousRecord = cursor.next(); - previousRecord.put("date", testData.get("date")); - previousRecord.put("dateString", testData.get("dateString")); - isWarmingUp = pumpRecord.isWarmingUp; - pumpRecord.mergeCurrentWithDBObject(previousRecord); - log.info("Uploading a DeviceRecord"); - deviceData.replaceOne(eq("_id", previousRecord.get("_id")), previousRecord); - }else{ - testData.put("name", pumpRecord.getDeviceName()); - testData.put("deviceId", pumpRecord.deviceId); - testData.put("insulinLeft", pumpRecord.insulinLeft); - testData.put("alarm", pumpRecord.alarm); - testData.put("status", pumpRecord.status); - testData.put("temporaryBasal", pumpRecord.temporaryBasal); - testData.put("batteryStatus", pumpRecord.batteryStatus); - testData.put("batteryVoltage", pumpRecord.batteryVoltage); - isWarmingUp = pumpRecord.isWarmingUp; - testData.put("isWarmingUp", pumpRecord.isWarmingUp); - log.info("Uploading a DeviceRecord"); - deviceData.insertOne(testData); - } - if (cursor != null) - cursor.close(); - } - }catch(IllegalArgumentException ex){ - Log.e("UploaderHelper", "Illegal record"); - if (cursor != null) - cursor.close(); - }catch(Exception ex2){ - sendErrorMessageToUI("Error uploading mongo record "+ ex2.getLocalizedMessage()); - if (cursor != null) - cursor.close(); - if ((typeSaved != null && (typeSaved == 0 ||typeSaved == 1 ))){//Only EGV records are important enough. - sendErrorMessageToUI("It is a SGV record, I am going to store it and retry the upload later."); - if (isWarmingUp){ - prefs.edit().putBoolean("isCheckedWUP", false); - } - log.warn("added to records not uploaded"); - if (recordsNotUploadedList.size() > 49){ - recordsNotUploadedList.remove(0); - recordsNotUploadedList.add(49, new JSONObject(testData.toJson())); - }else{ - recordsNotUploadedList.add(new JSONObject(testData.toJson())); - } - }else if (typeSaved == 3){ - prefs.edit().putBoolean("isWarmingUp", isWarmingUp); - } - Log.w(TAG, "Unable to upload data to mongo in loop"); - log.warn("Unable to upload data to mongo in loop"); - if (!refreshAsked){ - sendRefreshDBConnToUI(); - refreshAsked = true; - } - } - } - } catch (Exception e) { - if (cursor != null){ - cursor.close(); - cursor = null; - } - if (client != null){ - client.close(); - client = null; - } - if (!recordsTry){ - sendErrorMessageToUI("Error uploading mongo records "+ e.getLocalizedMessage()); - sendErrorMessageToUI("If there are SGV records, I am going to store them to try a later upload. "); - for (Record oRecord : records) { - testData = new Document(); - Date date = null; - try { - date = DATE_FORMAT.parse(oRecord.displayTime); - } catch (ParseException e1) { - date = new Date(); - } - testData.put("date", date.getTime()); - testData.put("dateString", oRecord.displayTime); - typeSaved = null; - if (oRecord instanceof EGVRecord){ - EGVRecord record = (EGVRecord) oRecord; - // make db object - testData.put("device", getSelectedDeviceName()); - testData.put("sgv", record.bGValue); - testData.put("direction", record.trend); - typeSaved = 0; - if (cgmSelected == Medtronic640gActivity.MEDTRONIC_CGM && (oRecord instanceof MedtronicSensorRecord)){ - typeSaved = 1; - testData.put("isig", ((MedtronicSensorRecord)record).isig); - testData.put("calibrationFactor", ((MedtronicSensorRecord)record).calibrationFactor); - testData.put("calibrationStatus", ((MedtronicSensorRecord)record).calibrationStatus); - testData.put("unfilteredGlucose", ((MedtronicSensorRecord)record).unfilteredGlucose); - testData.put("isCalibrating", ((MedtronicSensorRecord)record).isCalibrating); - } - } - if ((typeSaved != null && (typeSaved == 0 ||typeSaved == 1 ))){//Only EGV records are important enough. - log.warn("added to records not uploaded"); - try{ - if (recordsNotUploadedList.size() > 49){ - recordsNotUploadedList.remove(0); - recordsNotUploadedList.add(49, new JSONObject(testData.toJson())); - }else{ - recordsNotUploadedList.add(new JSONObject(testData.toJson())); - } - }catch(Exception ex){ - StringBuffer sb1 = new StringBuffer(""); - sb1.append("EXCEPTION!!!!!! "+ ex.getMessage()+" "+ex.getCause()); - for (StackTraceElement st : ex.getStackTrace()){ - sb1.append(st.toString()); - } - sendMessageToUI(sb1.toString(), false); - } - } - } - } - Log.e(TAG, "Unable to upload data to mongo", e); - log.error("Unable to upload data to mongo", e); - StringBuffer sb1 = new StringBuffer(""); - sb1.append("EXCEPTION!!!!!! "+ e.getMessage()+" "+e.getCause()); - for (StackTraceElement st : e.getStackTrace()){ - sb1.append(st.toString()); - } - sendMessageToUI(sb1.toString(), false); - if (!refreshAsked){ - sendRefreshDBConnToUI(); - refreshAsked = true; - } - } - try{ - if (db != null){ - //Uploading devicestatus - boolean update = true; - if (prefs.contains("lastBatteryUpdated")){ - long lastTimeUpdated = prefs.getLong("lastBatteryUpdated", 0); - if (lastTimeUpdated > 0){ - long current = System.currentTimeMillis(); - long diff = current - lastTimeUpdated; - if (diff < MedtronicConstants.TIME_5_MIN_IN_MS) - update = false; - else{ - SharedPreferences.Editor editor = prefs.edit(); - editor.putLong("lastBatteryUpdated", current); - editor.commit(); - } - }else{ - SharedPreferences.Editor editor = prefs.edit(); - editor.putLong("lastBatteryUpdated", System.currentTimeMillis()); - editor.commit(); - } - }else{ - SharedPreferences.Editor editor = prefs.edit(); - editor.putLong("lastBatteryUpdated", System.currentTimeMillis()); - editor.commit(); - } - if (update){ - Document devicestatus = new Document(); - devicestatus.put("uploaderBattery", Medtronic640gActivity.batLevel); - devicestatus.put("created_at", new Date()); - log.debug("Update Battery"); - dsCollection.insertOne(devicestatus); - } - } - } catch (Exception e) { - if (cursor != null){ - cursor.close(); - cursor = null; - } - if (client != null){ - client.close(); - client = null; - } - Log.e(TAG, "Unable to upload battery data to mongo", e); - log.error("Unable to upload battery data to mongo", e); - StringBuffer sb1 = new StringBuffer(""); - sb1.append("EXCEPTION!!!!!! "+ e.getMessage()+" "+e.getCause()); - for (StackTraceElement st : e.getStackTrace()){ - sb1.append(st.toString()); - } - sendMessageToUI(sb1.toString(), false); - if (!refreshAsked){ - sendRefreshDBConnToUI(); - refreshAsked = true; - } - } - if (cursor != null){ - cursor.close(); - cursor = null; - } - if (client != null){ - client.close(); - client = null; - } - if (recordsNotUploadedList.size() > 0){ - synchronized (isModifyingRecordsLock) { - try { - JSONArray recordsNotUploaded = new JSONArray(settings.getString("recordsNotUploaded","[]")); - if (recordsNotUploaded.length() > 0 && recordsNotUploaded.length() < recordsNotUploadedList.size()){ - for (int i = 0; i < recordsNotUploaded.length(); i++){ - if (recordsNotUploadedList.size() > 49){ - recordsNotUploadedList.remove(0); - recordsNotUploadedList.add(49, recordsNotUploaded.getJSONObject(i)); - }else{ - recordsNotUploadedList.add(recordsNotUploaded.getJSONObject(i)); - } - } - }else{ - for (int i = 0; i < recordsNotUploadedList.size(); i++){ - recordsNotUploaded.put(recordsNotUploadedList.get(i)); - } - recordsNotUploadedList.clear(); - int start = 0; - if (recordsNotUploaded.length() > 50){ - start = recordsNotUploaded.length() - 51; - } - for (int i = start; i < recordsNotUploaded.length(); i++){ - recordsNotUploadedList.add(recordsNotUploaded.getJSONObject(i)); - } - } - log.debug("retrieving older json records -->" +recordsNotUploaded.length()); - SharedPreferences.Editor editor = settings.edit(); - editor.remove("recordsNotUploaded"); - editor.commit(); - } catch (Exception e) { - log.debug("ERROR RETRIVING OLDER LISTs, I have lost them"); - SharedPreferences.Editor editor = settings.edit(); - if (settings.contains("recordsNotUploaded")) - editor.remove("recordsNotUploaded"); - editor.commit(); - } - JSONArray jsonArray = new JSONArray(recordsNotUploadedList); - SharedPreferences.Editor editor = settings.edit(); - editor.putString("recordsNotUploaded", jsonArray.toString()); - editor.commit(); - } - } - } - - } } diff --git a/app/src/main/java/info/nightscout/android/dexcom/USB/HexDump.java b/app/src/main/java/info/nightscout/android/utils/HexDump.java similarity index 99% rename from app/src/main/java/info/nightscout/android/dexcom/USB/HexDump.java rename to app/src/main/java/info/nightscout/android/utils/HexDump.java index 3608083..1e01ce7 100644 --- a/app/src/main/java/info/nightscout/android/dexcom/USB/HexDump.java +++ b/app/src/main/java/info/nightscout/android/utils/HexDump.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package info.nightscout.android.dexcom.USB; +package info.nightscout.android.utils; /** * Clone of Android's HexDump class, for use in debugging. Cosmetic changes diff --git a/app/src/main/java/info/nightscout/android/widget/CGMWidget.java b/app/src/main/java/info/nightscout/android/widget/CGMWidget.java deleted file mode 100644 index f507ba9..0000000 --- a/app/src/main/java/info/nightscout/android/widget/CGMWidget.java +++ /dev/null @@ -1,108 +0,0 @@ -package info.nightscout.android.widget; - -import java.io.File; -import java.io.FileInputStream; -import java.io.ObjectInputStream; -import java.util.Calendar; - -import android.app.AlarmManager; -import android.app.PendingIntent; -import android.appwidget.AppWidgetManager; -import android.appwidget.AppWidgetProvider; -import android.content.Context; -import android.content.Intent; -import android.util.Log; -import android.widget.RemoteViews; - -import info.nightscout.android.R; -import info.nightscout.android.medtronic.Medtronic640gActivity; -import info.nightscout.android.dexcom.EGVRecord; -import info.nightscout.android.medtronic.MedtronicConstants; -import info.nightscout.android.upload.MedtronicSensorRecord; -import info.nightscout.android.upload.Record; - -public class CGMWidget extends AppWidgetProvider { - private PendingIntent service = null; - public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { - final int N = appWidgetIds.length; - - // Perform this loop procedure for each App Widget that belongs to this provider - for (int i=0; i<N; i++) { - int appWidgetId = appWidgetIds[i]; - - // Create an Intent to launch ExampleActivity - Intent intent = new Intent(context, Medtronic640gActivity.class); - PendingIntent pendingIntent = PendingIntent.getActivity(context, 7, intent, 0); - - // Get the layout for the App Widget and attach an on-click listener - // to the button - RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_main); - views.setOnClickPendingIntent(R.id.imageButton1, pendingIntent); - Record auxRecord = CGMWidget.this.loadClassFile(new File(context.getFilesDir(), "save.bin")); - if (auxRecord instanceof MedtronicSensorRecord){ - MedtronicSensorRecord record = (MedtronicSensorRecord) auxRecord; - boolean isCalibrating = record.isCalibrating; - String calib = "---"; - if (isCalibrating) - calib = "*"; - else - calib = MedtronicConstants.getWidgetCalAppend(record.calibrationStatus); - views.setTextViewText(R.id.sgv_id, record.bGValue+calib); - views.setTextViewText(R.id.arrow_id, record.trendArrow); - - }else if (auxRecord instanceof EGVRecord){ - EGVRecord record = (EGVRecord)auxRecord; - views.setTextViewText(R.id.sgv_id, record.bGValue); - views.setTextViewText(R.id.arrow_id, record.trendArrow); - }else{ - views.setTextViewText(R.id.sgv_id, "---"); - views.setTextViewText(R.id.arrow_id, "---"); - } - // Tell the AppWidgetManager to perform an update on the current app widget - appWidgetManager.updateAppWidget(appWidgetId, views); - - final AlarmManager m = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); - - final Calendar TIME = Calendar.getInstance(); - TIME.set(Calendar.MINUTE, 0); - TIME.set(Calendar.SECOND, 0); - TIME.set(Calendar.MILLISECOND, 0); - - final Intent in = new Intent(context, CGMWidgetUpdater.class); - - if (service == null) - { - service = PendingIntent.getService(context, 0, in, PendingIntent.FLAG_CANCEL_CURRENT); - } - - m.setRepeating(AlarmManager.RTC, TIME.getTime().getTime(), 1000 * 30, service); - } - } - @Override - public void onDisabled(Context context) - { - final AlarmManager m = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); - - m.cancel(service); - } - public Record loadClassFile(File f) { - ObjectInputStream ois = null; - try { - ois = new ObjectInputStream(new FileInputStream(f)); - Object o = ois.readObject(); - ois.close(); - return (Record) o; - } catch (Exception ex) { - Log.w("CGMWidget", " unable to loadEGVRecord"); - try{ - if (ois != null) - ois.close(); - }catch(Exception e){ - Log.e("CGMWidget", " Error closing ObjectInputStream"); - } - } - return new Record(); - } - - -} diff --git a/app/src/main/java/info/nightscout/android/widget/CGMWidgetUpdater.java b/app/src/main/java/info/nightscout/android/widget/CGMWidgetUpdater.java deleted file mode 100644 index 0a48014..0000000 --- a/app/src/main/java/info/nightscout/android/widget/CGMWidgetUpdater.java +++ /dev/null @@ -1,117 +0,0 @@ -package info.nightscout.android.widget; - -import java.io.File; -import java.io.FileInputStream; -import java.io.ObjectInputStream; - -import android.app.KeyguardManager; -import android.app.PendingIntent; -import android.app.Service; -import android.appwidget.AppWidgetManager; -import android.content.ComponentName; -import android.content.Context; -import android.content.Intent; -import android.content.SharedPreferences; -import android.os.IBinder; -import android.preference.PreferenceManager; -import android.util.Log; -import android.widget.RemoteViews; - -import info.nightscout.android.R; -import info.nightscout.android.medtronic.Medtronic640gActivity; -import info.nightscout.android.dexcom.EGVRecord; -import info.nightscout.android.medtronic.MedtronicConstants; -import info.nightscout.android.upload.MedtronicSensorRecord; -import info.nightscout.android.upload.Record; - -public class CGMWidgetUpdater extends Service{ - - public static int UPDATE_FREQUENCY_SEC = 10; - @Override - public void onCreate() - { - super.onCreate(); - } - - @Override - public int onStartCommand(Intent intent, int flags, int startId) - { - buildUpdate(); - - return super.onStartCommand(intent, flags, startId); - } - - private void buildUpdate() - { - - RemoteViews views = null; - KeyguardManager myKM = (KeyguardManager) getBaseContext().getSystemService(Context.KEYGUARD_SERVICE); - if( myKM.inKeyguardRestrictedInputMode()) { - views = new RemoteViews(getPackageName(), R.layout.widget_lock); - } else { - views = new RemoteViews(getPackageName(), R.layout.widget_main); - Intent intent = new Intent(getBaseContext(), Medtronic640gActivity.class); - PendingIntent pendingIntent = PendingIntent.getActivity(getBaseContext(), 7, intent, 0); - views.setOnClickPendingIntent(R.id.imageButton1, pendingIntent); - } - Record auxRecord = CGMWidgetUpdater.this.loadClassFile(new File(getBaseContext().getFilesDir(), "save.bin")); - updateValues(auxRecord, views); - - // Push update for this widget to the home screen - ComponentName thisWidget = new ComponentName(this, CGMWidget.class); - AppWidgetManager manager = AppWidgetManager.getInstance(this); - manager.updateAppWidget(thisWidget, views); - } - - private void updateValues(Record auxRecord, RemoteViews views){ - if (auxRecord instanceof MedtronicSensorRecord){ - SharedPreferences prefs = PreferenceManager - .getDefaultSharedPreferences(getBaseContext()); - MedtronicSensorRecord record = (MedtronicSensorRecord) auxRecord; - boolean isCalibrating = record.isCalibrating; - String calib = "---"; - if (isCalibrating) - calib = "*"; - else - calib = MedtronicConstants.getWidgetCalAppend(record.calibrationStatus); - if (prefs.getBoolean("isWarmingUp",false)){ - calib = ""; - record.bGValue = "W._Up"; - record.trendArrow="---"; - } - views.setTextViewText(R.id.sgv_id, record.bGValue+calib); - views.setTextViewText(R.id.arrow_id, record.trendArrow); - - }else if (auxRecord instanceof EGVRecord){ - EGVRecord record = (EGVRecord)auxRecord; - views.setTextViewText(R.id.sgv_id, record.bGValue); - views.setTextViewText(R.id.arrow_id, record.trendArrow); - }else{ - views.setTextViewText(R.id.sgv_id, "---"); - views.setTextViewText(R.id.arrow_id, "---"); - } - } - public Record loadClassFile(File f) { - ObjectInputStream ois = null; - try { - ois = new ObjectInputStream(new FileInputStream(f)); - Object o = ois.readObject(); - ois.close(); - return (Record) o; - } catch (Exception ex) { - Log.w("CGMWidget", " unable to loadEGVRecord"); - try{ - if (ois != null) - ois.close(); - }catch(Exception e){ - Log.e("CGMWidget", " Error closing ObjectInputStream"); - } - } - return new Record(); - } - @Override - public IBinder onBind(Intent intent) - { - return null; - } -} \ No newline at end of file -- GitLab