DanaR driver as a service

This commit is contained in:
Milos Kozak 2016-07-18 12:02:33 +02:00
parent d82a696bfb
commit a1a64873fd
53 changed files with 834 additions and 970 deletions

View file

@ -32,6 +32,7 @@
</intent-filter> </intent-filter>
</activity> </activity>
<activity android:name=".PreferencesActivity" /> <activity android:name=".PreferencesActivity" />
<activity android:name=".AgreementActivity" />
<!-- Receiver from NSClient --> <!-- Receiver from NSClient -->
<receiver <receiver
@ -84,17 +85,14 @@
android:name=".Services.AlertService" android:name=".Services.AlertService"
android:exported="false" /> android:exported="false" />
<meta-data
android:name="io.fabric.ApiKey"
android:value="59d462666c664c57b29e1d79ea123e01f8057cfa" />
<service <service
android:name=".plugins.DanaR.Services.DanaRService" android:name=".plugins.DanaR.Services.ExecutionService"
android:enabled="true" android:enabled="true"
android:exported="false" /> android:exported="false" />
<activity android:name=".AgreementActivity" /> <meta-data
android:name="io.fabric.ApiKey"
android:value="59d462666c664c57b29e1d79ea123e01f8057cfa" />
</application> </application>
</manifest> </manifest>

View file

@ -1,9 +0,0 @@
package info.nightscout.androidaps.events;
/**
* Created by mike on 07.07.2016.
*/
public class EventPumpConnecting {
public boolean sConnecting;
public boolean sConnected;
}

View file

@ -1,466 +0,0 @@
package info.nightscout.androidaps.plugins.DanaR;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.PowerManager;
import android.preference.PreferenceManager;
import com.j256.ormlite.dao.Dao;
import com.squareup.otto.Bus;
import com.squareup.otto.Subscribe;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.SQLException;
import java.util.Calendar;
import java.util.Date;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.MainActivity;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.Services.AlertService;
import info.nightscout.androidaps.db.Treatment;
import info.nightscout.androidaps.events.EventPreferenceChange;
import info.nightscout.androidaps.plugins.DanaR.comm.*;
import info.nightscout.androidaps.plugins.DanaR.events.EventDanaRBolusProgress;
import info.nightscout.androidaps.plugins.DanaR.events.EventDanaRConnectionStatus;
import info.nightscout.androidaps.plugins.DanaR.events.EventDanaRNewStatus;
import info.nightscout.client.data.NSProfile;
import info.nightscout.utils.ToastUtils;
/**
* Created by mike on 07.07.2016.
*/
public class DanaConnection {
private static Logger log = LoggerFactory.getLogger(DanaConnection.class);
SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext());
public String devName = SP.getString("danar_bt_name", "");
Handler mHandler;
public static HandlerThread mHandlerThread;
private final Bus mBus;
private SerialEngine mSerialEngine;
private InputStream mInputStream;
private OutputStream mOutputStream;
private BluetoothSocket mRfcommSocket;
private BluetoothDevice mDevice;
PowerManager.WakeLock mWakeLock;
private Treatment bolusingTreatment = null;
private static Object connectionInProgress = new Object();
private DanaRFragment danaRFragment;
private DanaRPump danaRPump;
private static final ScheduledExecutorService worker = Executors.newSingleThreadScheduledExecutor();
private static ScheduledFuture<?> scheduledDisconnection = null;
private static final UUID SPP_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
public DanaConnection(Bus bus) {
danaRFragment = (DanaRFragment) MainActivity.getSpecificPlugin(DanaRFragment.class);
danaRFragment.setDanaConnection(this);
danaRPump = danaRFragment.getDanaRPump();
mHandlerThread = new HandlerThread(DanaConnection.class.getSimpleName());
mHandlerThread.start();
mHandler = new Handler(mHandlerThread.getLooper());
getSelectedPump();
this.mBus = bus;
createRfCommSocket();
PowerManager powerManager = (PowerManager) MainApp.instance().getApplicationContext().getSystemService(Context.POWER_SERVICE);
mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "DanaConnection");
}
private void createRfCommSocket() {
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter != null) {
Set<BluetoothDevice> devices = mBluetoothAdapter.getBondedDevices();
for (BluetoothDevice device : devices) {
String dName = device.getName();
if (devName.equals(dName)) {
mDevice = device;
try {
mRfcommSocket = mDevice.createRfcommSocketToServiceRecord(SPP_UUID);
} catch (IOException e) {
log.error("Error creating socket: ", e);
}
break;
}
}
registerBTdisconnectionBroadcastReceiver();
} else {
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.sResources.getString(R.string.nobtadapter));
}
if (mDevice == null) {
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.sResources.getString(R.string.devicenotfound));
}
}
private void registerBTdisconnectionBroadcastReceiver() {
BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
String action = intent.getAction();
if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
log.debug("Device has disconnected " + device.getName());//Device has disconnected
if (mDevice != null && mDevice.getName().equals(device.getName())) {
if (mRfcommSocket != null) {
try {
mInputStream.close();
} catch (Exception e) {
log.debug(e.getMessage());
}
try {
mOutputStream.close();
} catch (Exception e) {
log.debug(e.getMessage());
}
try {
mRfcommSocket.close();
} catch (Exception e) {
log.debug(e.getMessage());
}
}
mBus.post(new EventDanaRConnectionStatus(false, false, 0));
}
}
}
};
MainApp.instance().getApplicationContext().registerReceiver(receiver, new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED));
}
public synchronized void connectIfNotConnected(String callerName) {
synchronized (connectionInProgress) {
mWakeLock.acquire();
long startTime = System.currentTimeMillis();
short connectionAttemptCount = 0;
if (!(isConnected())) {
long timeToConnectTimeSoFar = 0;
while (!(isConnected())) {
timeToConnectTimeSoFar = (System.currentTimeMillis() - startTime) / 1000;
mBus.post(new EventDanaRConnectionStatus(true, false, connectionAttemptCount));
connectBT();
if (isConnected()) {
mBus.post(new EventDanaRConnectionStatus(false, true, 0));
break;
}
if (Config.logDanaBTComm)
log.debug("connectIfNotConnected waiting " + timeToConnectTimeSoFar + "s attempts:" + connectionAttemptCount + " caller:" + callerName);
connectionAttemptCount++;
if (timeToConnectTimeSoFar / 60 > 15 || connectionAttemptCount > 180) {
Intent alarmServiceIntent = new Intent(MainApp.instance().getApplicationContext(), AlertService.class);
alarmServiceIntent.putExtra("alarmText", MainApp.sResources.getString(R.string.connectionerror));
MainApp.instance().getApplicationContext().startService(alarmServiceIntent);
}
waitMsec(1000);
}
if (Config.logDanaBTComm)
log.debug("connectIfNotConnected took " + timeToConnectTimeSoFar + "s attempts:" + connectionAttemptCount);
pingStatus();
} else {
mBus.post(new EventDanaRConnectionStatus(false, true, 0));
}
mWakeLock.release();
}
}
private synchronized void connectBT() {
if (mDevice == null) {
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.sResources.getString(R.string.devicenotfound));
return;
}
if (mRfcommSocket == null) {
try {
mRfcommSocket = mDevice.createRfcommSocketToServiceRecord(SPP_UUID);
} catch (IOException e) {
log.error("Error creating socket: ", e);
}
if (mRfcommSocket == null) {
log.warn("connectBT() mRfcommSocket is null");
return;
}
}
if (!mRfcommSocket.isConnected()) {
try {
mRfcommSocket.connect();
if (Config.logDanaBTComm)
log.debug("Connected");
mOutputStream = mRfcommSocket.getOutputStream();
mInputStream = mRfcommSocket.getInputStream();
if (mSerialEngine != null) {
mSerialEngine.stopLoop();
}
mSerialEngine = new SerialEngine(this, mInputStream, mOutputStream, mRfcommSocket);
mBus.post(new EventDanaRConnectionStatus(false, true, 0));
} catch (IOException e) {
log.warn("connectBT() ConnectionStatusEvent attempt failed: " + e.getMessage());
mRfcommSocket = null;
}
}
}
public void scheduleDisconnection() {
class DisconnectRunnable implements Runnable {
public void run() {
disconnect("scheduleDisconnection");
scheduledDisconnection = null;
}
}
// prepare task for execution in 5 sec
// cancel waiting task to prevent sending multiple disconnections
if (scheduledDisconnection != null)
scheduledDisconnection.cancel(false);
Runnable task = new DisconnectRunnable();
final int sec = 5;
scheduledDisconnection = worker.schedule(task, sec, TimeUnit.SECONDS);
//if (Config.logDanaBTComm)
// log.debug("Disconnection scheduled in " + sec + "secs");
}
public void disconnect(String from) {
if (mRfcommSocket.isConnected()) {
if (Config.logDanaBTComm)
log.debug("Disconnecting " + from);
try {
mInputStream.close();
} catch (Exception e) {
log.debug(e.getMessage());
}
try {
mOutputStream.close();
} catch (Exception e) {
log.debug(e.getMessage());
}
try {
mRfcommSocket.close();
} catch (Exception e) {
log.debug(e.getMessage());
}
} else {
if (Config.logDanaBTComm)
log.debug("Already disconnected " + from);
}
}
public boolean isConnected() {
return mRfcommSocket != null && mRfcommSocket.isConnected();
}
private void pingStatus() {
try {
MsgStatus statusMsg = new MsgStatus();
MsgStatusBasic statusBasicMsg = new MsgStatusBasic();
MsgStatusTempBasal tempStatusMsg = new MsgStatusTempBasal();
MsgStatusBolusExtended exStatusMsg = new MsgStatusBolusExtended();
mSerialEngine.sendMessage(tempStatusMsg); // do this before statusBasic because here is temp duration
mSerialEngine.sendMessage(exStatusMsg);
mSerialEngine.sendMessage(statusMsg);
mSerialEngine.sendMessage(statusBasicMsg);
if (danaRPump.isNewPump) {
mSerialEngine.sendMessage(new MsgSettingShippingInfo());
mSerialEngine.sendMessage(new MsgCheckValue());
}
if (!statusMsg.received) {
mSerialEngine.sendMessage(statusMsg);
}
if (!statusBasicMsg.received) {
mSerialEngine.sendMessage(statusBasicMsg);
}
if (!tempStatusMsg.received) {
// Load of status of current basal rate failed, give one more try
mSerialEngine.sendMessage(tempStatusMsg);
}
if (!exStatusMsg.received) {
// Load of status of current extended bolus failed, give one more try
mSerialEngine.sendMessage(exStatusMsg);
}
// Check we have really current status of pump
if (!statusMsg.received || !statusBasicMsg.received || !tempStatusMsg.received || !exStatusMsg.received) {
waitMsec(10 * 1000);
log.debug("pingStatus failed");
connectIfNotConnected("pingStatus fail");
pingStatus();
return;
}
Date now = new Date();
if (danaRPump.lastSettingsRead.getTime() + 60 * 60 * 1000L < now.getTime()) {
mSerialEngine.sendMessage(new MsgSettingShippingInfo());
mSerialEngine.sendMessage(new MsgSettingActiveProfile());
//0x3203
mSerialEngine.sendMessage(new MsgSettingBasal());
//0x3201
mSerialEngine.sendMessage(new MsgSettingMaxValues());
mSerialEngine.sendMessage(new MsgSettingGlucose());
mSerialEngine.sendMessage(new MsgSettingPumpTime());
mSerialEngine.sendMessage(new MsgSettingActiveProfile());
mSerialEngine.sendMessage(new MsgSettingProfileRatios());
mSerialEngine.sendMessage(new MsgSettingProfileRatiosAll());
danaRPump.lastSettingsRead = now;
}
danaRPump.lastConnection = now;
mBus.post(new EventDanaRNewStatus());
} catch (Exception e) {
log.error("err", e);
}
}
public void tempBasal(int percent, int durationInHours) {
mSerialEngine.sendMessage(new MsgSetTempBasalStart(percent, durationInHours));
mSerialEngine.sendMessage(new MsgStatusTempBasal());
}
public void tempBasalStop() {
mSerialEngine.sendMessage(new MsgSetTempBasalStop());
mSerialEngine.sendMessage(new MsgStatusTempBasal());
}
public void extendedBolus(double insulin, int durationInHalfHours) {
mSerialEngine.sendMessage(new MsgSetExtendedBolusStart(insulin, (byte) (durationInHalfHours & 0xFF)));
mSerialEngine.sendMessage(new MsgStatusBolusExtended());
}
public void extendedBolusStop() {
mSerialEngine.sendMessage(new MsgSetExtendedBolusStop());
mSerialEngine.sendMessage(new MsgStatusBolusExtended());
}
public void stop() {
try {
mInputStream.close();
} catch (Exception e) {
log.debug(e.getMessage());
}
try {
mOutputStream.close();
} catch (Exception e) {
log.debug(e.getMessage());
}
try {
mRfcommSocket.close();
} catch (Exception e) {
log.debug(e.getMessage());
}
if (mSerialEngine != null) mSerialEngine.stopLoop();
}
public void bolus(Double amount, Treatment t) {
// TODO: progress dialog
bolusingTreatment = t;
MsgBolusStart start = new MsgBolusStart(amount);
MsgBolusProgress progress = new MsgBolusProgress(MainApp.bus(), amount, t);
MsgBolusStop stop = new MsgBolusStop(MainApp.bus(), amount, t);
mSerialEngine.sendMessage(start);
while (!stop.stopped && !start.failed) {
waitMsec(100);
}
bolusingTreatment = null;
pingStatus();
}
public void bolusStop() {
Treatment lastBolusingTreatment = bolusingTreatment;
if (Config.logDanaBTComm)
log.debug("bolusStop >>>>> @ " + (bolusingTreatment == null ? "" : bolusingTreatment.insulin));
MsgBolusStop stop = new MsgBolusStop();
stop.forced = true;
mSerialEngine.sendMessage(stop);
while (!stop.stopped) {
mSerialEngine.sendMessage(stop);
waitMsec(200);
}
// and update ns status to last amount
waitMsec(60000);
EventDanaRBolusProgress be = EventDanaRBolusProgress.getInstance();
be.sStatus = "";
mBus.post(be);
}
public void carbsEntry(int amount) {
Calendar time = Calendar.getInstance();
MsgSetCarbsEntry msg = new MsgSetCarbsEntry(time, amount);
mSerialEngine.sendMessage(msg);
//pingStatus();
}
public void updateBasalsInPump(final NSProfile profile) {
double[] basal = buildDanaRProfileRecord(profile);
MsgSetBasalProfile msgSet = new MsgSetBasalProfile((byte) 0, basal);
mSerialEngine.sendMessage(msgSet);
MsgSetActivateBasalProfile msgActivate = new MsgSetActivateBasalProfile((byte) 0);
mSerialEngine.sendMessage(msgActivate);
pingStatus();
}
public double[] buildDanaRProfileRecord(NSProfile nsProfile) {
double[] record = new double[24];
for (Integer hour = 0; hour < 24; hour++) {
double value = nsProfile.getBasal(hour * 60 * 60);
if (Config.logDanaMessageDetail)
log.debug("NS basal value for " + hour + ":00 is " + value);
record[hour] = value;
}
return record;
}
@Subscribe
public void onStatusEvent(final EventPreferenceChange pch) {
getSelectedPump();
createRfCommSocket();
}
private void getSelectedPump() {
devName = SP.getString("danar_bt_name", "");
}
public void waitMsec(long msecs) {
try {
Thread.sleep(msecs);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

View file

@ -2,10 +2,15 @@ package info.nightscout.androidaps.plugins.DanaR;
import android.app.Activity; import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences; import android.content.SharedPreferences;
import android.os.Bundle; import android.os.Bundle;
import android.os.Handler; import android.os.Handler;
import android.os.HandlerThread; import android.os.HandlerThread;
import android.os.IBinder;
import android.preference.PreferenceManager; import android.preference.PreferenceManager;
import android.support.annotation.Nullable; import android.support.annotation.Nullable;
import android.support.v4.app.Fragment; import android.support.v4.app.Fragment;
@ -41,6 +46,7 @@ import info.nightscout.androidaps.interfaces.ProfileInterface;
import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderFragment; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderFragment;
import info.nightscout.androidaps.plugins.DanaR.Dialogs.ProfileViewDialog; import info.nightscout.androidaps.plugins.DanaR.Dialogs.ProfileViewDialog;
import info.nightscout.androidaps.plugins.DanaR.Services.ExecutionService;
import info.nightscout.androidaps.plugins.DanaR.events.EventDanaRConnectionStatus; import info.nightscout.androidaps.plugins.DanaR.events.EventDanaRConnectionStatus;
import info.nightscout.androidaps.plugins.DanaR.events.EventDanaRNewStatus; import info.nightscout.androidaps.plugins.DanaR.events.EventDanaRNewStatus;
import info.nightscout.client.data.NSProfile; import info.nightscout.client.data.NSProfile;
@ -48,14 +54,17 @@ import info.nightscout.utils.DateUtil;
import info.nightscout.utils.DecimalFormatter; import info.nightscout.utils.DecimalFormatter;
import info.nightscout.utils.Round; import info.nightscout.utils.Round;
import info.nightscout.utils.SetWarnColor; import info.nightscout.utils.SetWarnColor;
import info.nightscout.utils.ToastUtils;
public class DanaRFragment extends Fragment implements PluginBase, PumpInterface, ConstraintsInterface, ProfileInterface { public class DanaRFragment extends Fragment implements PluginBase, PumpInterface, ConstraintsInterface, ProfileInterface {
private static Logger log = LoggerFactory.getLogger(DanaRFragment.class); private static Logger log = LoggerFactory.getLogger(DanaRFragment.class);
Handler mHandler; private Handler mHandler;
public static HandlerThread mHandlerThread; private static HandlerThread mHandlerThread;
private boolean mBounded;
private static ExecutionService mExecutionService;
private static DanaConnection sDanaConnection = null;
private static DanaRPump sDanaRPump = new DanaRPump(); private static DanaRPump sDanaRPump = new DanaRPump();
private static boolean useExtendedBoluses = false; private static boolean useExtendedBoluses = false;
@ -64,8 +73,8 @@ public class DanaRFragment extends Fragment implements PluginBase, PumpInterface
boolean fragmentPumpVisible = true; boolean fragmentPumpVisible = true;
boolean visibleNow = false; boolean visibleNow = false;
Handler loopHandler = new Handler(); private Handler loopHandler = new Handler();
Runnable refreshLoop = null; private Runnable refreshLoop = null;
TextView lastConnectionView; TextView lastConnectionView;
TextView btConnectionView; TextView btConnectionView;
@ -79,13 +88,7 @@ public class DanaRFragment extends Fragment implements PluginBase, PumpInterface
TextView iobView; TextView iobView;
Button viewProfileButton; Button viewProfileButton;
public static DanaConnection getDanaConnection() { // TODO: password in prefs
return sDanaConnection;
}
public static void setDanaConnection(DanaConnection con) {
sDanaConnection = con;
}
public static DanaRPump getDanaRPump() { public static DanaRPump getDanaRPump() {
return sDanaRPump; return sDanaRPump;
@ -170,9 +173,7 @@ public class DanaRFragment extends Fragment implements PluginBase, PumpInterface
mHandler.post(new Runnable() { mHandler.post(new Runnable() {
@Override @Override
public void run() { public void run() {
if (getDanaConnection() == null) mExecutionService.connect("Connect request from GUI");
setDanaConnection(new DanaConnection(MainApp.bus()));
getDanaConnection().connectIfNotConnected("Connect request from GUI");
} }
} }
); );
@ -183,24 +184,58 @@ public class DanaRFragment extends Fragment implements PluginBase, PumpInterface
return view; return view;
} }
@Override
public void onStart() {
super.onStart();
Context context = getContext();
Intent intent = new Intent(context, ExecutionService.class);
context.bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
ServiceConnection mConnection = new ServiceConnection() {
public void onServiceDisconnected(ComponentName name) {
ToastUtils.showToastInUiThread(getContext(), "ExecutionService is disconnected"); // TODO: remove
mBounded = false;
mExecutionService = null;
}
public void onServiceConnected(ComponentName name, IBinder service) {
ToastUtils.showToastInUiThread(getContext(), "ExecutionService is connected"); // TODO: remove
log.debug("Service is connected");
mBounded = true;
ExecutionService.LocalBinder mLocalBinder = (ExecutionService.LocalBinder) service;
mExecutionService = mLocalBinder.getServiceInstance();
}
};
@Override
public void onStop() {
super.onStop();
if (mBounded) {
getContext().unbindService(mConnection);
mBounded = false;
}
}
;
@Subscribe @Subscribe
public void onStatusEvent(final EventDanaRConnectionStatus c) { public void onStatusEvent(final EventDanaRConnectionStatus c) {
Activity activity = getActivity(); Activity activity = getActivity();
if (activity != null) { if (activity != null) {
activity.runOnUiThread(new Runnable() { activity.runOnUiThread(
@Override new Runnable() {
public void run() { @Override
if (c.sConnecting) { public void run() {
btConnectionView.setText("{fa-bluetooth-b spin} " + c.sConnectionAttemptNo); if (c.sStatus == c.CONNECTING)
} else { btConnectionView.setText("{fa-bluetooth-b spin} " + c.sSecondsElapsed + "s");
if (c.sConnected) { else if (c.sStatus == c.CONNECTED)
btConnectionView.setText("{fa-bluetooth}"); btConnectionView.setText("{fa-bluetooth}");
} else { else
btConnectionView.setText("{fa-bluetooth-b}"); btConnectionView.setText("{fa-bluetooth-b}");
} }
} }
}
}
); );
} }
} }
@ -221,8 +256,7 @@ public class DanaRFragment extends Fragment implements PluginBase, PumpInterface
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext()); SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext());
useExtendedBoluses = sharedPreferences.getBoolean("danar_useextended", false); useExtendedBoluses = sharedPreferences.getBoolean("danar_useextended", false);
if (useExtendedBoluses != previousValue && isExtendedBoluslInProgress()) { if (useExtendedBoluses != previousValue && isExtendedBoluslInProgress()) {
getDanaConnection().connectIfNotConnected("EventPreferenceChange"); mExecutionService.extendedBolusStop();
getDanaConnection().extendedBolusStop();
} }
updateGUI(); updateGUI();
} }
@ -289,10 +323,8 @@ public class DanaRFragment extends Fragment implements PluginBase, PumpInterface
@Override @Override
public void setNewBasalProfile(NSProfile profile) { public void setNewBasalProfile(NSProfile profile) {
if (getDanaConnection() == null) if (!mExecutionService.updateBasalsInPump(profile))
setDanaConnection(new DanaConnection(MainApp.bus())); ToastUtils.showToastInUiThread(getContext(), MainApp.sResources.getString(R.string.failedupdatebasalprofile));
getDanaConnection().connectIfNotConnected("setNewBasalProfile");
getDanaConnection().updateBasalsInPump(profile);
} }
@Override @Override
@ -357,13 +389,13 @@ public class DanaRFragment extends Fragment implements PluginBase, PumpInterface
ConfigBuilderFragment configBuilderFragment = MainApp.getConfigBuilder(); ConfigBuilderFragment configBuilderFragment = MainApp.getConfigBuilder();
insulin = configBuilderFragment.applyBolusConstraints(insulin); insulin = configBuilderFragment.applyBolusConstraints(insulin);
if (insulin > 0 || carbs > 0) { if (insulin > 0 || carbs > 0) {
getDanaConnection().connectIfNotConnected("deliverTreatment");
Treatment t = new Treatment(); Treatment t = new Treatment();
t.insulin = insulin; t.insulin = insulin;
if (insulin > 0) getDanaConnection().bolus(insulin, t); boolean connectionOK = false;
if (carbs > 0) getDanaConnection().carbsEntry(carbs); if (carbs > 0) connectionOK = mExecutionService.carbsEntry(carbs);
if (insulin > 0) connectionOK = mExecutionService.bolus(insulin, t);
PumpEnactResult result = new PumpEnactResult(); PumpEnactResult result = new PumpEnactResult();
result.success = true; result.success = connectionOK;
result.bolusDelivered = t.insulin; result.bolusDelivered = t.insulin;
result.carbsDelivered = carbs; result.carbsDelivered = carbs;
result.comment = MainApp.instance().getString(R.string.virtualpump_resultok); result.comment = MainApp.instance().getString(R.string.virtualpump_resultok);
@ -418,7 +450,7 @@ public class DanaRFragment extends Fragment implements PluginBase, PumpInterface
} }
if (doLowTemp || doHighTemp) { if (doLowTemp || doHighTemp) {
Integer percentRate = new Double(absoluteRate / getBaseBasalRate() * 100).intValue(); Integer percentRate = Double.valueOf(absoluteRate / getBaseBasalRate() * 100).intValue();
if (percentRate < 100) percentRate = Round.ceilTo((double) percentRate, 10d).intValue(); if (percentRate < 100) percentRate = Round.ceilTo((double) percentRate, 10d).intValue();
else percentRate = Round.floorTo((double) percentRate, 10d).intValue(); else percentRate = Round.floorTo((double) percentRate, 10d).intValue();
if (percentRate > 200) { if (percentRate > 200) {
@ -552,10 +584,9 @@ public class DanaRFragment extends Fragment implements PluginBase, PumpInterface
log.debug("setTempBasalPercent: Correct value already set"); log.debug("setTempBasalPercent: Correct value already set");
return result; return result;
} }
getDanaConnection().connectIfNotConnected("setTempBasalPercent");
int durationInHours = Math.max(durationInMinutes / 60, 1); int durationInHours = Math.max(durationInMinutes / 60, 1);
getDanaConnection().tempBasal(percent, durationInHours); boolean connectionOK = mExecutionService.tempBasal(percent, durationInHours);
if (getDanaRPump().isTempBasalInProgress && getDanaRPump().tempBasalPercent == percent) { if (connectionOK && getDanaRPump().isTempBasalInProgress && getDanaRPump().tempBasalPercent == percent) {
result.enacted = true; result.enacted = true;
result.success = true; result.success = true;
result.comment = MainApp.instance().getString(R.string.virtualpump_resultok); result.comment = MainApp.instance().getString(R.string.virtualpump_resultok);
@ -594,10 +625,9 @@ public class DanaRFragment extends Fragment implements PluginBase, PumpInterface
log.debug("setExtendedBolus: Correct extended bolus already set"); log.debug("setExtendedBolus: Correct extended bolus already set");
return result; return result;
} }
getDanaConnection().connectIfNotConnected("setExtendedBolus");
int durationInHalfHours = Math.max(durationInMinutes / 30, 1); int durationInHalfHours = Math.max(durationInMinutes / 30, 1);
getDanaConnection().extendedBolus(insulin, durationInHalfHours); boolean connectionOK = mExecutionService.extendedBolus(insulin, durationInHalfHours);
if (getDanaRPump().isExtendedInProgress && getDanaRPump().extendedBolusAmount - insulin == 0) { if (connectionOK && getDanaRPump().isExtendedInProgress && getDanaRPump().extendedBolusAmount - insulin == 0) {
result.enacted = true; result.enacted = true;
result.success = true; result.success = true;
result.comment = MainApp.instance().getString(R.string.virtualpump_resultok); result.comment = MainApp.instance().getString(R.string.virtualpump_resultok);
@ -633,9 +663,8 @@ public class DanaRFragment extends Fragment implements PluginBase, PumpInterface
public PumpEnactResult cancelRealTempBasal() { public PumpEnactResult cancelRealTempBasal() {
PumpEnactResult result = new PumpEnactResult(); PumpEnactResult result = new PumpEnactResult();
getDanaConnection().connectIfNotConnected("cancelRealTempBasal");
if (getDanaRPump().isTempBasalInProgress) { if (getDanaRPump().isTempBasalInProgress) {
getDanaConnection().tempBasalStop(); mExecutionService.tempBasalStop();
result.enacted = true; result.enacted = true;
result.isTempCancel = true; result.isTempCancel = true;
} }
@ -658,9 +687,8 @@ public class DanaRFragment extends Fragment implements PluginBase, PumpInterface
@Override @Override
public PumpEnactResult cancelExtendedBolus() { public PumpEnactResult cancelExtendedBolus() {
PumpEnactResult result = new PumpEnactResult(); PumpEnactResult result = new PumpEnactResult();
getDanaConnection().connectIfNotConnected("cancelExtendedBolus");
if (getDanaRPump().isExtendedInProgress) { if (getDanaRPump().isExtendedInProgress) {
getDanaConnection().extendedBolusStop(); mExecutionService.extendedBolusStop();
result.enacted = true; result.enacted = true;
result.isTempCancel = true; result.isTempCancel = true;
} }
@ -678,6 +706,10 @@ public class DanaRFragment extends Fragment implements PluginBase, PumpInterface
} }
} }
public static void doConnect(String from) {
mExecutionService.connect(from);
}
@Override @Override
public JSONObject getJSONStatus() { public JSONObject getJSONStatus() {
JSONObject pump = new JSONObject(); JSONObject pump = new JSONObject();
@ -803,6 +835,7 @@ public class DanaRFragment extends Fragment implements PluginBase, PumpInterface
if (getDanaRPump() != null) { if (getDanaRPump() != null) {
if (absoluteRate > getDanaRPump().maxBasal) { if (absoluteRate > getDanaRPump().maxBasal) {
absoluteRate = getDanaRPump().maxBasal; absoluteRate = getDanaRPump().maxBasal;
if (Config.logConstraintsChanges && origAbsoluteRate != Constants.basalAbsoluteOnlyForCheckLimit)
if (Config.logConstraintsChanges && origAbsoluteRate != Constants.basalAbsoluteOnlyForCheckLimit) if (Config.logConstraintsChanges && origAbsoluteRate != Constants.basalAbsoluteOnlyForCheckLimit)
log.debug("Limiting rate " + origAbsoluteRate + "U/h by pump constraint to " + absoluteRate + "U/h"); log.debug("Limiting rate " + origAbsoluteRate + "U/h by pump constraint to " + absoluteRate + "U/h");
} }

View file

@ -22,7 +22,7 @@ public class DanaRPump {
public static final int UNITS_MGDL = 0; public static final int UNITS_MGDL = 0;
public static final int UNITS_MMOL = 1; public static final int UNITS_MMOL = 1;
Date lastConnection = new Date(0); public Date lastConnection = new Date(0);
public Date lastSettingsRead = new Date(0); public Date lastSettingsRead = new Date(0);
// Info // Info

View file

@ -16,9 +16,7 @@ import org.slf4j.LoggerFactory;
import java.util.Date; import java.util.Date;
import info.nightscout.androidaps.MainActivity; import info.nightscout.androidaps.MainActivity;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.plugins.DanaR.DanaConnection;
import info.nightscout.androidaps.plugins.DanaR.DanaRFragment; import info.nightscout.androidaps.plugins.DanaR.DanaRFragment;
import info.nightscout.client.data.NSProfile; import info.nightscout.client.data.NSProfile;
import info.nightscout.utils.DecimalFormatter; import info.nightscout.utils.DecimalFormatter;
@ -75,12 +73,11 @@ public class ProfileViewDialog extends DialogFragment {
@Override @Override
public void run() { public void run() {
DanaRFragment.getDanaRPump().lastSettingsRead = new Date(0); DanaRFragment.getDanaRPump().lastSettingsRead = new Date(0);
if (DanaRFragment.getDanaConnection() == null) DanaRFragment.setDanaConnection(new DanaConnection(MainApp.bus())); // if (DanaRFragment.getDanaConnection() == null) DanaRFragment.setDanaConnection(new DanaConnection(MainApp.bus()));
DanaRFragment.getDanaConnection().connectIfNotConnected("ProfileViewDialog"); // DanaRFragment.getDanaConnection().connectIfNotConnected("ProfileViewDialog");
//refreshButton.setVisibility(View.VISIBLE); DanaRFragment.doConnect("ProfileViewDialog");
} }
}); });
//refreshButton.setVisibility(View.GONE);
dismiss(); dismiss();
} }
}); });

View file

@ -1,202 +0,0 @@
package info.nightscout.androidaps.plugins.DanaR;
import android.bluetooth.BluetoothSocket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.plugins.DanaR.comm.DanaRMessage;
import info.nightscout.androidaps.plugins.DanaR.comm.DanaRMessageHashTable;
import info.nightscout.utils.CRC;
/**
* Created by mike on 04.07.2016.
*/
public class SerialEngine extends Thread {
private static Logger log = LoggerFactory.getLogger(SerialEngine.class);
private final InputStream mInputStream;
private final OutputStream mOutputStream;
private BluetoothSocket mRfcommSocket;
private final DanaConnection mDc;
private boolean mKeepRunning = true;
private byte[] mReadBuff = new byte[0];
private HashMap<Integer, DanaRMessage> mOutputQueue = new HashMap<Integer, DanaRMessage>();
public SerialEngine(DanaConnection dc, InputStream inputStream, OutputStream outputStream, BluetoothSocket rfcommSocket) {
super("SerialEngine"); // Thread name
mInputStream = inputStream;
mOutputStream = outputStream;
mRfcommSocket = rfcommSocket;
mDc = dc;
this.start();
}
@Override
public final void run() {
try {
while (mKeepRunning) {
int availableBytes = mInputStream.available();
// Ask for 1024 byte (or more if available)
byte[] newData = new byte[Math.max(1024, availableBytes)];
int gotBytes = mInputStream.read(newData);
// When we are here there is some new data available
// add newData to mReadBuff
byte[] newReadBuff = new byte[mReadBuff.length + gotBytes];
System.arraycopy(mReadBuff, 0, newReadBuff, 0, mReadBuff.length);
System.arraycopy(newData, 0, newReadBuff, mReadBuff.length, gotBytes);
mReadBuff = newReadBuff;
if (mReadBuff.length < 3) {
continue;
} // 3rd byte is packet size packet still not complete
// process all messages we already got
while (mReadBuff.length > 3) {
if (mReadBuff[0] == (byte) 0x7E && mReadBuff[1] == (byte) 0x7E) {
int length = (mReadBuff[2] & 0xFF) + 7;
// Check if we have enough data
if (mReadBuff.length < length) {
break;
}
if (mReadBuff[length - 2] != (byte) 0x2E || mReadBuff[length - 1] != (byte) 0x2E) {
log.error("wrong packet lenght=" + length + " data " + DanaRMessage.toHexString(mReadBuff));
mDc.disconnect("wrong packet");
break;
}
short crc = CRC.getCrc16(mReadBuff, 3, length - 7);
byte crcByte0 = (byte) (crc >> 8 & 0xFF);
byte crcByte1 = (byte) (crc & 0xFF);
byte crcByte0received = mReadBuff[length - 4];
byte crcByte1received = mReadBuff[length - 3];
if (crcByte0 != crcByte0received || crcByte1 != crcByte1received) {
log.error("CRC Error" + String.format("%02x ", crcByte0) + String.format("%02x ", crcByte1) + String.format("%02x ", crcByte0received) + String.format("%02x ", crcByte1received));
mDc.disconnect("crc error");
break;
}
// Packet is verified here. extract data
byte[] extractedBuff = new byte[length];
System.arraycopy(mReadBuff, 0, extractedBuff, 0, length);
// remove extracted data from read buffer
byte[] unprocessedData = new byte[mReadBuff.length - length];
System.arraycopy(mReadBuff, length, unprocessedData, 0, unprocessedData.length);
mReadBuff = unprocessedData;
int command = (extractedBuff[5] & 0xFF) | ((extractedBuff[4] << 8) & 0xFF00);
// Check if message is out queue. if yes use it
DanaRMessage message = mOutputQueue.get(command);
// if not get it from hash table
if (message == null)
message = DanaRMessageHashTable.findMessage(command);
if (Config.logDanaMessageDetail)
log.debug("<<<<< " + message.getMessageName() + " " + message.toHexString(extractedBuff));
mDc.scheduleDisconnection();
// process the message content
message.received = true;
message.handleMessage(extractedBuff);
mOutputQueue.remove(message.getCommand());
synchronized (message) {
message.notify();
}
} else {
log.error("Wrong beginning of packet len=" + mReadBuff.length + " " + DanaRMessage.toHexString(mReadBuff));
}
}
}
} catch (Throwable x) {
if (x instanceof IOException || "socket closed".equals(x.getMessage())) {
if (Config.logDanaSerialEngine) log.info("Thread run " + x.getMessage());
} else {
if (Config.logDanaSerialEngine) log.error("Thread run ", x);
}
mKeepRunning = false;
}
try {
mInputStream.close();
} catch (Exception e) {
if (Config.logDanaSerialEngine) log.debug(e.getMessage());
}
try {
mOutputStream.close();
} catch (Exception e) {
if (Config.logDanaSerialEngine) log.debug(e.getMessage());
}
try {
mRfcommSocket.close();
} catch (Exception e) {
if (Config.logDanaSerialEngine) log.debug(e.getMessage());
}
try {
System.runFinalization();
} catch (Exception e) {
if (Config.logDanaSerialEngine) log.debug(e.getMessage());
}
}
public synchronized void sendMessage(DanaRMessage message) {
mOutputQueue.put(message.getCommand(), message);
byte[] messageBytes = message.getRawMessageBytes();
if (Config.logDanaSerialEngine)
log.debug(">>>>> " + message.getMessageName() + " " + message.toHexString(messageBytes));
try {
// Wait until input stream is empty
while (mInputStream.available() > 0) {
if (Config.logDanaSerialEngine) log.debug("Waiting for empty input stream");
synchronized (this.mInputStream) {
mInputStream.notify();
}
Thread.sleep(100);
}
mOutputStream.write(messageBytes);
} catch (Exception e) {
log.error("sendMessage exception: ", e);
e.printStackTrace();
}
synchronized (mInputStream) {
mInputStream.notify();
}
synchronized (message) {
try {
message.wait(5000);
} catch (InterruptedException e) {
log.error("sendMessage InterruptedException", e);
e.printStackTrace();
}
}
if (mOutputQueue.containsKey(message.getCommand())) {
log.error("Reply not received " + message.getMessageName());
mOutputQueue.remove(message.getCommand());
}
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
mDc.scheduleDisconnection();
}
public void stopLoop() {
mKeepRunning = false;
}
}

View file

@ -0,0 +1,220 @@
package info.nightscout.androidaps.plugins.DanaR;
import android.bluetooth.BluetoothSocket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.plugins.DanaR.comm.MessageBase;
import info.nightscout.androidaps.plugins.DanaR.comm.MessageHashTable;
import info.nightscout.utils.CRC;
/**
* Created by mike on 17.07.2016.
*/
public class SerialIOThread extends Thread {
private static Logger log = LoggerFactory.getLogger(SerialIOThread.class);
private InputStream mInputStream = null;
private OutputStream mOutputStream = null;
private BluetoothSocket mRfCommSocket;
private static final ScheduledExecutorService worker = Executors.newSingleThreadScheduledExecutor();
private static ScheduledFuture<?> scheduledDisconnection = null;
private boolean mKeepRunning = true;
private byte[] mReadBuff = new byte[0];
MessageBase processedMessage;
public SerialIOThread(BluetoothSocket rfcommSocket) {
super(SerialIOThread.class.toString());
mRfCommSocket = rfcommSocket;
try {
mOutputStream = mRfCommSocket.getOutputStream();
mInputStream = mRfCommSocket.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
this.start();
}
@Override
public final void run() {
try {
while (mKeepRunning) {
int availableBytes = mInputStream.available();
// Ask for 1024 byte (or more if available)
byte[] newData = new byte[Math.max(1024, availableBytes)];
int gotBytes = mInputStream.read(newData);
// When we are here there is some new data available
appendToBuffer(newData, gotBytes);
// process all messages we already got
while (mReadBuff.length > 3) { // 3rd byte is packet size. continue only if we an determine packet size
byte[] extractedBuff = cutMessageFromBuffer();
if (extractedBuff == null) break; // message is not complete in buffer (wrong packet calls disconnection)
int command = (extractedBuff[5] & 0xFF) | ((extractedBuff[4] << 8) & 0xFF00);
MessageBase message;
if (processedMessage != null & processedMessage.getCommand() == command) {
message = processedMessage;
} else {
// get it from hash table
message = MessageHashTable.findMessage(command);
}
if (Config.logDanaMessageDetail)
log.debug("<<<<< " + message.getMessageName() + " " + message.toHexString(extractedBuff));
// process the message content
message.received = true;
message.handleMessage(extractedBuff);
synchronized (message) {
message.notify();
}
scheduleDisconnection();
}
}
} catch (Exception e) {
if (Config.logDanaSerialEngine && e.getMessage().indexOf("bt socket closed") < 0)
log.error("Thread exception: ", e);
mKeepRunning = false;
}
disconnect("EndOfLoop");
}
void appendToBuffer(byte[] newData, int gotBytes) {
// add newData to mReadBuff
byte[] newReadBuff = new byte[mReadBuff.length + gotBytes];
System.arraycopy(mReadBuff, 0, newReadBuff, 0, mReadBuff.length);
System.arraycopy(newData, 0, newReadBuff, mReadBuff.length, gotBytes);
mReadBuff = newReadBuff;
}
byte[] cutMessageFromBuffer() {
if (mReadBuff[0] == (byte) 0x7E && mReadBuff[1] == (byte) 0x7E) {
int length = (mReadBuff[2] & 0xFF) + 7;
// Check if we have enough data
if (mReadBuff.length < length) {
return null;
}
if (mReadBuff[length - 2] != (byte) 0x2E || mReadBuff[length - 1] != (byte) 0x2E) {
log.error("wrong packet lenght=" + length + " data " + MessageBase.toHexString(mReadBuff));
disconnect("wrong packet");
return null;
}
short crc = CRC.getCrc16(mReadBuff, 3, length - 7);
byte crcByte0 = (byte) (crc >> 8 & 0xFF);
byte crcByte1 = (byte) (crc & 0xFF);
byte crcByte0received = mReadBuff[length - 4];
byte crcByte1received = mReadBuff[length - 3];
if (crcByte0 != crcByte0received || crcByte1 != crcByte1received) {
log.error("CRC Error" + String.format("%02x ", crcByte0) + String.format("%02x ", crcByte1) + String.format("%02x ", crcByte0received) + String.format("%02x ", crcByte1received));
disconnect("crc error");
return null;
}
// Packet is verified here. extract data
byte[] extractedBuff = new byte[length];
System.arraycopy(mReadBuff, 0, extractedBuff, 0, length);
// remove extracted data from read buffer
byte[] unprocessedData = new byte[mReadBuff.length - length];
System.arraycopy(mReadBuff, length, unprocessedData, 0, unprocessedData.length);
mReadBuff = unprocessedData;
return extractedBuff;
} else {
log.error("Wrong beginning of packet len=" + mReadBuff.length + " " + MessageBase.toHexString(mReadBuff));
disconnect("Wrong beginning of packet");
return null;
}
}
public synchronized void sendMessage(MessageBase message) {
if (!mRfCommSocket.isConnected()) {
log.error("Socket not connected on sendMessage");
return;
}
processedMessage = message;
byte[] messageBytes = message.getRawMessageBytes();
if (Config.logDanaSerialEngine)
log.debug(">>>>> " + message.getMessageName() + " " + message.toHexString(messageBytes));
try {
mOutputStream.write(messageBytes);
} catch (Exception e) {
log.error("sendMessage write exception: ", e);
e.printStackTrace();
}
synchronized (message) {
try {
message.wait(5000);
} catch (InterruptedException e) {
log.error("sendMessage InterruptedException", e);
e.printStackTrace();
}
}
if (!message.received) {
log.warn("Reply not received " + message.getMessageName());
}
scheduleDisconnection();
}
public void scheduleDisconnection() {
class DisconnectRunnable implements Runnable {
public void run() {
disconnect("scheduleDisconnection");
scheduledDisconnection = null;
}
}
// prepare task for execution in 5 sec
// cancel waiting task to prevent sending multiple disconnections
if (scheduledDisconnection != null)
scheduledDisconnection.cancel(false);
Runnable task = new DisconnectRunnable();
final int sec = 5;
scheduledDisconnection = worker.schedule(task, sec, TimeUnit.SECONDS);
}
public void disconnect(String reason) {
mKeepRunning = false;
try {
mInputStream.close();
} catch (Exception e) {
if (Config.logDanaSerialEngine) log.debug(e.getMessage());
}
try {
mOutputStream.close();
} catch (Exception e) {
if (Config.logDanaSerialEngine) log.debug(e.getMessage());
}
try {
mRfCommSocket.close();
} catch (Exception e) {
if (Config.logDanaSerialEngine) log.debug(e.getMessage());
}
try {
System.runFinalization();
} catch (Exception e) {
if (Config.logDanaSerialEngine) log.debug(e.getMessage());
}
if (Config.logDanaSerialEngine) log.debug("Disconnected: " + reason);
}
}

View file

@ -1,145 +0,0 @@
package info.nightscout.androidaps.plugins.DanaR.Services;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.support.v7.app.NotificationCompat;
import com.squareup.otto.Subscribe;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.MainActivity;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.events.EventAppExit;
import info.nightscout.androidaps.events.EventPumpConnecting;
import info.nightscout.androidaps.plugins.DanaR.DanaConnection;
import info.nightscout.androidaps.plugins.DanaR.DanaRFragment;
public class DanaRService extends Service {
private static Logger log = LoggerFactory.getLogger(DanaRService.class);
Handler mHandler;
private HandlerThread mHandlerThread;
private Notification mNotification;
private NotificationManager mNotificationManager;
private NotificationCompat.Builder mNotificationCompatBuilder;
private DanaConnection mDanaConnection;
private static final int notifyId = 130;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (Config.logFunctionCalls)
log.info("onStartCommand");
if (mHandlerThread == null) {
enableForeground();
if (Config.logFunctionCalls)
log.debug("Creating handler thread");
this.mHandlerThread = new HandlerThread(DanaRService.class.getSimpleName() + "Handler");
mHandlerThread.start();
this.mHandler = new Handler(mHandlerThread.getLooper());
DanaRFragment danaRFragment = (DanaRFragment) MainActivity.getSpecificPlugin(DanaRFragment.class);
mDanaConnection = danaRFragment.getDanaConnection();
registerBus();
if (mDanaConnection == null) {
mDanaConnection = new DanaConnection(MainApp.bus());
danaRFragment.setDanaConnection(mDanaConnection);
}
}
if (Config.DANAR)
mHandler.post(new Runnable() {
@Override
public void run() {
mDanaConnection.connectIfNotConnected("onStartCommand connectionCheck");
}
});
if (Config.logFunctionCalls)
log.info("onStartCommand end");
return START_STICKY;
}
private void registerBus() {
try {
MainApp.bus().unregister(this);
} catch (RuntimeException x) {
// Ignore
}
MainApp.bus().register(this);
}
private void enableForeground() {
mNotificationCompatBuilder = new NotificationCompat.Builder(getApplicationContext());
mNotificationCompatBuilder.setContentTitle(MainApp.sResources.getString(R.string.app_name))
.setSmallIcon(R.drawable.notification_icon)
.setAutoCancel(false)
.setOngoing(true)
.setPriority(Notification.PRIORITY_MIN)
.setOnlyAlertOnce(true)
.setWhen(System.currentTimeMillis())
.setLocalOnly(true);
mNotification = mNotificationCompatBuilder.build();
notifyManagerNotify();
startForeground(notifyId, mNotification);
}
private void notifyManagerNotify() {
mNotificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(notifyId, mNotification);
}
@Subscribe
public void onStatusEvent(final EventPumpConnecting c) {
if (Config.DANAR) {
String connectionText;
if (c.sConnecting) {
connectionText = MainApp.sResources.getString(R.string.connecting);
} else {
if (c.sConnected) {
connectionText = MainApp.sResources.getString(R.string.connected);
} else {
connectionText = MainApp.sResources.getString(R.string.disconnected);
}
}
mNotificationCompatBuilder.setWhen(System.currentTimeMillis())
.setContentText(connectionText);
mNotification = mNotificationCompatBuilder.build();
notifyManagerNotify();
}
}
@Subscribe
public void onStopEvent(EventAppExit event) {
if (Config.logFunctionCalls)
log.debug("onStopEvent received");
mDanaConnection.stop();
stopForeground(true);
stopSelf();
if (Config.logFunctionCalls)
log.debug("onStopEvent finished");
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}

View file

@ -0,0 +1,403 @@
package info.nightscout.androidaps.plugins.DanaR.Services;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Binder;
import android.os.IBinder;
import android.os.PowerManager;
import android.preference.PreferenceManager;
import com.squareup.otto.Subscribe;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.Set;
import java.util.UUID;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.MainActivity;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.db.Treatment;
import info.nightscout.androidaps.events.EventAppExit;
import info.nightscout.androidaps.events.EventPreferenceChange;
import info.nightscout.androidaps.plugins.DanaR.DanaRFragment;
import info.nightscout.androidaps.plugins.DanaR.DanaRPump;
import info.nightscout.androidaps.plugins.DanaR.SerialIOThread;
import info.nightscout.androidaps.plugins.DanaR.comm.MsgBolusProgress;
import info.nightscout.androidaps.plugins.DanaR.comm.MsgBolusStart;
import info.nightscout.androidaps.plugins.DanaR.comm.MsgBolusStop;
import info.nightscout.androidaps.plugins.DanaR.comm.MsgCheckValue;
import info.nightscout.androidaps.plugins.DanaR.comm.MsgSetActivateBasalProfile;
import info.nightscout.androidaps.plugins.DanaR.comm.MsgSetBasalProfile;
import info.nightscout.androidaps.plugins.DanaR.comm.MsgSetCarbsEntry;
import info.nightscout.androidaps.plugins.DanaR.comm.MsgSetExtendedBolusStart;
import info.nightscout.androidaps.plugins.DanaR.comm.MsgSetExtendedBolusStop;
import info.nightscout.androidaps.plugins.DanaR.comm.MsgSetTempBasalStart;
import info.nightscout.androidaps.plugins.DanaR.comm.MsgSetTempBasalStop;
import info.nightscout.androidaps.plugins.DanaR.comm.MsgSettingActiveProfile;
import info.nightscout.androidaps.plugins.DanaR.comm.MsgSettingBasal;
import info.nightscout.androidaps.plugins.DanaR.comm.MsgSettingGlucose;
import info.nightscout.androidaps.plugins.DanaR.comm.MsgSettingMaxValues;
import info.nightscout.androidaps.plugins.DanaR.comm.MsgSettingProfileRatios;
import info.nightscout.androidaps.plugins.DanaR.comm.MsgSettingProfileRatiosAll;
import info.nightscout.androidaps.plugins.DanaR.comm.MsgSettingPumpTime;
import info.nightscout.androidaps.plugins.DanaR.comm.MsgSettingShippingInfo;
import info.nightscout.androidaps.plugins.DanaR.comm.MsgStatus;
import info.nightscout.androidaps.plugins.DanaR.comm.MsgStatusBasic;
import info.nightscout.androidaps.plugins.DanaR.comm.MsgStatusBolusExtended;
import info.nightscout.androidaps.plugins.DanaR.comm.MsgStatusTempBasal;
import info.nightscout.androidaps.plugins.DanaR.events.EventDanaRBolusProgress;
import info.nightscout.androidaps.plugins.DanaR.events.EventDanaRConnectionStatus;
import info.nightscout.androidaps.plugins.DanaR.events.EventDanaRNewStatus;
import info.nightscout.client.data.NSProfile;
import info.nightscout.utils.ToastUtils;
public class ExecutionService extends Service {
private static Logger log = LoggerFactory.getLogger(ExecutionService.class);
private SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext());
private String devName;
private SerialIOThread mSerialIOThread;
private BluetoothSocket mRfcommSocket;
private BluetoothDevice mBTDevice;
private PowerManager.WakeLock mWakeLock;
private IBinder mBinder = new LocalBinder();
private DanaRPump danaRPump;
private Treatment bolusingTreatment = null;
private static Object connectionInProgress = new Object();
private static final UUID SPP_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
private BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
String action = intent.getAction();
if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
log.debug("Device has disconnected " + device.getName());//Device has disconnected
if (mBTDevice != null && mBTDevice.getName().equals(device.getName())) {
if (mSerialIOThread != null) {
mSerialIOThread.disconnect("BT disconnection broadcast");
}
MainApp.bus().post(new EventDanaRConnectionStatus(EventDanaRConnectionStatus.DISCONNECTED, 0));
}
}
}
};
public ExecutionService() {
registerBus();
MainApp.instance().getApplicationContext().registerReceiver(receiver, new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED));
DanaRFragment danaRFragment = (DanaRFragment) MainActivity.getSpecificPlugin(DanaRFragment.class);
if (danaRFragment != null)
danaRPump = danaRFragment.getDanaRPump();
else
log.error("danaRFragment is null");
PowerManager powerManager = (PowerManager) MainApp.instance().getApplicationContext().getSystemService(Context.POWER_SERVICE);
mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "DanaConnection");
}
public class LocalBinder extends Binder {
public ExecutionService getServiceInstance() {
return ExecutionService.this;
}
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
private void registerBus() {
try {
MainApp.bus().unregister(this);
} catch (RuntimeException x) {
// Ignore
}
MainApp.bus().register(this);
}
@Subscribe
public void onStatusEvent(EventAppExit event) {
if (Config.logFunctionCalls)
log.debug("EventAppExit received");
// TODO: mDanaConnection.stop();
if (mSerialIOThread != null)
mSerialIOThread.disconnect("Application exit");
MainApp.instance().getApplicationContext().unregisterReceiver(receiver);
stopSelf();
if (Config.logFunctionCalls)
log.debug("EventAppExit finished");
}
private boolean isConnected() {
return mRfcommSocket != null && mRfcommSocket.isConnected();
}
public void connect(String from) {
if (isConnected()) {
if (Config.logDanaBTComm)
log.debug("already connected from:" + from);
return;
}
final long maxConnectionTime = 5 * 60 * 1000L; // 5 min
synchronized (connectionInProgress) {
mWakeLock.acquire();
getBTSocketForSelectedPump();
if (mRfcommSocket == null || mBTDevice == null)
return; // Device not found
long startTime = new Date().getTime();
while (!isConnected() && startTime + maxConnectionTime >= new Date().getTime()) {
long secondsElapsed = (new Date().getTime() - startTime) / 1000L;
MainApp.bus().post(new EventDanaRConnectionStatus(EventDanaRConnectionStatus.CONNECTING, (int) secondsElapsed));
if (Config.logDanaBTComm)
log.debug("connect waiting " + secondsElapsed + "sec from:" + from);
try {
mRfcommSocket.connect();
} catch (IOException e) {
}
waitMsec(1000);
}
if (isConnected()) {
if (mSerialIOThread != null) {
mSerialIOThread.disconnect("Recreate SerialIOThread");
}
mSerialIOThread = new SerialIOThread(mRfcommSocket);
MainApp.bus().post(new EventDanaRConnectionStatus(EventDanaRConnectionStatus.CONNECTED, 0));
getPumpStatus();
} else {
log.error("Pump connection timed out");
}
mWakeLock.release();
}
}
private void getBTSocketForSelectedPump() {
devName = SP.getString("danar_bt_name", "");
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter != null) {
Set<BluetoothDevice> bondedDevices = bluetoothAdapter.getBondedDevices();
for (BluetoothDevice device : bondedDevices) {
if (devName.equals(device.getName())) {
mBTDevice = device;
try {
mRfcommSocket = mBTDevice.createRfcommSocketToServiceRecord(SPP_UUID);
} catch (IOException e) {
log.error("Error creating socket: ", e);
}
break;
}
}
} else {
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.sResources.getString(R.string.nobtadapter));
}
if (mBTDevice == null) {
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.sResources.getString(R.string.devicenotfound));
}
}
@Subscribe
public void onStatusEvent(final EventPreferenceChange pch) {
if (mSerialIOThread != null)
mSerialIOThread.disconnect("EventPreferenceChange");
}
private void getPumpStatus() { // TODO rename after
try {
MsgStatus statusMsg = new MsgStatus();
MsgStatusBasic statusBasicMsg = new MsgStatusBasic();
MsgStatusTempBasal tempStatusMsg = new MsgStatusTempBasal();
MsgStatusBolusExtended exStatusMsg = new MsgStatusBolusExtended();
mSerialIOThread.sendMessage(tempStatusMsg); // do this before statusBasic because here is temp duration
mSerialIOThread.sendMessage(exStatusMsg);
mSerialIOThread.sendMessage(statusMsg);
mSerialIOThread.sendMessage(statusBasicMsg);
if (danaRPump.isNewPump) {
mSerialIOThread.sendMessage(new MsgSettingShippingInfo());
mSerialIOThread.sendMessage(new MsgCheckValue());
}
if (!statusMsg.received) {
mSerialIOThread.sendMessage(statusMsg);
}
if (!statusBasicMsg.received) {
mSerialIOThread.sendMessage(statusBasicMsg);
}
if (!tempStatusMsg.received) {
// Load of status of current basal rate failed, give one more try
mSerialIOThread.sendMessage(tempStatusMsg);
}
if (!exStatusMsg.received) {
// Load of status of current extended bolus failed, give one more try
mSerialIOThread.sendMessage(exStatusMsg);
}
// Check we have really current status of pump
if (!statusMsg.received || !statusBasicMsg.received || !tempStatusMsg.received || !exStatusMsg.received) {
waitMsec(10 * 1000);
log.debug("getPumpStatus failed");
connect("getPumpStatus fail");
return;
}
Date now = new Date();
if (danaRPump.lastSettingsRead.getTime() + 60 * 60 * 1000L < now.getTime()) {
mSerialIOThread.sendMessage(new MsgSettingShippingInfo());
mSerialIOThread.sendMessage(new MsgSettingActiveProfile());
//0x3203
mSerialIOThread.sendMessage(new MsgSettingBasal());
//0x3201
mSerialIOThread.sendMessage(new MsgSettingMaxValues());
mSerialIOThread.sendMessage(new MsgSettingGlucose());
mSerialIOThread.sendMessage(new MsgSettingPumpTime());
mSerialIOThread.sendMessage(new MsgSettingActiveProfile());
mSerialIOThread.sendMessage(new MsgSettingProfileRatios());
mSerialIOThread.sendMessage(new MsgSettingProfileRatiosAll());
danaRPump.lastSettingsRead = now;
}
danaRPump.lastConnection = now;
MainApp.bus().post(new EventDanaRNewStatus());
} catch (Exception e) {
log.error("err", e);
}
}
public boolean tempBasal(int percent, int durationInHours) {
connect("tempBasal");
if (!isConnected()) return false;
mSerialIOThread.sendMessage(new MsgSetTempBasalStart(percent, durationInHours));
mSerialIOThread.sendMessage(new MsgStatusTempBasal());
return true;
}
public boolean tempBasalStop() {
connect("tempBasalStop");
if (!isConnected()) return false;
mSerialIOThread.sendMessage(new MsgSetTempBasalStop());
mSerialIOThread.sendMessage(new MsgStatusTempBasal());
return true;
}
public boolean extendedBolus(double insulin, int durationInHalfHours) {
connect("extendedBolus");
if (!isConnected()) return false;
mSerialIOThread.sendMessage(new MsgSetExtendedBolusStart(insulin, (byte) (durationInHalfHours & 0xFF)));
mSerialIOThread.sendMessage(new MsgStatusBolusExtended());
return true;
}
public boolean extendedBolusStop() {
connect("extendedBolusStop");
if (!isConnected()) return false;
mSerialIOThread.sendMessage(new MsgSetExtendedBolusStop());
mSerialIOThread.sendMessage(new MsgStatusBolusExtended());
return true;
}
public boolean bolus(Double amount, Treatment t) {
connect("bolus");
if (!isConnected()) return false;
// TODO: progress dialog
bolusingTreatment = t;
MsgBolusStart start = new MsgBolusStart(amount);
MsgBolusProgress progress = new MsgBolusProgress(MainApp.bus(), amount, t);
MsgBolusStop stop = new MsgBolusStop(MainApp.bus(), amount, t);
mSerialIOThread.sendMessage(start);
while (!stop.stopped && !start.failed) {
waitMsec(100);
}
bolusingTreatment = null;
getPumpStatus();
return true;
}
public void bolusStop() {
Treatment lastBolusingTreatment = bolusingTreatment;
if (Config.logDanaBTComm)
log.debug("bolusStop >>>>> @ " + (bolusingTreatment == null ? "" : bolusingTreatment.insulin));
MsgBolusStop stop = new MsgBolusStop();
stop.forced = true;
mSerialIOThread.sendMessage(stop);
while (!stop.stopped) {
mSerialIOThread.sendMessage(stop);
waitMsec(200);
}
// and update ns status to last amount
waitMsec(60000);
EventDanaRBolusProgress be = EventDanaRBolusProgress.getInstance();
be.sStatus = "";
MainApp.bus().post(be);
}
public boolean carbsEntry(int amount) {
connect("carbsEntry");
if (!isConnected()) return false;
Calendar time = Calendar.getInstance();
MsgSetCarbsEntry msg = new MsgSetCarbsEntry(time, amount);
mSerialIOThread.sendMessage(msg);
return true;
}
public boolean updateBasalsInPump(final NSProfile profile) {
connect("updateBasalsInPump");
if (!isConnected()) return false;
double[] basal = buildDanaRProfileRecord(profile);
MsgSetBasalProfile msgSet = new MsgSetBasalProfile((byte) 0, basal);
mSerialIOThread.sendMessage(msgSet);
MsgSetActivateBasalProfile msgActivate = new MsgSetActivateBasalProfile((byte) 0);
mSerialIOThread.sendMessage(msgActivate);
getPumpStatus();
return true;
}
private double[] buildDanaRProfileRecord(NSProfile nsProfile) {
double[] record = new double[24];
for (Integer hour = 0; hour < 24; hour++) {
double value = nsProfile.getBasal(hour * 60 * 60);
if (Config.logDanaMessageDetail)
log.debug("NS basal value for " + hour + ":00 is " + value);
record[hour] = value;
}
return record;
}
private void waitMsec(long msecs) {
try {
Thread.sleep(msecs);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

View file

@ -6,23 +6,23 @@ import android.os.Build;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.Config;
import info.nightscout.utils.CRC;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.Arrays; import java.util.Arrays;
import java.util.Calendar; import java.util.Calendar;
import java.util.Date; import java.util.Date;
import java.util.GregorianCalendar; import java.util.GregorianCalendar;
import info.nightscout.androidaps.Config;
import info.nightscout.utils.CRC;
/* /*
* 00 01 02 03 04 05 06 * 00 01 02 03 04 05 06
* *
* 7E 7E len F1 CMD SUB data CRC CRC 2E 2E * 7E 7E len F1 CMD SUB data CRC CRC 2E 2E
*/ */
public class DanaRMessage { public class MessageBase {
private static Logger log = LoggerFactory.getLogger(DanaRMessage.class); private static Logger log = LoggerFactory.getLogger(MessageBase.class);
private byte[] buffer = new byte[512]; private byte[] buffer = new byte[512];
private int position = 6; private int position = 6;
@ -58,7 +58,7 @@ public class DanaRMessage {
int length = this.position - 3; int length = this.position - 3;
this.buffer[2] = (byte) length; this.buffer[2] = (byte) length;
this.buffer[3] = (byte) 0xf1; this.buffer[3] = (byte) 0xF1;
this.AddParamInt(CRC.getCrc16(this.buffer, 3, length)); this.AddParamInt(CRC.getCrc16(this.buffer, 3, length));
@ -69,7 +69,7 @@ public class DanaRMessage {
} }
public String getMessageName() { public String getMessageName() {
return DanaRMessageNames.getName(getCommand()); return MessageOriginalNames.getName(getCommand());
} }
public void handleMessage(byte[] bytes) { public void handleMessage(byte[] bytes) {

View file

@ -8,14 +8,14 @@ import java.util.HashMap;
/** /**
* Created by mike on 28.05.2016. * Created by mike on 28.05.2016.
*/ */
public class DanaRMessageHashTable { public class MessageHashTable {
private static Logger log = LoggerFactory.getLogger(DanaRMessageHashTable.class); private static Logger log = LoggerFactory.getLogger(MessageHashTable.class);
public static HashMap<Integer, DanaRMessage> messages = null; public static HashMap<Integer, MessageBase> messages = null;
static { static {
if (messages == null) { if (messages == null) {
messages = new HashMap<Integer, DanaRMessage>(); messages = new HashMap<Integer, MessageBase>();
put(new MsgBolusStop()); // 0x0101 CMD_MEALINS_STOP put(new MsgBolusStop()); // 0x0101 CMD_MEALINS_STOP
put(new MsgBolusStart()); // 0x0102 CMD_MEALINS_START_DATA put(new MsgBolusStart()); // 0x0102 CMD_MEALINS_START_DATA
put(new MsgBolusProgress()); // 0x0202 CMD_PUMP_THIS_REMAINDER_MEAL_INS put(new MsgBolusProgress()); // 0x0202 CMD_PUMP_THIS_REMAINDER_MEAL_INS
@ -54,18 +54,18 @@ public class DanaRMessageHashTable {
} }
} }
public static void put(DanaRMessage message) { public static void put(MessageBase message) {
int command = message.getCommand(); int command = message.getCommand();
//String name = DanaRMessageNames.getName(command); //String name = MessageOriginalNames.getName(command);
messages.put(command, message); messages.put(command, message);
//log.debug(String.format("%04x ", command) + " " + name); //log.debug(String.format("%04x ", command) + " " + name);
} }
public static DanaRMessage findMessage(Integer command) { public static MessageBase findMessage(Integer command) {
if (messages.containsKey(command)) { if (messages.containsKey(command)) {
return messages.get(command); return messages.get(command);
} else { } else {
return new DanaRMessage(); return new MessageBase();
} }
} }
} }

View file

@ -8,8 +8,8 @@ import java.util.HashMap;
/** /**
* Created by mike on 28.05.2016. * Created by mike on 28.05.2016.
*/ */
public class DanaRMessageNames { public class MessageOriginalNames {
private static Logger log = LoggerFactory.getLogger(DanaRMessageNames.class); private static Logger log = LoggerFactory.getLogger(MessageOriginalNames.class);
public static HashMap<Integer,String> messageNames; public static HashMap<Integer,String> messageNames;

View file

@ -10,7 +10,7 @@ import info.nightscout.androidaps.db.Treatment;
import info.nightscout.androidaps.plugins.DanaR.events.EventDanaRBolusProgress; import info.nightscout.androidaps.plugins.DanaR.events.EventDanaRBolusProgress;
import info.nightscout.utils.DecimalFormatter; import info.nightscout.utils.DecimalFormatter;
public class MsgBolusProgress extends DanaRMessage { public class MsgBolusProgress extends MessageBase {
private static Logger log = LoggerFactory.getLogger(MsgBolusProgress.class); private static Logger log = LoggerFactory.getLogger(MsgBolusProgress.class);
private static Bus bus = null; private static Bus bus = null;

View file

@ -5,7 +5,7 @@ import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.Config; import info.nightscout.androidaps.Config;
public class MsgBolusStart extends DanaRMessage { public class MsgBolusStart extends MessageBase {
private static Logger log = LoggerFactory.getLogger(MsgBolusStart.class); private static Logger log = LoggerFactory.getLogger(MsgBolusStart.class);
public MsgBolusStart() { public MsgBolusStart() {

View file

@ -8,7 +8,7 @@ import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.db.Treatment; import info.nightscout.androidaps.db.Treatment;
import info.nightscout.androidaps.plugins.DanaR.events.EventDanaRBolusProgress; import info.nightscout.androidaps.plugins.DanaR.events.EventDanaRBolusProgress;
public class MsgBolusStop extends DanaRMessage { public class MsgBolusStop extends MessageBase {
private static Logger log = LoggerFactory.getLogger(MsgBolusStop.class); private static Logger log = LoggerFactory.getLogger(MsgBolusStop.class);
private static Treatment t; private static Treatment t;
private static Double amount; private static Double amount;

View file

@ -8,7 +8,7 @@ import info.nightscout.androidaps.Config;
/** /**
* Created by mike on 30.06.2016. * Created by mike on 30.06.2016.
*/ */
public class MsgCheckValue extends DanaRMessage { public class MsgCheckValue extends MessageBase {
private static Logger log = LoggerFactory.getLogger(MsgCheckValue.class); private static Logger log = LoggerFactory.getLogger(MsgCheckValue.class);
public MsgCheckValue() { public MsgCheckValue() {

View file

@ -11,7 +11,7 @@ import java.util.Date;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.db.HistoryRecord; import info.nightscout.androidaps.db.HistoryRecord;
public class MsgHistoryAll extends DanaRMessage { public class MsgHistoryAll extends MessageBase {
private static Logger log = LoggerFactory.getLogger(MsgHistoryAll.class); private static Logger log = LoggerFactory.getLogger(MsgHistoryAll.class);
public MsgHistoryAll() { public MsgHistoryAll() {
@ -37,7 +37,7 @@ public class MsgHistoryAll extends DanaRMessage {
historyRecord.setBytes(bytes); historyRecord.setBytes(bytes);
switch (recordCode) { switch (recordCode) {
case DanaRRecordTypes.RECORD_TYPE_BOLUS: case RecordTypes.RECORD_TYPE_BOLUS:
historyRecord.setRecordDate(datetime); historyRecord.setRecordDate(datetime);
switch (0xF0 & paramByte8) { switch (0xF0 & paramByte8) {
case 0xA0: case 0xA0:
@ -59,25 +59,25 @@ public class MsgHistoryAll extends DanaRMessage {
historyRecord.setRecordDuration(((int) paramByte8 & 0x0F) * 60 + (int) paramByte7); historyRecord.setRecordDuration(((int) paramByte8 & 0x0F) * 60 + (int) paramByte7);
historyRecord.setRecordValue(value * 0.01); historyRecord.setRecordValue(value * 0.01);
break; break;
case DanaRRecordTypes.RECORD_TYPE_DAILY: case RecordTypes.RECORD_TYPE_DAILY:
historyRecord.setRecordDate(date); historyRecord.setRecordDate(date);
historyRecord.setRecordDailyBasal((double) ((int) paramByte5 * 0xFF + (int) paramByte6) * 0.01); historyRecord.setRecordDailyBasal((double) ((int) paramByte5 * 0xFF + (int) paramByte6) * 0.01);
historyRecord.setRecordDailyBolus((double) ((int) paramByte7 * 0xFF + (int) paramByte8) / 0.01); historyRecord.setRecordDailyBolus((double) ((int) paramByte7 * 0xFF + (int) paramByte8) / 0.01);
break; break;
case DanaRRecordTypes.RECORD_TYPE_PRIME: case RecordTypes.RECORD_TYPE_PRIME:
case DanaRRecordTypes.RECORD_TYPE_ERROR: case RecordTypes.RECORD_TYPE_ERROR:
case DanaRRecordTypes.RECORD_TYPE_REFILL: case RecordTypes.RECORD_TYPE_REFILL:
case DanaRRecordTypes.RECORD_TYPE_BASALHOUR: case RecordTypes.RECORD_TYPE_BASALHOUR:
case DanaRRecordTypes.RECORD_TYPE_TB: case RecordTypes.RECORD_TYPE_TB:
historyRecord.setRecordDate(datetimewihtsec); historyRecord.setRecordDate(datetimewihtsec);
historyRecord.setRecordValue(value * 0.01); historyRecord.setRecordValue(value * 0.01);
break; break;
case DanaRRecordTypes.RECORD_TYPE_GLUCOSE: case RecordTypes.RECORD_TYPE_GLUCOSE:
case DanaRRecordTypes.RECORD_TYPE_CARBO: case RecordTypes.RECORD_TYPE_CARBO:
historyRecord.setRecordDate(datetimewihtsec); historyRecord.setRecordDate(datetimewihtsec);
historyRecord.setRecordValue(value); historyRecord.setRecordValue(value);
break; break;
case DanaRRecordTypes.RECORD_TYPE_ALARM: case RecordTypes.RECORD_TYPE_ALARM:
historyRecord.setRecordDate(datetimewihtsec); historyRecord.setRecordDate(datetimewihtsec);
String strAlarm = "None"; String strAlarm = "None";
switch ((int) paramByte8) { switch ((int) paramByte8) {
@ -97,7 +97,7 @@ public class MsgHistoryAll extends DanaRMessage {
historyRecord.setRecordAlarm(strAlarm); historyRecord.setRecordAlarm(strAlarm);
historyRecord.setRecordValue(value * 0.01); historyRecord.setRecordValue(value * 0.01);
break; break;
case DanaRRecordTypes.RECORD_TYPE_SUSPEND: case RecordTypes.RECORD_TYPE_SUSPEND:
historyRecord.setRecordDate(datetimewihtsec); historyRecord.setRecordDate(datetimewihtsec);
String strRecordValue = "Off"; String strRecordValue = "Off";
if ((int) paramByte8 == 79) if ((int) paramByte8 == 79)

View file

@ -1,6 +1,6 @@
package info.nightscout.androidaps.plugins.DanaR.comm; package info.nightscout.androidaps.plugins.DanaR.comm;
public class MsgHistoryAllDone extends DanaRMessage { public class MsgHistoryAllDone extends MessageBase {
public MsgHistoryAllDone() { public MsgHistoryAllDone() {
SetCommand(0x41F1); SetCommand(0x41F1);

View file

@ -3,7 +3,7 @@ package info.nightscout.androidaps.plugins.DanaR.comm;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
public class MsgInitConnStatusBasic extends DanaRMessage { public class MsgInitConnStatusBasic extends MessageBase {
private static Logger log = LoggerFactory.getLogger(MsgInitConnStatusBasic.class); private static Logger log = LoggerFactory.getLogger(MsgInitConnStatusBasic.class);
public MsgInitConnStatusBasic() { public MsgInitConnStatusBasic() {

View file

@ -6,7 +6,7 @@ import org.slf4j.LoggerFactory;
/** /**
* Created by mike on 28.05.2016. * Created by mike on 28.05.2016.
*/ */
public class MsgInitConnStatusBolus extends DanaRMessage{ public class MsgInitConnStatusBolus extends MessageBase {
private static Logger log = LoggerFactory.getLogger(MsgInitConnStatusBolus.class); private static Logger log = LoggerFactory.getLogger(MsgInitConnStatusBolus.class);
public MsgInitConnStatusBolus() { public MsgInitConnStatusBolus() {

View file

@ -9,7 +9,7 @@ import info.nightscout.androidaps.plugins.DanaR.DanaRFragment;
/** /**
* Created by mike on 28.05.2016. * Created by mike on 28.05.2016.
*/ */
public class MsgInitConnStatusOption extends DanaRMessage { public class MsgInitConnStatusOption extends MessageBase {
private static Logger log = LoggerFactory.getLogger(MsgInitConnStatusOption.class); private static Logger log = LoggerFactory.getLogger(MsgInitConnStatusOption.class);
public MsgInitConnStatusOption() { public MsgInitConnStatusOption() {

View file

@ -7,7 +7,7 @@ import java.util.Date;
import info.nightscout.androidaps.Config; import info.nightscout.androidaps.Config;
public class MsgInitConnStatusTime extends DanaRMessage { public class MsgInitConnStatusTime extends MessageBase {
private static Logger log = LoggerFactory.getLogger(MsgInitConnStatusTime.class); private static Logger log = LoggerFactory.getLogger(MsgInitConnStatusTime.class);
public MsgInitConnStatusTime() { public MsgInitConnStatusTime() {

View file

@ -18,7 +18,7 @@ import info.nightscout.androidaps.plugins.DanaR.events.EventDanaRBolusProgress;
import info.nightscout.client.data.DbLogger; import info.nightscout.client.data.DbLogger;
import info.nightscout.utils.DateUtil; import info.nightscout.utils.DateUtil;
public class MsgOcclusion extends DanaRMessage { public class MsgOcclusion extends MessageBase {
private static Logger log = LoggerFactory.getLogger(MsgOcclusion.class); private static Logger log = LoggerFactory.getLogger(MsgOcclusion.class);
public MsgOcclusion() { public MsgOcclusion() {

View file

@ -1,6 +1,6 @@
package info.nightscout.androidaps.plugins.DanaR.comm; package info.nightscout.androidaps.plugins.DanaR.comm;
public class MsgPCCommStart extends DanaRMessage { public class MsgPCCommStart extends MessageBase {
public MsgPCCommStart() { public MsgPCCommStart() {
SetCommand(0x3001); SetCommand(0x3001);
} }

View file

@ -1,6 +1,6 @@
package info.nightscout.androidaps.plugins.DanaR.comm; package info.nightscout.androidaps.plugins.DanaR.comm;
public class MsgPCCommStop extends DanaRMessage { public class MsgPCCommStop extends MessageBase {
public MsgPCCommStop() { public MsgPCCommStop() {
SetCommand(0x3002); SetCommand(0x3002);
} }

View file

@ -5,7 +5,7 @@ import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.Config; import info.nightscout.androidaps.Config;
public class MsgSetActivateBasalProfile extends DanaRMessage { public class MsgSetActivateBasalProfile extends MessageBase {
private static Logger log = LoggerFactory.getLogger(MsgSetActivateBasalProfile.class); private static Logger log = LoggerFactory.getLogger(MsgSetActivateBasalProfile.class);
public MsgSetActivateBasalProfile() { public MsgSetActivateBasalProfile() {

View file

@ -5,7 +5,7 @@ import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.Config; import info.nightscout.androidaps.Config;
public class MsgSetBasalProfile extends DanaRMessage { public class MsgSetBasalProfile extends MessageBase {
private static Logger log = LoggerFactory.getLogger(MsgSetBasalProfile.class); private static Logger log = LoggerFactory.getLogger(MsgSetBasalProfile.class);
public MsgSetBasalProfile() { public MsgSetBasalProfile() {

View file

@ -7,7 +7,7 @@ import java.util.Calendar;
import info.nightscout.androidaps.Config; import info.nightscout.androidaps.Config;
public class MsgSetCarbsEntry extends DanaRMessage { public class MsgSetCarbsEntry extends MessageBase {
private static Logger log = LoggerFactory.getLogger(MsgSetCarbsEntry.class); private static Logger log = LoggerFactory.getLogger(MsgSetCarbsEntry.class);
public MsgSetCarbsEntry() { public MsgSetCarbsEntry() {
@ -17,7 +17,7 @@ public class MsgSetCarbsEntry extends DanaRMessage {
public MsgSetCarbsEntry(Calendar time, int amount) { public MsgSetCarbsEntry(Calendar time, int amount) {
this(); this();
AddParamByte((byte) DanaRRecordTypes.RECORD_TYPE_CARBO); AddParamByte((byte) RecordTypes.RECORD_TYPE_CARBO);
AddParamByte((byte) (time.get(Calendar.YEAR) % 100)); AddParamByte((byte) (time.get(Calendar.YEAR) % 100));
AddParamByte((byte) (time.get(Calendar.MONTH) + 1)); AddParamByte((byte) (time.get(Calendar.MONTH) + 1));
AddParamByte((byte) (time.get(Calendar.DAY_OF_MONTH))); AddParamByte((byte) (time.get(Calendar.DAY_OF_MONTH)));

View file

@ -5,7 +5,7 @@ import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.Config; import info.nightscout.androidaps.Config;
public class MsgSetExtendedBolusStart extends DanaRMessage { public class MsgSetExtendedBolusStart extends MessageBase {
private static Logger log = LoggerFactory.getLogger(MsgSetExtendedBolusStart.class); private static Logger log = LoggerFactory.getLogger(MsgSetExtendedBolusStart.class);
public MsgSetExtendedBolusStart() { public MsgSetExtendedBolusStart() {

View file

@ -5,7 +5,7 @@ import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.Config; import info.nightscout.androidaps.Config;
public class MsgSetExtendedBolusStop extends DanaRMessage { public class MsgSetExtendedBolusStop extends MessageBase {
private static Logger log = LoggerFactory.getLogger(MsgSetExtendedBolusStop.class); private static Logger log = LoggerFactory.getLogger(MsgSetExtendedBolusStop.class);
public MsgSetExtendedBolusStop() { public MsgSetExtendedBolusStop() {

View file

@ -5,7 +5,7 @@ import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.Config; import info.nightscout.androidaps.Config;
public class MsgSetTempBasalStart extends DanaRMessage { public class MsgSetTempBasalStart extends MessageBase {
private static Logger log = LoggerFactory.getLogger(MsgSetTempBasalStart.class); private static Logger log = LoggerFactory.getLogger(MsgSetTempBasalStart.class);
public MsgSetTempBasalStart() { public MsgSetTempBasalStart() {

View file

@ -5,7 +5,7 @@ import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.Config; import info.nightscout.androidaps.Config;
public class MsgSetTempBasalStop extends DanaRMessage { public class MsgSetTempBasalStop extends MessageBase {
private static Logger log = LoggerFactory.getLogger(MsgSetTempBasalStop.class); private static Logger log = LoggerFactory.getLogger(MsgSetTempBasalStop.class);
public MsgSetTempBasalStop() { public MsgSetTempBasalStop() {

View file

@ -9,7 +9,7 @@ import info.nightscout.androidaps.plugins.DanaR.DanaRFragment;
/** /**
* Created by mike on 05.07.2016. * Created by mike on 05.07.2016.
*/ */
public class MsgSettingActiveProfile extends DanaRMessage { public class MsgSettingActiveProfile extends MessageBase {
private static Logger log = LoggerFactory.getLogger(MsgSettingBasal.class); private static Logger log = LoggerFactory.getLogger(MsgSettingBasal.class);
public MsgSettingActiveProfile() { public MsgSettingActiveProfile() {

View file

@ -10,7 +10,7 @@ import info.nightscout.androidaps.plugins.DanaR.DanaRPump;
/** /**
* Created by mike on 05.07.2016. * Created by mike on 05.07.2016.
*/ */
public class MsgSettingBasal extends DanaRMessage { public class MsgSettingBasal extends MessageBase {
private static Logger log = LoggerFactory.getLogger(MsgSettingBasal.class); private static Logger log = LoggerFactory.getLogger(MsgSettingBasal.class);
public MsgSettingBasal() { public MsgSettingBasal() {

View file

@ -15,7 +15,7 @@ import info.nightscout.androidaps.plugins.DanaR.DanaRPump;
* THIS IS BROKEN IN PUMP... SENDING ONLY 1 PROFILE * THIS IS BROKEN IN PUMP... SENDING ONLY 1 PROFILE
* *
*/ */
public class MsgSettingBasalProfileAll extends DanaRMessage { public class MsgSettingBasalProfileAll extends MessageBase {
private static Logger log = LoggerFactory.getLogger(MsgSettingBasalProfileAll.class); private static Logger log = LoggerFactory.getLogger(MsgSettingBasalProfileAll.class);
public MsgSettingBasalProfileAll() { public MsgSettingBasalProfileAll() {

View file

@ -10,7 +10,7 @@ import info.nightscout.androidaps.plugins.DanaR.DanaRPump;
/** /**
* Created by mike on 05.07.2016. * Created by mike on 05.07.2016.
*/ */
public class MsgSettingGlucose extends DanaRMessage { public class MsgSettingGlucose extends MessageBase {
private static Logger log = LoggerFactory.getLogger(MsgSettingGlucose.class); private static Logger log = LoggerFactory.getLogger(MsgSettingGlucose.class);
public MsgSettingGlucose() { public MsgSettingGlucose() {

View file

@ -10,7 +10,7 @@ import info.nightscout.androidaps.plugins.DanaR.DanaRFragment;
/** /**
* Created by mike on 05.07.2016. * Created by mike on 05.07.2016.
*/ */
public class MsgSettingMaxValues extends DanaRMessage { public class MsgSettingMaxValues extends MessageBase {
private static Logger log = LoggerFactory.getLogger(MsgSettingMaxValues.class); private static Logger log = LoggerFactory.getLogger(MsgSettingMaxValues.class);
public MsgSettingMaxValues() { public MsgSettingMaxValues() {

View file

@ -10,7 +10,7 @@ import info.nightscout.androidaps.plugins.DanaR.DanaRPump;
/** /**
* Created by mike on 05.07.2016. * Created by mike on 05.07.2016.
*/ */
public class MsgSettingProfileRatios extends DanaRMessage { public class MsgSettingProfileRatios extends MessageBase {
private static Logger log = LoggerFactory.getLogger(MsgSettingProfileRatios.class); private static Logger log = LoggerFactory.getLogger(MsgSettingProfileRatios.class);
public MsgSettingProfileRatios() { public MsgSettingProfileRatios() {

View file

@ -10,7 +10,7 @@ import info.nightscout.androidaps.plugins.DanaR.DanaRPump;
/** /**
* Created by mike on 05.07.2016. * Created by mike on 05.07.2016.
*/ */
public class MsgSettingProfileRatiosAll extends DanaRMessage { public class MsgSettingProfileRatiosAll extends MessageBase {
private static Logger log = LoggerFactory.getLogger(MsgSettingProfileRatiosAll.class); private static Logger log = LoggerFactory.getLogger(MsgSettingProfileRatiosAll.class);
public MsgSettingProfileRatiosAll() { public MsgSettingProfileRatiosAll() {

View file

@ -8,7 +8,7 @@ import java.util.Date;
import info.nightscout.androidaps.Config; import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.plugins.DanaR.DanaRFragment; import info.nightscout.androidaps.plugins.DanaR.DanaRFragment;
public class MsgSettingPumpTime extends DanaRMessage { public class MsgSettingPumpTime extends MessageBase {
private static Logger log = LoggerFactory.getLogger(MsgSettingPumpTime.class); private static Logger log = LoggerFactory.getLogger(MsgSettingPumpTime.class);
public MsgSettingPumpTime() { public MsgSettingPumpTime() {

View file

@ -9,7 +9,7 @@ import info.nightscout.androidaps.plugins.DanaR.DanaRFragment;
/** /**
* Created by mike on 05.07.2016. * Created by mike on 05.07.2016.
*/ */
public class MsgSettingShippingInfo extends DanaRMessage { public class MsgSettingShippingInfo extends MessageBase {
private static Logger log = LoggerFactory.getLogger(MsgSettingShippingInfo.class); private static Logger log = LoggerFactory.getLogger(MsgSettingShippingInfo.class);
public MsgSettingShippingInfo() { public MsgSettingShippingInfo() {

View file

@ -6,7 +6,7 @@ import org.slf4j.LoggerFactory;
/** /**
* Created by mike on 05.07.2016. * Created by mike on 05.07.2016.
*/ */
public class MsgSettingUserOptions extends DanaRMessage { public class MsgSettingUserOptions extends MessageBase {
private static Logger log = LoggerFactory.getLogger(MsgSettingShippingInfo.class); private static Logger log = LoggerFactory.getLogger(MsgSettingShippingInfo.class);
public MsgSettingUserOptions() { public MsgSettingUserOptions() {

View file

@ -3,12 +3,10 @@ package info.nightscout.androidaps.plugins.DanaR.comm;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.util.Date;
import info.nightscout.androidaps.Config; import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.plugins.DanaR.DanaRFragment; import info.nightscout.androidaps.plugins.DanaR.DanaRFragment;
public class MsgStatus extends DanaRMessage { public class MsgStatus extends MessageBase {
private static Logger log = LoggerFactory.getLogger(MsgStatus.class); private static Logger log = LoggerFactory.getLogger(MsgStatus.class);
public MsgStatus() { public MsgStatus() {

View file

@ -7,7 +7,7 @@ import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.plugins.DanaR.DanaRFragment; import info.nightscout.androidaps.plugins.DanaR.DanaRFragment;
public class MsgStatusBasic extends DanaRMessage { public class MsgStatusBasic extends MessageBase {
private static Logger log = LoggerFactory.getLogger(MsgStatusBasic.class); private static Logger log = LoggerFactory.getLogger(MsgStatusBasic.class);
public MsgStatusBasic() { public MsgStatusBasic() {

View file

@ -16,7 +16,7 @@ import info.nightscout.androidaps.events.EventTempBasalChange;
import info.nightscout.androidaps.plugins.DanaR.DanaRFragment; import info.nightscout.androidaps.plugins.DanaR.DanaRFragment;
import info.nightscout.androidaps.plugins.DanaR.DanaRPump; import info.nightscout.androidaps.plugins.DanaR.DanaRPump;
public class MsgStatusBolusExtended extends DanaRMessage { public class MsgStatusBolusExtended extends MessageBase {
private static Logger log = LoggerFactory.getLogger(MsgStatusBolusExtended.class); private static Logger log = LoggerFactory.getLogger(MsgStatusBolusExtended.class);
public MsgStatusBolusExtended() { public MsgStatusBolusExtended() {

View file

@ -10,7 +10,7 @@ import info.nightscout.androidaps.plugins.DanaR.DanaRPump;
/** /**
* Created by mike on 05.07.2016. * Created by mike on 05.07.2016.
*/ */
public class MsgStatusProfile extends DanaRMessage { public class MsgStatusProfile extends MessageBase {
private static Logger log = LoggerFactory.getLogger(MsgStatusProfile.class); private static Logger log = LoggerFactory.getLogger(MsgStatusProfile.class);
public MsgStatusProfile() { public MsgStatusProfile() {

View file

@ -16,7 +16,7 @@ import info.nightscout.androidaps.events.EventTempBasalChange;
import info.nightscout.androidaps.plugins.DanaR.DanaRFragment; import info.nightscout.androidaps.plugins.DanaR.DanaRFragment;
import info.nightscout.androidaps.plugins.DanaR.DanaRPump; import info.nightscout.androidaps.plugins.DanaR.DanaRPump;
public class MsgStatusTempBasal extends DanaRMessage { public class MsgStatusTempBasal extends MessageBase {
private static Logger log = LoggerFactory.getLogger(MsgStatusTempBasal.class); private static Logger log = LoggerFactory.getLogger(MsgStatusTempBasal.class);
public MsgStatusTempBasal() { public MsgStatusTempBasal() {

View file

@ -3,7 +3,7 @@ package info.nightscout.androidaps.plugins.DanaR.comm;
/** /**
* Created by mike on 28.05.2016. * Created by mike on 28.05.2016.
*/ */
public class DanaRRecordTypes { public class RecordTypes {
public static final byte RECORD_TYPE_BOLUS = (byte) 0x01; public static final byte RECORD_TYPE_BOLUS = (byte) 0x01;
public static final byte RECORD_TYPE_DAILY = (byte) 0x02; public static final byte RECORD_TYPE_DAILY = (byte) 0x02;
public static final byte RECORD_TYPE_PRIME = (byte) 0x03; public static final byte RECORD_TYPE_PRIME = (byte) 0x03;

View file

@ -1,19 +1,15 @@
package info.nightscout.androidaps.plugins.DanaR.events; package info.nightscout.androidaps.plugins.DanaR.events;
public class EventDanaRConnectionStatus { public class EventDanaRConnectionStatus {
public boolean sConnecting = false; public static final int CONNECTING = 0;
public boolean sConnected = false; public static final int CONNECTED = 1;
public int sConnectionAttemptNo =0; public static final int DISCONNECTED = 2;
public EventDanaRConnectionStatus(boolean connecting, boolean connected, int connectionAttemptNo) { public int sStatus = DISCONNECTED;
sConnecting = connecting; public int sSecondsElapsed = 0;
sConnected = connected;
if(connectionAttemptNo!=0)
sConnectionAttemptNo = connectionAttemptNo;
}
public EventDanaRConnectionStatus() {
public EventDanaRConnectionStatus(int status, int secondsElapsed) {
sStatus = status;
sSecondsElapsed = secondsElapsed;
} }
} }

View file

@ -7,8 +7,11 @@ package info.nightscout.androidaps.receivers;
import android.app.AlarmManager; import android.app.AlarmManager;
import android.app.PendingIntent; import android.app.PendingIntent;
import android.content.BroadcastReceiver; import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.PowerManager; import android.os.PowerManager;
import org.slf4j.Logger; import org.slf4j.Logger;
@ -17,13 +20,35 @@ import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.Config; import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainActivity; import info.nightscout.androidaps.MainActivity;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.plugins.DanaR.DanaRFragment; import info.nightscout.androidaps.plugins.DanaR.DanaRFragment;
import info.nightscout.androidaps.plugins.DanaR.Services.DanaRService; import info.nightscout.androidaps.plugins.DanaR.Services.ExecutionService;
import info.nightscout.utils.ToastUtils;
public class KeepAliveReceiver extends BroadcastReceiver { public class KeepAliveReceiver extends BroadcastReceiver {
private static Logger log = LoggerFactory.getLogger(KeepAliveReceiver.class); private static Logger log = LoggerFactory.getLogger(KeepAliveReceiver.class);
private boolean mBounded;
private static ExecutionService mExecutionService;
ServiceConnection mConnection = new ServiceConnection() {
public void onServiceDisconnected(ComponentName name) {
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), "ExecutionService is disconnected"); // TODO: remove
mBounded = false;
mExecutionService = null;
}
public void onServiceConnected(ComponentName name, IBinder service) {
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), "ExecutionService is connected"); // TODO: remove
log.debug("Service is connected");
mBounded = true;
ExecutionService.LocalBinder mLocalBinder = (ExecutionService.LocalBinder) service;
mExecutionService = mLocalBinder.getServiceInstance();
}
};
@Override @Override
public void onReceive(Context context, Intent rIntent) { public void onReceive(Context context, Intent rIntent) {
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE); PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
@ -33,8 +58,13 @@ public class KeepAliveReceiver extends BroadcastReceiver {
log.debug("KeepAlive received"); log.debug("KeepAlive received");
DanaRFragment danaRFragment = (DanaRFragment) MainActivity.getSpecificPlugin(DanaRFragment.class); DanaRFragment danaRFragment = (DanaRFragment) MainActivity.getSpecificPlugin(DanaRFragment.class);
if (Config.DANAR && danaRFragment != null && danaRFragment.isEnabled(PluginBase.PUMP)) { if (Config.DANAR && danaRFragment != null && danaRFragment.isEnabled(PluginBase.PUMP)) {
Intent intent = new Intent(context, DanaRService.class); Thread t = new Thread(new Runnable() {
context.startService(intent); @Override
public void run() {
mExecutionService.connect("KeepAlive");
}
});
t.start();
} }
wl.release(); wl.release();
@ -50,6 +80,10 @@ public class KeepAliveReceiver extends BroadcastReceiver {
} }
am.cancel(pi); am.cancel(pi);
am.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), Constants.keepAliveMsecs, pi); am.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), Constants.keepAliveMsecs, pi);
// DanaR bind
Intent intent = new Intent(context, ExecutionService.class);
context.bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
} }
public void cancelAlarm(Context context) { public void cancelAlarm(Context context) {
@ -57,5 +91,11 @@ public class KeepAliveReceiver extends BroadcastReceiver {
PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0); PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(sender); alarmManager.cancel(sender);
// DanaR bind
if (mBounded) {
context.unbindService(mConnection);
mBounded = false;
}
} }
} }

View file

@ -76,7 +76,7 @@
<string name="lowsuspend_low_title">Hodnota nízké glykémie</string> <string name="lowsuspend_low_title">Hodnota nízké glykémie</string>
<string name="manualenacts">Ručně spuštěno</string> <string name="manualenacts">Ručně spuštěno</string>
<string name="lowsuspend_lowprojected">Předpokládaná nízká glykémie</string> <string name="lowsuspend_lowprojected">Předpokládaná nízká glykémie</string>
<string name="minago">min zpět</string> <string name="minago">m zpět</string>
<string name="minimalduration">Minimální trvání</string> <string name="minimalduration">Minimální trvání</string>
<string name="nav_backup">Záloha</string> <string name="nav_backup">Záloha</string>
<string name="nav_exit">Ukončit</string> <string name="nav_exit">Ukončit</string>

View file

@ -79,7 +79,7 @@
<string name="glucose">Glucose</string> <string name="glucose">Glucose</string>
<string name="delta">Delta</string> <string name="delta">Delta</string>
<string name="avgdelta">Avg. delta</string> <string name="avgdelta">Avg. delta</string>
<string name="minago">min ago</string> <string name="minago">m ago</string>
<string name="configbuilder">Config Builder</string> <string name="configbuilder">Config Builder</string>
<string name="lowsuspend">Low Suspend</string> <string name="lowsuspend">Low Suspend</string>
@ -260,5 +260,6 @@
<string name="danarprofile">DanaR profile settings</string> <string name="danarprofile">DanaR profile settings</string>
<string name="danarprofile_dia">DIA [h]</string> <string name="danarprofile_dia">DIA [h]</string>
<string name="danarprofile_car">Carbs absorption rate</string> <string name="danarprofile_car">Carbs absorption rate</string>
<string name="failedupdatebasalprofile">Failed to update basal profile</string>
</resources> </resources>