Merge pull request #8 from jotomo/combo-scripter-v2

combo
This commit is contained in:
Simon Pauwels 2017-12-18 19:29:35 +01:00 committed by GitHub
commit a076eda49d
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
520 changed files with 27591 additions and 7707 deletions

View file

@ -7,7 +7,7 @@ android:
components: components:
- platform-tools - platform-tools
- tools - tools
- build-tools-25.0.2 - build-tools-26.0.2
- android-23 - android-23
- extra-google-m2repository - extra-google-m2repository
- extra-android-m2repository - extra-android-m2repository

152
README-Combo.md Normal file
View file

@ -0,0 +1,152 @@
**This software is part of a DIY solution and is not a product, but
requires YOU to read, learn and understand the system and how to use it.
It is not something that does all your diabetes management for you, but
allows you to improve your diabetes and quality of life significantly
if you're willing to put in the time required.
You alone are responsible for what you do with it.**
Hardware requirements:
- A Roche Accu-Chek Combo (any firmware, they all work)
- A Smartpix or Realtyme device together with the 360 Configuration
Software to configure the pump.
Roche sends these out Smartpix devices and the configuration software
free of charge to their customers upon request.
- A compatible phone: An Android phone with a phone running LineageOS 14.1 (formerly CyanogenMod)
- To build AndroidAPS with Combo support you need the lastet Android Studio 3 version
Limitations:
- Extended bolus and multiwave bolus are not supported.
- Only one basal profile is supported.
- Setting a basal profile other than 1 on the pump, or delivering extended boluses or multiwave
boluses from the pump interferes with TBRs and forces the loop into low-suspend only mode for 6 hours
as the the loop can't run safely under those conditions.
- It's currently not possible to set the time and date on the pump, so daylight saving times
changes have to be performed manually.
- There's a bug in the pump's firmware that's triggered when "too much" communication happens
with the pump. Specifically, this issue occurs when going from just issuing commands to the pump
to reading the pumps data and history. For that reason, a minimal amount of data is read from
the pump.
The bug might still rarely occur and causes the pump to not accept any connection
unless a button is physically pressed on the pump.
Therefore, the pump's reservoir level is not read and the pump status information uploaded to Nightscout
shows fake numbers of 150 (above low threshold - which can be configured via the configuration
tool), 8 (below low threshold, triggers NS alarm since < 10) and 0 if the reservoir is empty.
Furthermore, no history (from the My Data menu) is read unless absolutely required.
Reading all pump data can be forced through the Combo tab, to import
events that happened solely on the pump, but that code has been tested less, might cause duplicates and may
trigger the bug, so it's strongly recommended to stick to the usage scenario of controlling the
pump solely through AAPS.
Checking history, reservoir level etc on the pump causes no issues but should be avoided
when the Bluetooth icon is displayed on the display, indicating that AAPS is communicating with the pump.
Setup:
- Configure pump using 360 config software.
- Set/leave the menu configuration as "Standard", this will show only the supported
menus/actions on the pump and hide those which are unsupported (extended/multiwave bolus,
multiple basal rates), which cause the loop functionality to be restricted when used because
it's not possible to run the loop in a safe manner when used.
- Set maximum TBR to 500%
- Disable end of TBR alert
- Set TBR duration step-size to 15 min
- Set low cartridge alarm to your licking
- Enable keylock (can also be set on the pump directly, see usage section on reasoning)
- Get Android Studio 3
- Get ruffy from https://github.com/jotomo/ruffy (branch `combo-scripter-v2`)
- Pair the pump, if it doesn't work, switch to the `pairing` branch, pair,
then switch back the original branch. If the pump is already paired and
can be controlled via ruffy, installing the above version is sufficient.
If AAPS is already installed, switch to the MDI plugin to avoid the Combo
plugin from interfering with ruffy during the pairing process.
Note that the pairing processing is somewhat fragile and may need a few attempts;
quickly acknowledge prompts and when starting over, remove the pump device
from the bluetooth settings beforehand
- Get AndroidAPS from https://github.com/jotomo/AndroidAPS (Branch `combo-scripter-v2`)
- Before enabling the Combo plugin in AAPS make sure you're profile is set up
correctly and your basal profile is up to date as AAPS will sync the basal profile
to the pump.
Usage:
- Keep in mind that this is not a product, esp. in the beginning the user needs to monitor and understand the system,
its limitations and how it can fail. It is strongly advised NOT to use this system when the person
using is not able to fully understand the system.
- This integration uses the same functionality which the meter provides that comes with the Combo.
The meter allows to mirror the pump screen and forwards button presses to the pump. The connection
to the pump and this forwarding is what the ruffy app does. A `scripter` components reads the screen
and automates inputing boluses, TBRs etc and making sure inputs are processed correctly (that's what
the scripter-part in the branch name stands for).
AAPS then interacts with the scripter to apply loop commands and to administer boluses.
This mode has some restrictions: it's comparatively slow (but well fast enough for what it is used for),
doesn't support reading history continuously and setting a TBR or giving a bolus causes the pump to
vibrate.
- The integration of the Combo with AndroidAPS is designed with the assumption that all inputs are
made via AndroidAPS. Boluses entered on the pump will NOT be detected by AAPS and may therefore
result in too much insulin being delivered.
- It's recommended to enable key lock on the pump to prevent bolusing from the pump, esp. when the
pump was used before and quick bolusing was a habit.
Also, with keylock enabled, accidentally pressing a key will NOT interrupt a running command
- When a BOLUS/TBR CANCELLED alert starts on the pump during bolusing or setting a TBR, this is
caused by a disconnect between pump and phone. The app will try to reconnect and confirm the alert
and then retry the last action (boluses are NOT retried for safety reasons). Therefore,
such an alarm shall be ignored (cancelling it is not a big issue, but will lead to the currently
active action to have to wait till the pump's display turns off before it can reconnect to the
pump). If the pump's alarm continues, the last action might have failed, in which case the user
needs to confirm the alarm.
- When a low cartridge or low battery alarm is raised during a bolus, they are confirmed and shown
as a notification in AAPS. If they occur while no connection is open to the pump, going to the
combo tab and hitting the Refresh button will take over those alerts by confirming them and
showing a notification in AAPS.
- When AAPS fails to confirm a TBR CANCELLED alert, or one is raised for a different reason,
hitting Refresh in the Combo tab establishes a connection, confirms the alert and shows
a notification for it in AAPS. This can safely be done, since those alerts are benign - an
appropriate TBR will be set again during the next loop iteration.
- For all other alerts raised by the pump: connecting to the pump will show the alert message in
the Combo tab, e.g. "State: E4: Occlusion" as well as showing a notification on the main screen.
An error will raise an urgent notification.
- After pairing, ruffy should not be used directly (AAPS will start in the background as needed),
since using ruffy at AAPS at the same time is not supported.
- If AAPS crashes (or is stopped from the debugger) while AAPS and the pump were comunicating (using
ruffy), it might be necessary to force close ruffy. Restarting AAPS will start ruffy again.
- Read the documentation on the wiki as well as the docs at https://openaps.org
- Don't press any buttons on the pump while AAPS communicates with the pump (Bluetooth logo is
shown on the pump).
- If the loop requests a running TBR to be cancelled the Combo will set a TBR of 90% or 110%
for 15 minutes instead. This is because cancelling a TBR causes an alert on the pump which
causes a lot of vibrations.
- Due to the bug (which causes the pump to become unreachable when reading history regularly),
a delivered bolus will NOT be added to treatments when the connection was lost during bolusing
or when a pump error occurs (e.g. occlusion). This will raise a message (and play an annoying
sound) and the user will have a create a bolus record via Careportal/NS manually. Currently
this requires an available NS installation and being online (for a short time). Hopefully
both of these issues can be resolved in future versions.
Known issues:
- On phones with low memory (or aggressive power saving settings), Android may kill
AAPS frequently (if the buttons on the overview screen aren't displayed when opening
AAPS, the app was started again after Android killed it).
This may trigger false 'pump unreachable alarms' on start.
See the Combo tab's "last connection" field to check when the pump was last connected.
This may drain the pump's battery quicker since on startup the basal profile is read
from the pump. This may also increase the chance to hit the bug that makes the pump
reject all incoming connections until a button on the pump is pressed.
- Occasionally (every couple of days or less) AAPS might fail to automatically cancel
a TBR CANCELLED alert and needs to be dealt with (press the refresh button in AAPS
to transfer the warning to AAPS or confirm the alert on the pump). Similarly, the
'pump unreachable' bug may occur from time to time.
- Overall the integration seems rather robust, but there are limits to the way the
pump is controlled and how stable BT is, so there will be minor issues like the above
from time to time, though they're small compared to what works well.
Reporting bugs:
- Note the precise time the problem occurred and describe the circumstances and steps that caused
the problem
- Note the Build version (found in the About dialog in the app, when pressing the three dots in the
upper-right corner).
- Attach the app's log files, which can be found on the phone in
_/storage/emulated/0/Android/data/info.nightscout.androidaps/_
Components/Layers (developers):
- AndroidAPS
- ComboPlugin
- ruffy-spi (RuffyCommands interface to plug in lower layer)
- Scripting layer (ruffyscripter) / Command layer
- Driver layer (ruffy)

142
TODO-Combo.md Normal file
View file

@ -0,0 +1,142 @@
- [x] Bugs
- [-] Pump stops to response to connect attemps every 2-20h or so, only reacting
again when physically pressing a button on the pump ...
Occassionally the pump starts to accept connections again, sometimes
after 40m, sometimes no luck even after 80m
Stuff tried without success:
- Restarting BT
- Restarting ruffy
- Restarting AAPS
- Restarting phone
- Removing rtDisconnect on failed connect attempt (RuffyScripter.ensureConnected)
- Ruffy v1 branch with minimal NPE fixes and needed menus
Observations:
- Last command run beforehand was a short one, connection time < 1m
- It's unrelated to battery voltage.
- Auto off is disabled
- Keylock makes no difference
Speculations:
Did this already happen before the whole 'basal profile' thing?
Takes ages, could that trigger some weird bug that has never
surfaced in any other scenario before?
- [-] Temp basal history shows TBRs twice, once with a 1 min
duration and then with the reminder; caused by clock not
being within ~30s of the phone.
Cancelling TBR or overriding a running one with a new one
(both cases require a TBR end record) require an end TBR record.
checkTbrMismatch causes history read and TBR is right in AAPS
so far and any TBR set on the pump is cancelled, so it works,
but isn't clean. Needs some rethink - with a fresh mind -
maybe understanding what DanaR does, how to translate it to
the Combo.
Explicit end records when adding pump history records;
and/or: logic to detect time differences and align data
Current solution works, albeit a bit ugly, but is used in rare
circumstances where clock might be off anyway, so this would
still occur.
- [x] Deleting a bolus from the history re-adds it from the pump's
history. Deleting it again, flags it as invalid at which point
it will not be added to IOB and not be re-added.
- [x] Taking over benign warnings on connect doesn't work properly
(Notification raised but not confirmed?)
- [x] Optimization reading full history doesn't seem to work
- [x] Reading full history multiple times duplicates entries shown in Stats/TDD dialog
- [x] ruffy: Accessing the quick info menu yields noMenu when cartridge is low
- [x] ruffy: Multi-digit error codes in error history aren't supported
- [-] No connection can be established anymore; ruffy issue i can't solve
- Removing the BT device's bonding (!=pairing) fixes it; nope it doesn't
- Ruffy logs in BTConnection:163 handler.fail("no connection possible: " + e.getMessage());
- When developing (and thus killing/restarting AAPS often) this is trigger more frequently, leaving
some ruffy-releated (BT) cache in disarray? Immune to wiping, only repairing seems to work so far
- [x] Timeout connecting to pump -> crash (result.state wasn't filled in case of timeout)
- [x] Bolus deleted in treatments (marked invalid?!) is re-added when pump reads history
Probably fixed through other bugfixes, irrelevant though as "pump history records" can't
be deleted in AAPS
- [x] Issue of creating TBR start date from main menu time, which might be off by a minute
when we read it as a history record. End date time might be slightly off, unless
CancelTempBasal is updated to read from history (probably not worth it).
What would happen if while setting the TBR the start time was 12:01 but then
we read a history record with a start time of 12:02, both running 30min.
Would the former be trimmed to 1m? That'd be acceptable (this edge case occurs
if between confirm the TBR and reading the main menu date, the second goes
from 59.9999 to 0)
Only in issue if TBR was set on pump. In that case the TBR is cancelled and the
resulting history record is read
- [x] Tasks
- [x] Main
- [x] On command error: recover by returning to main menu
check entry and exit points of commands
- [x] Taking over alerts
- [x] On connect
- [x] During bolusing
- Can the low warning be set as high as 280 or so? To be able to trigger it with a quick refill? yup.
- [x] Check for errors first thing in runCommand? Whenever analysing a CommandResult?
- [x] forward all warnings and errors encountered, but only confirm benign ones
- [-] Reporting back failures in UI, maybe warn if lots of errors (unreachable alert might
already be enough, since it's based on 'lastSuccessfulConnection', where a connection is
considered successful if the command during that connection succeeded.
KeepAlive triggered check suffices.
- [x] Finish ComboPlugin structure to only have to plug date setting and pump setting in later
(actually, just use stub methods)
- [-] Updating time on pump
- [x] Raise a warning if time clock is off
- [-] Ruffy: support reading date/time menus
- [x] Setting pump basal profile
- [x] Overview notification on updated/failed basal profile
- [-] Pairing (and sourcing ruffy)
- [x] Run readReservoirAndBolusLevel after SetTbr too so boluses on the pump are caught sooner?
Currently the pump gets to know such a record when bolusing or when refresh() is called
after 15m of no other command taking place. IOB will then be current with next loop
checkPumpHistory is now called every 15m the least after executing a command
- [x] Reading history
- [x] Bolus
- [x] Read
- [x] Update DB
- [x] TBRs
- [x] Read
- [x] Update DB
- [x] Alerts
- [x] Read
- [x] Update DB? No, but raise an alert if new ones are found beyond those read at startup
(Those that occurred while AAPS was not active needn't be turned into alarms,
the user had to deal with them on the pump already). (Done via "Taking over alerts")
- [x] Display in UI
- [x] TDD
- [x] Read
- [x] Update DB? No, just write to plugin cache
- [x] Display in UI
- [x] Optimize reading full history to pass timestamps of last known records to avoid reading known records
iteration.
- [x] Cleanups
- [x] TBR cancel logic
- [x] Check dynamic timeout logic in RuffyScripter.runCommand
- [x] Finish 'enacted' removal rewrite (esp. cancel tbr)
- [x] ComboPlugin, commands invocation, checks, upadting combo store/cache
- [x] Finish reconnect
- [x] Adrian says: when changing time; last treatments timestamp is updated??
- Nope, at least not with a 2014 pump (SW1.06?)
- [x] Reconnect and auto-retry for commands
- [x] Empty battery state
- [x] Integrate alarms
- [x] Remove combo alerter thread
- [x] Display errors in combo tab(?), nope notifications are better suited; also there's the alerts thing already
- [x] Option to raise overview notifications as android notification with noise (for urgent ones?)
- [ ] Next version(s)
- [ ] State in ComboPump is not safely shared among threads
- [x] Naming is messed up: pump has warnings and errors, which cause alerts; W+E are thus alerts,
e.g. pumpAlertHistory should be renamed to alertHistory
- [x] Enable BT if disabled? does DanaR does this? BT watchdog in CommandQueue takes care of it
- [-] Finish and test German translation
- [x] No clean startup/shutdown; RuffyScripter is instanciated once, idle disconnect thread never killed
- Application shut down is broken with PersistentNotification (never shut down) and WearPlugin -
Android logs it as crashed and restarts it, thereby restarting the app (or just keeping it alive,
also causes errors with the DB as there were attemtps to open a closed DB instance/ref.
Does xDrip intents start AAPS? Starts automatically (but not instantly) after boot and there's no "start on boot" setting enabled
CommandQueue now issues disconnect and the idle-disconnect-monitor has been removed.
- [ ] Check if TBRs are set to often from ConfigBuilder on high base basal rates (basalstep is 0.01; in reality larger on >1U/h base basal)
- [ ] With long running commands (e.g. setting basal rate, which can take up to 5m), multiple 'set tbr' commands
may stack up. Since setting a TBR multiple times in one minute fails, the ComboPlugin rejects such
request, letting the oldest TBR run till the net iteration. This can potentially be nicely solved
through the queue branch. However, the original problem is the amount of time the Combo can
take to execute commands, which might go away (mostly) with command mode.
- [ ] Fix display of alarms on mainscreen (increase height if needed)

104
Testing-Combo.md Normal file
View file

@ -0,0 +1,104 @@
- [ ] Pairing
- [ ] Pairing works with `combo-scripter-v2` branch
- [ ] Bolusing
- [ ] Cancelling bolus at various stages shall not yield an error but cancel the bolus. If
cancelled before delivery started, no treatment must have been added, if cancel after delivery
started, the partially delivered bolus must have been added to treatments
- [ ] Enter a bolus of 2 U and press cancel when delivery is at 1.7 (cancelling requires AAAPS
to press the up button for 3 seconds, so the cancellation attempt will not succeed because delivery
ends before those 3 seconds are elapsed). The code should handle this without giving an
error and add the full bolus to treatments.
- [ ] Recovery from connection issues during bolusing
- [ ] Pressing a button on the pump during delivery => Progress dialog freezes, then states that recovery
is in process and then closes; no error dialog, record correctly added to treatments
- [ ] Breaking the connection e.g. by moving the pump away from phone for up to a minute => same as above
- [ ] Same as above but put pump out of reach for 5 minutes => Error dialog, no record in treatments
- [ ] Starting a bolus bigger than what's left in the reservoir => Error dialog and a record in treatments with the partially delivered bolus
- [ ] When the connection breaks during bolusing, pressing the cancel button should not interfere with recovery and
the delivered bolus should be added to treatments
- [ ] Low cartridge alarm during bolus
- [ ] alarm must be confirmed by AAPS
- [ ] bolus must have been fully delivered by pump
- [ ] bolus must have been added to DB
- [ ] the confirmed pump warning must be raised as a notification in AAPS
(or as android notification on watch/smartphone if setting "use system notifications ..." is enabled
- [ ] Pressing a button on the pump, or moving the pump away from the phone to break connection
must confirm the pump alert and recover to finish the bolusing.
- [ ] If recovery fails, an error popup must be displayed
- [ ] Test bolusing a bolus bigger than what's left in the reservoir. A message to check what
was actually delivered must appear (this is a corner-case where we practically can't
check what was actually delivered).
- [ ] Pressing a button on the pump before bolus delivery started must be handled gracefully
- [ ] Same as above, but moving pump out of range
- [ ] Pressing a button on the pump after bolus delivery has started will freeze the progress bar,
initiate recovery and add the delivered bolus the treatments.
- [ ] Same as above, but moving pump out of range
- [ ] Test the highest bolus you'd ever give yourself (AAPS has a configurable limit and the pump
has a limit which can be configured with the Config SW), no timeout or other issues must show
- [ ] BT disconnect issues
- [ ] Moving pump out of reach when setting TBR causes "TBR cancelled" alarm on pump.
When putting pump close to phone, AAPS must confirm the alert and successfully
retry setting TBR (reconnects are a best-effort kind of a thing, so this might not always work)
- [ ] When a disconnect occurs, the pump's screen shows the error and the pump only accepts a connection
again when the pump's menu(?) timeout has occurred. A recovery should be quicker if that timeout is decreased.
It might be interesting to experiment with the Config software to set lower menu or display timeouts
(or whatever they're called ...) to improve recovery speed.
- [ ] AAPS start
- [ ] Starting AAPS without a reachable pump must show something sensible in the Combo tab
(not hanging indefinitely with "initializing" activity)
- [ ] Starting AAPS without a reachable pump must trigger "pump unrechable" alert after the configured threshold
- [ ] If the pump's basal profile doesn't match AAPS', the pump must be updated when AAPS starts
- [ ] Read history using Smartpix and compare with AAPS' DB (treatment tab)
Esp. those times we communication was interrupted, boluses were cancelled, ...
- [ ] Boluses
- [ ] TBR
- [ ] Alerts
- [ ] Disconnected pump (pump unreachable)
- [ ] With local alerts enabled for 'pump unreachable', an alert must be triggered within 5 minutes
after the configured threshold. (Don't set the threshold too low, e.g. 10 minutes, since
there might be no need to set a TBR within such a short time, but since there was no pump connection
within that time, the alarm would be triggered).
- [ ] Refilling cartridge
- [ ] If TBR was cancelled by refilling, AAPS must detect this and create a TBR record in AAPS
based on what the pump displays (not the full TBR duration, but what is displayed as remaining
on the main screen.
- [ ] Stress testing
- PersistentNotification plugin disabled
- Lots of comms running, like Wifi, GSM, BT audio
- AAPS running in background
- Foreground app stresses the phone's memory, CPU (like a game) (potentially) pushing AAPS out of memory
- [ ] TBR must still be set/cancelled while running in the background
- [ ] With the pump powered off or out of reach, the 'pump unreachable alert' must still
trigger
- [ ] Combo tab
- [ ] Check displayed data (state, battery, reservoir, temp basal) is the same
as on the pump
- [ ] Unsafe usage
- [ ] An extended or multiwave bolus given within the last six hour must raise an alert and
restrict the loop functionality to low-suspend only (setting maxIOB to zero)
- [ ] Closed loop functionality must resume 6 h after the last ext/multiwave bolus
- [ ] An active ext/multiwave bolus must also raise an alert and restrict the loop
- [ ] If a basal rate other than profile 1 is activated, this must also raise an alert and disable
the restrict the loop
- [ ] Reading/setting basal profile
- [ ] AAPS reads basal rate properly
- [ ] Test profile with 115% (or something like that) change to ask the
pump for basal rates like 0.812, which should then be set propely
- [ ] Updating the profile extensively (200%, shifting time) takes up to 6 minutes, but
should complete without timeout.
- [ ] Doing a profile change (to shift time or increase/decrease insulin), the pump's basal profile must be updated
- [ ] If a profile change has a duration, the pump's basal profile must be set to the original value again at the end
(this can vary a few minutes between what the overview screen shows and when the pump is updated, as the check
whether the pump is up-to-date or not is performed periodically and not at the exact minute a profile change ends)
- [ ] Taking over alerts
- [ ] If an error alert is active on the pump, pressing refresh shall display the error
in the Combo tab but NOT confirm it. Easiest error to trigger: rewind piston
and attempt to start the pump, this will trigger E11: Not primed.
- [ ] Pressing refresh while a low cartridge or low battery alarm is active
must confirm the alarm, indicate the new status in the Combo tab and
show a notification on the overview screen
- [ ] A TBR CANCELLED is now also taken over when refreshing (since it's a benign error the loop will correct
during the next iteration).
- [ ] Misc
- [ ] Pump state is correctly uploaded to Nightscout (note that reservoir level are fake numbers representing
norma/low/empty).

View file

@ -37,16 +37,21 @@ def generateGitBuild = { ->
android { android {
compileSdkVersion 23 compileSdkVersion 23
buildToolsVersion "25.0.2" buildToolsVersion "26.0.2"
defaultConfig { defaultConfig {
applicationId "info.nightscout.androidaps" applicationId "info.nightscout.androidaps"
minSdkVersion 21 minSdkVersion 21
targetSdkVersion 23 targetSdkVersion 23
multiDexEnabled true
versionCode 1500 versionCode 1500
version "1.51" version "1.56-combo-csv2-test"
buildConfigField "String", "VERSION", '"' + version + '"' buildConfigField "String", "VERSION", '"' + version + '"'
buildConfigField "String", "BUILDVERSION", generateGitBuild() buildConfigField "String", "BUILDVERSION", generateGitBuild()
ndk {
moduleName "BleCommandUtil"
}
} }
lintOptions { lintOptions {
disable 'MissingTranslation' disable 'MissingTranslation'
@ -58,7 +63,7 @@ android {
} }
} }
productFlavors { productFlavors {
flavorDimensions "standard", "wear" flavorDimensions "standard"
full { full {
dimension "standard" dimension "standard"
resValue "string", "app_name", "AndroidAPS" resValue "string", "app_name", "AndroidAPS"
@ -70,6 +75,7 @@ android {
buildConfigField "boolean", "PUMPDRIVERS", "true" buildConfigField "boolean", "PUMPDRIVERS", "true"
buildConfigField "boolean", "NSCLIENTOLNY", "false" buildConfigField "boolean", "NSCLIENTOLNY", "false"
buildConfigField "boolean", "CLOSEDLOOP", "true" buildConfigField "boolean", "CLOSEDLOOP", "true"
buildConfigField "boolean", "G5UPLOADER", "false"
} }
openloop { openloop {
dimension "standard" dimension "standard"
@ -82,6 +88,7 @@ android {
buildConfigField "boolean", "PUMPDRIVERS", "true" buildConfigField "boolean", "PUMPDRIVERS", "true"
buildConfigField "boolean", "NSCLIENTOLNY", "false" buildConfigField "boolean", "NSCLIENTOLNY", "false"
buildConfigField "boolean", "CLOSEDLOOP", "false" buildConfigField "boolean", "CLOSEDLOOP", "false"
buildConfigField "boolean", "G5UPLOADER", "false"
} }
pumpcontrol { pumpcontrol {
dimension "standard" dimension "standard"
@ -94,6 +101,7 @@ android {
buildConfigField "boolean", "PUMPDRIVERS", "true" buildConfigField "boolean", "PUMPDRIVERS", "true"
buildConfigField "boolean", "NSCLIENTOLNY", "false" buildConfigField "boolean", "NSCLIENTOLNY", "false"
buildConfigField "boolean", "CLOSEDLOOP", "false" buildConfigField "boolean", "CLOSEDLOOP", "false"
buildConfigField "boolean", "G5UPLOADER", "false"
} }
nsclient { nsclient {
dimension "standard" dimension "standard"
@ -106,24 +114,26 @@ android {
buildConfigField "boolean", "PUMPDRIVERS", "false" buildConfigField "boolean", "PUMPDRIVERS", "false"
buildConfigField "boolean", "NSCLIENTOLNY", "true" buildConfigField "boolean", "NSCLIENTOLNY", "true"
buildConfigField "boolean", "CLOSEDLOOP", "false" buildConfigField "boolean", "CLOSEDLOOP", "false"
buildConfigField "boolean", "G5UPLOADER", "false"
} }
wear { g5uploader {
dimension "wear" dimension "standard"
buildConfigField "boolean", "WEAR", "true" resValue "string", "app_name", "NSClient"
buildConfigField "boolean", "WEAR_CONTROL", "false" versionName version + "-nsclient"
manifestPlaceholders = [
} appIcon: "@mipmap/yellowowl"
wearcontrol { ]
dimension "wear" buildConfigField "boolean", "APS", "false"
buildConfigField "boolean", "WEAR", "true" buildConfigField "boolean", "PUMPDRIVERS", "false"
buildConfigField "boolean", "WEAR_CONTROL", "true" buildConfigField "boolean", "NSCLIENTOLNY", "false"
} buildConfigField "boolean", "CLOSEDLOOP", "false"
nowear { buildConfigField "boolean", "G5UPLOADER", "true"
dimension "wear"
buildConfigField "boolean", "WEAR", "false"
buildConfigField "boolean", "WEAR_CONTROL", "false"
} }
} }
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
} }
allprojects { allprojects {
@ -136,8 +146,7 @@ allprojects {
} }
dependencies { dependencies {
wearWearApp project(path: ':wear', configuration: 'restrictedRelease') wearApp project(':wear')
wearcontrolWearApp project(path: ':wear', configuration: 'fullRelease')
compile fileTree(include: ['*.jar'], dir: 'libs') compile fileTree(include: ['*.jar'], dir: 'libs')
compile('com.crashlytics.sdk.android:crashlytics:2.6.7@aar') { compile('com.crashlytics.sdk.android:crashlytics:2.6.7@aar') {
@ -161,9 +170,9 @@ dependencies {
compile('com.github.tony19:logback-android-classic:1.1.1-6') { compile('com.github.tony19:logback-android-classic:1.1.1-6') {
exclude group: 'com.google.android', module: 'android' exclude group: 'com.google.android', module: 'android'
} }
compile 'org.apache.commons:commons-lang3:3.6'
compile 'org.slf4j:slf4j-api:1.7.12' compile 'org.slf4j:slf4j-api:1.7.12'
compile 'com.jjoe64:graphview:4.0.1' compile 'com.jjoe64:graphview:4.0.1'
compile 'com.eclipsesource.j2v8:j2v8:3.1.6@aar'
compile 'com.joanzapata.iconify:android-iconify-fontawesome:2.1.1' compile 'com.joanzapata.iconify:android-iconify-fontawesome:2.1.1'
compile 'com.google.android.gms:play-services-wearable:7.5.0' compile 'com.google.android.gms:play-services-wearable:7.5.0'
compile 'junit:junit:4.12' compile 'junit:junit:4.12'
@ -173,7 +182,7 @@ dependencies {
androidTestCompile 'com.google.dexmaker:dexmaker:1.2' androidTestCompile 'com.google.dexmaker:dexmaker:1.2'
androidTestCompile 'com.google.dexmaker:dexmaker-mockito:1.2' androidTestCompile 'com.google.dexmaker:dexmaker-mockito:1.2'
compile(name: 'android-edittext-validator-v1.3.4-mod', ext: 'aar') compile(name: 'android-edittext-validator-v1.3.4-mod', ext: 'aar')
compile ('com.google.android:flexbox:0.3.0') { compile('com.google.android:flexbox:0.3.0') {
exclude group: 'com.android.support' exclude group: 'com.android.support'
} }
compile('io.socket:socket.io-client:0.8.3') { compile('io.socket:socket.io-client:0.8.3') {
@ -182,5 +191,5 @@ dependencies {
} }
compile 'com.google.code.gson:gson:2.7' compile 'com.google.code.gson:gson:2.7'
compile 'com.google.guava:guava:20.0' compile 'com.google.guava:guava:20.0'
compile project(path: ':ruffyscripter')
} }

BIN
app/libs/rhino-1.7.7.2.jar Normal file

Binary file not shown.

View file

@ -17,6 +17,7 @@
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="com.google.android.permission.PROVIDE_BACKGROUND" /> <uses-permission android:name="com.google.android.permission.PROVIDE_BACKGROUND" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission-sdk-23 android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" /> <uses-permission-sdk-23 android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
@ -41,6 +42,9 @@
<activity <activity
android:name=".plugins.Overview.Dialogs.BolusProgressHelperActivity" android:name=".plugins.Overview.Dialogs.BolusProgressHelperActivity"
android:theme="@style/Theme.AppCompat.Translucent" /> android:theme="@style/Theme.AppCompat.Translucent" />
<activity
android:name=".plugins.Overview.Dialogs.ErrorHelperActivity"
android:theme="@style/Theme.AppCompat.Translucent" />
<activity android:name=".AgreementActivity" /> <activity android:name=".AgreementActivity" />
<activity android:name=".plugins.PumpDanaR.activities.DanaRHistoryActivity" /> <activity android:name=".plugins.PumpDanaR.activities.DanaRHistoryActivity" />
<activity android:name=".plugins.PumpDanaR.activities.DanaRStatsActivity" /> <activity android:name=".plugins.PumpDanaR.activities.DanaRStatsActivity" />
@ -50,6 +54,13 @@
<category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.DEFAULT" />
</intent-filter> </intent-filter>
</activity> </activity>
<activity android:name=".plugins.PumpDanaRS.activities.BLEScanActivity">
<intent-filter>
<action android:name="info.nightscout.androidaps.plugins.PumpDanaRS.activities.BLEScanActivity" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity android:name=".plugins.PumpDanaRS.activities.PairingHelperActivity" />
<receiver <receiver
android:name=".receivers.DataReceiver" android:name=".receivers.DataReceiver"
@ -64,6 +75,8 @@
<action android:name="com.eveningoutpost.dexdrip.NS_EMULATOR" /> <action android:name="com.eveningoutpost.dexdrip.NS_EMULATOR" />
<!-- Receiver from glimp --> <!-- Receiver from glimp -->
<action android:name="it.ct.glicemia.ACTION_GLUCOSE_MEASURED" /> <action android:name="it.ct.glicemia.ACTION_GLUCOSE_MEASURED" />
<!-- Receiver from DexcomG5 -->
<action android:name="com.dexcom.cgm.DATA" />
</intent-filter> </intent-filter>
</receiver> </receiver>
<!-- Receiver keepalive, scheduled every 30 min --> <!-- Receiver keepalive, scheduled every 30 min -->
@ -113,6 +126,10 @@
android:name=".plugins.PumpDanaRv2.services.DanaRv2ExecutionService" android:name=".plugins.PumpDanaRv2.services.DanaRv2ExecutionService"
android:enabled="true" android:enabled="true"
android:exported="false" /> android:exported="false" />
<service
android:name=".plugins.PumpDanaRS.services.DanaRSService"
android:enabled="true"
android:exported="true"></service>
<service <service
android:name=".plugins.Wear.wearintegration.WatchUpdaterService" android:name=".plugins.Wear.wearintegration.WatchUpdaterService"
android:exported="true"> android:exported="true">
@ -128,6 +145,9 @@
android:name=".Services.AlarmSoundService" android:name=".Services.AlarmSoundService"
android:enabled="true" android:enabled="true"
android:exported="true" /> android:exported="true" />
<service
android:name=".plugins.Overview.notifications.DismissNotificationService"
android:exported="false"></service>
<meta-data <meta-data
android:name="io.fabric.ApiKey" android:name="io.fabric.ApiKey"

View file

@ -0,0 +1,12 @@
var console = { };
console.error = function error(){
for (var i = 0, len = arguments.length; i < len; i++) {
console2.log(arguments[i]);
}
};
console.log = function log(){
for (var i = 0, len = arguments.length; i < len; i++) {
console2.log(arguments[i]);
}
};

View file

@ -15,7 +15,7 @@
<maxHistory>120</maxHistory> <maxHistory>120</maxHistory>
</rollingPolicy> </rollingPolicy>
<encoder> <encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level [%file:%line]: %msg%n</pattern> <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level [%class:%line]: %msg%n</pattern>
</encoder> </encoder>
</appender> </appender>
@ -24,7 +24,7 @@
<pattern>%logger{0}</pattern> <pattern>%logger{0}</pattern>
</tagEncoder> </tagEncoder>
<encoder> <encoder>
<pattern>[%thread] %-5level [%file:%line]: %msg%n</pattern> <pattern>[%thread] %-5level [%class:%line]: %msg%n</pattern>
</encoder> </encoder>
</appender> </appender>

View file

@ -0,0 +1,120 @@
package com.cozmo.danar.util;
import android.content.Context;
import info.nightscout.androidaps.MainApp;
public class BleCommandUtil {
public static final int DANAR_PACKET__TYPE_ENCRYPTION_REQUEST = 0x01;
public static final int DANAR_PACKET__TYPE_ENCRYPTION_RESPONSE = 0x02;
public static final int DANAR_PACKET__TYPE_COMMAND = 0xA1;
public static final int DANAR_PACKET__TYPE_RESPONSE = 0xB2;
public static final int DANAR_PACKET__TYPE_NOTIFY = 0xC3;
public static final int DANAR_PACKET__OPCODE_ENCRYPTION__PUMP_CHECK = 0x00;
public static final int DANAR_PACKET__OPCODE_ENCRYPTION__CHECK_PASSKEY = 0xD0;
public static final int DANAR_PACKET__OPCODE_ENCRYPTION__PASSKEY_REQUEST = 0xD1;
public static final int DANAR_PACKET__OPCODE_ENCRYPTION__PASSKEY_RETURN = 0xD2;
public static final int DANAR_PACKET__OPCODE_ENCRYPTION__TIME_INFORMATION = 0x01;
public static final int DANAR_PACKET__OPCODE_NOTIFY__DELIVERY_COMPLETE = 0x01;
public static final int DANAR_PACKET__OPCODE_NOTIFY__DELIVERY_RATE_DISPLAY = 0x02;
public static final int DANAR_PACKET__OPCODE_NOTIFY__ALARM = 0x03;
public static final int DANAR_PACKET__OPCODE_NOTIFY__MISSED_BOLUS_ALARM = 0x04;
public static final int DANAR_PACKET__OPCODE_REVIEW__INITIAL_SCREEN_INFORMATION = 0x02;
public static final int DANAR_PACKET__OPCODE_REVIEW__DELIVERY_STATUS = 0x03;
public static final int DANAR_PACKET__OPCODE_REVIEW__GET_PASSWORD = 0x04;
public static final int DANAR_PACKET__OPCODE_REVIEW__BOLUS_AVG = 0x10;
public static final int DANAR_PACKET__OPCODE_REVIEW__BOLUS = 0x11;
public static final int DANAR_PACKET__OPCODE_REVIEW__DAILY = 0x12;
public static final int DANAR_PACKET__OPCODE_REVIEW__PRIME = 0x13;
public static final int DANAR_PACKET__OPCODE_REVIEW__REFILL = 0x14;
public static final int DANAR_PACKET__OPCODE_REVIEW__BLOOD_GLUCOSE = 0x15;
public static final int DANAR_PACKET__OPCODE_REVIEW__CARBOHYDRATE = 0x16;
public static final int DANAR_PACKET__OPCODE_REVIEW__TEMPORARY = 0x17;
public static final int DANAR_PACKET__OPCODE_REVIEW__SUSPEND = 0x18;
public static final int DANAR_PACKET__OPCODE_REVIEW__ALARM = 0x19;
public static final int DANAR_PACKET__OPCODE_REVIEW__BASAL = 0x1A;
public static final int DANAR_PACKET__OPCODE_REVIEW__ALL_HISTORY = 0x1F;
public static final int DANAR_PACKET__OPCODE_REVIEW__GET_SHIPPING_INFORMATION = 0x20;
public static final int DANAR_PACKET__OPCODE_REVIEW__GET_PUMP_CHECK = 0x21;
public static final int DANAR_PACKET__OPCODE_REVIEW__GET_USER_TIME_CHANGE_FLAG = 0x22;
public static final int DANAR_PACKET__OPCODE_REVIEW__SET_USER_TIME_CHANGE_FLAG_CLEAR = 0x23;
public static final int DANAR_PACKET__OPCODE_REVIEW__GET_MORE_INFORMATION = 0x24;
public static final int DANAR_PACKET__OPCODE_REVIEW__SET_HISTORY_UPLOAD_MODE = 0x25;
public static final int DANAR_PACKET__OPCODE_REVIEW__GET_TODAY_DELIVERY_TOTAL = 0x26;
public static final int DANAR_PACKET__OPCODE_BOLUS__GET_STEP_BOLUS_INFORMATION = 0x40;
public static final int DANAR_PACKET__OPCODE_BOLUS__GET_EXTENDED_BOLUS_STATE = 0x41;
public static final int DANAR_PACKET__OPCODE_BOLUS__GET_EXTENDED_BOLUS = 0x42;
public static final int DANAR_PACKET__OPCODE_BOLUS__GET_DUAL_BOLUS = 0x43;
public static final int DANAR_PACKET__OPCODE_BOLUS__SET_STEP_BOLUS_STOP = 0x44;
public static final int DANAR_PACKET__OPCODE_BOLUS__GET_CARBOHYDRATE_CALCULATION_INFORMATION = 0x45;
public static final int DANAR_PACKET__OPCODE_BOLUS__GET_EXTENDED_MENU_OPTION_STATE = 0x46;
public static final int DANAR_PACKET__OPCODE_BOLUS__SET_EXTENDED_BOLUS = 0x47;
public static final int DANAR_PACKET__OPCODE_BOLUS__SET_DUAL_BOLUS = 0x48;
public static final int DANAR_PACKET__OPCODE_BOLUS__SET_EXTENDED_BOLUS_CANCEL = 0x49;
public static final int DANAR_PACKET__OPCODE_BOLUS__SET_STEP_BOLUS_START = 0x4A;
public static final int DANAR_PACKET__OPCODE_BOLUS__GET_CALCULATION_INFORMATION = 0x4B;
public static final int DANAR_PACKET__OPCODE_BOLUS__GET_BOLUS_RATE = 0x4C;
public static final int DANAR_PACKET__OPCODE_BOLUS__SET_BOLUS_RATE = 0x4D;
public static final int DANAR_PACKET__OPCODE_BOLUS__GET_CIR_CF_ARRAY = 0x4E;
public static final int DANAR_PACKET__OPCODE_BOLUS__SET_CIR_CF_ARRAY = 0x4F;
public static final int DANAR_PACKET__OPCODE_BOLUS__GET_BOLUS_OPTION = 0x50;
public static final int DANAR_PACKET__OPCODE_BOLUS__SET_BOLUS_OPTION = 0x51;
public static final int DANAR_PACKET__OPCODE_BASAL__SET_TEMPORARY_BASAL = 0x60;
public static final int DANAR_PACKET__OPCODE_BASAL__TEMPORARY_BASAL_STATE = 0x61;
public static final int DANAR_PACKET__OPCODE_BASAL__CANCEL_TEMPORARY_BASAL = 0x62;
public static final int DANAR_PACKET__OPCODE_BASAL__GET_PROFILE_NUMBER = 0x63;
public static final int DANAR_PACKET__OPCODE_BASAL__SET_PROFILE_NUMBER = 0x64;
public static final int DANAR_PACKET__OPCODE_BASAL__GET_PROFILE_BASAL_RATE = 0x65;
public static final int DANAR_PACKET__OPCODE_BASAL__SET_PROFILE_BASAL_RATE = 0x66;
public static final int DANAR_PACKET__OPCODE_BASAL__GET_BASAL_RATE = 0x67;
public static final int DANAR_PACKET__OPCODE_BASAL__SET_BASAL_RATE = 0x68;
public static final int DANAR_PACKET__OPCODE_BASAL__SET_SUSPEND_ON = 0x69;
public static final int DANAR_PACKET__OPCODE_BASAL__SET_SUSPEND_OFF = 0x6A;
public static final int DANAR_PACKET__OPCODE_OPTION__GET_PUMP_TIME = 0x70;
public static final int DANAR_PACKET__OPCODE_OPTION__SET_PUMP_TIME = 0x71;
public static final int DANAR_PACKET__OPCODE_OPTION__GET_USER_OPTION = 0x72;
public static final int DANAR_PACKET__OPCODE_OPTION__SET_USER_OPTION = 0x73;
public static final int DANAR_PACKET__OPCODE_BASAL__APS_SET_TEMPORARY_BASAL = 0xC1;
public static final int DANAR_PACKET__OPCODE__APS_HISTORY_EVENTS = 0xC2;
public static final int DANAR_PACKET__OPCODE__APS_SET_EVENT_HISTORY = 0xC3;
public static final int DANAR_PACKET__OPCODE_ETC__SET_HISTORY_SAVE = 0xE0;
public static final int DANAR_PACKET__OPCODE_ETC__KEEP_CONNECTION = 0xFF;
static {
System.loadLibrary("BleCommandUtil");
}
private static native byte[] getEncryptedPacketJni(Object context, int opcode, byte[] bytes, String deviceName);
private static native byte[] getDecryptedPacketJni(Object context, byte[] bytes);
// ---------------------------------------------------------
private static BleCommandUtil mInstance = null;
public static BleCommandUtil getInstance() {
if (mInstance == null) {
mInstance = new BleCommandUtil();
}
return mInstance;
}
// ---------------------------------------------------------
public byte[] getEncryptedPacket(int opcode, byte[] bytes, String deviceName) {
return getEncryptedPacketJni(MainApp.instance().getApplicationContext(), opcode, bytes, deviceName);
}
public byte[] getDecryptedPacket(byte[] bytes) {
return getDecryptedPacketJni(MainApp.instance().getApplicationContext(), bytes);
}
}

View file

@ -0,0 +1,87 @@
package com.squareup.otto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import info.nightscout.androidaps.events.Event;
/** Logs events has they're being posted to and dispatched from the event bus.
*
* A summary of event-receiver calls that occurred so far is logged
* after 10s (after startup) and then again every 60s.
* */
public class LoggingBus extends Bus {
private static Logger log = LoggerFactory.getLogger(LoggingBus.class);
private static long everyMinute = System.currentTimeMillis() + 10 * 1000;
private Map<String, Set<String>> event2Receiver = new HashMap<>();
public LoggingBus(ThreadEnforcer enforcer) {
super(enforcer);
}
@Override
public void post(Object event) {
if (event instanceof DeadEvent) {
log.debug("Event has no receiver: " + ((DeadEvent) event).event + ", source: " + ((DeadEvent) event).source);
return;
}
if (!(event instanceof Event)) {
log.error("Posted event not an event class: " + event.getClass());
}
log.debug("<<< " + event);
try {
StackTraceElement caller = new Throwable().getStackTrace()[1];
String className = caller.getClassName();
className = className.substring(className.lastIndexOf(".") + 1);
log.debug(" source: " + className + "." + caller.getMethodName() + ":" + caller.getLineNumber());
} catch (RuntimeException e) {
log.debug(" source: <unknown>");
}
super.post(event);
}
@Override
protected void dispatch(Object event, EventHandler wrapper) {
try {
log.debug(">>> " + event);
Field methodField = wrapper.getClass().getDeclaredField("method");
methodField.setAccessible(true);
Method targetMethod = (Method) methodField.get(wrapper);
String className = targetMethod.getDeclaringClass().getSimpleName();
String methodName = targetMethod.getName();
String receiverMethod = className + "." + methodName;
log.debug(" receiver: " + receiverMethod);
String key = event.getClass().getSimpleName();
if (!event2Receiver.containsKey(key)) event2Receiver.put(key, new HashSet<String>());
event2Receiver.get(key).add(receiverMethod);
} catch (ReflectiveOperationException e) {
log.debug(" receiver: <unknown>");
}
if (everyMinute < System.currentTimeMillis()) {
log.debug("***************** Event -> receiver pairings seen so far ****************");
for (Map.Entry<String, Set<String>> stringSetEntry : event2Receiver.entrySet()) {
log.debug(" " + stringSetEntry.getKey());
for (String s : stringSetEntry.getValue()) {
log.debug(" -> " + s);
}
}
log.debug("*************************************************************************");
everyMinute = System.currentTimeMillis() + 60 * 1000;
}
super.dispatch(event, wrapper);
}
}

View file

@ -4,31 +4,26 @@ package info.nightscout.androidaps;
* Created by mike on 07.06.2016. * Created by mike on 07.06.2016.
*/ */
public class Config { public class Config {
public static int SUPPORTEDNSVERSION = 1000; // 0.10.00 public static int SUPPORTEDNSVERSION = 1002; // 0.10.00
// MAIN FUCTIONALITY // MAIN FUCTIONALITY
public static final boolean APS = BuildConfig.APS; public static final boolean APS = BuildConfig.APS;
// PLUGINS // PLUGINS
public static final boolean OPENAPSENABLED = APS;
public static final boolean LOOPENABLED = APS;
public static final boolean WEAR = BuildConfig.WEAR;
public static final boolean NSCLIENT = BuildConfig.NSCLIENTOLNY; public static final boolean NSCLIENT = BuildConfig.NSCLIENTOLNY;
public static final boolean G5UPLOADER = BuildConfig.G5UPLOADER;
public static final boolean DANAR = true && BuildConfig.PUMPDRIVERS; public static final boolean COMBO = true && BuildConfig.PUMPDRIVERS;
public static final boolean DANARv2 = true && BuildConfig.PUMPDRIVERS; public static final boolean DANAR = BuildConfig.PUMPDRIVERS;
public static final boolean ACTION = !BuildConfig.NSCLIENTOLNY; public static final boolean ACTION = !BuildConfig.NSCLIENTOLNY && !BuildConfig.G5UPLOADER;
public static final boolean VIRTUALPUMP = !BuildConfig.NSCLIENTOLNY; public static final boolean VIRTUALPUMP = !BuildConfig.NSCLIENTOLNY && !BuildConfig.G5UPLOADER;
public static final boolean MDI = !BuildConfig.NSCLIENTOLNY; public static final boolean MDI = !BuildConfig.NSCLIENTOLNY && !BuildConfig.G5UPLOADER;
public static final boolean OTHERPROFILES = !BuildConfig.NSCLIENTOLNY; public static final boolean OTHERPROFILES = !BuildConfig.NSCLIENTOLNY && !BuildConfig.G5UPLOADER;
public static final boolean SAFETY = !BuildConfig.NSCLIENTOLNY; public static final boolean SAFETY = !BuildConfig.NSCLIENTOLNY && !BuildConfig.G5UPLOADER;
public static final boolean SMSCOMMUNICATORENABLED = !BuildConfig.NSCLIENTOLNY; public static final boolean SMSCOMMUNICATORENABLED = !BuildConfig.NSCLIENTOLNY && !BuildConfig.G5UPLOADER;
public static final boolean ALLPREFERENCES = !BuildConfig.NSCLIENTOLNY;
public static final boolean detailedLog = true; public static final boolean detailedLog = true;
public static final boolean logFunctionCalls = true; public static final boolean logFunctionCalls = true;
public static final boolean logIncommingData = true; public static final boolean logIncommingData = true;
@ -40,10 +35,11 @@ public class Config {
public static final boolean logNSUpload = true; public static final boolean logNSUpload = true;
public static final boolean logPumpActions = true; public static final boolean logPumpActions = true;
public static final boolean logCongigBuilderActions = true; public static final boolean logCongigBuilderActions = true;
public static final boolean logAutosensData = true; public static final boolean logAutosensData = false;
public static final boolean logEvents = false;
// DanaR specific // DanaR specific
public static final boolean logDanaBTComm = true; public static final boolean logDanaBTComm = true;
public static final boolean logDanaMessageDetail = true; public static boolean logDanaMessageDetail = true;
public static final boolean logDanaSerialEngine = true; public static final boolean logDanaSerialEngine = true;
} }

View file

@ -1,7 +1,5 @@
package info.nightscout.androidaps; package info.nightscout.androidaps;
import com.j256.ormlite.stmt.query.In;
/** /**
* Created by mike on 07.06.2016. * Created by mike on 07.06.2016.
*/ */
@ -32,6 +30,8 @@ public class Constants {
// Circadian Percentage Profile // Circadian Percentage Profile
public static final int CPP_MIN_PERCENTAGE = 50; public static final int CPP_MIN_PERCENTAGE = 50;
public static final int CPP_MAX_PERCENTAGE = 200; public static final int CPP_MAX_PERCENTAGE = 200;
public static final int CPP_MIN_TIMESHIFT = -6;
public static final int CPP_MAX_TIMESHIFT = 23;
// Very Hard Limits Ranges // Very Hard Limits Ranges
// First value is the Lowest and second value is the Highest a Limit can define // First value is the Lowest and second value is the Highest a Limit can define
@ -52,8 +52,12 @@ public class Constants {
//Screen: Threshold for width/height to go into small width/height layout //Screen: Threshold for width/height to go into small width/height layout
public static final int SMALL_WIDTH = 320; public static final int SMALL_WIDTH = 320;
public static final int SMALL_HEIGHT = 320; public static final int SMALL_HEIGHT = 480;
//Autosens //Autosens
public static final double DEVIATION_TO_BE_EQUAL = 2.0; public static final double DEVIATION_TO_BE_EQUAL = 2.0;
// Pump
public static final int PUMP_MAX_CONNECTION_TIME_IN_SECONDS = 120 - 1;
public static final int MIN_WATCHDOG_INTERVAL_IN_SECONDS = 12 * 60;
} }

View file

@ -58,8 +58,10 @@ public class MainActivity extends AppCompatActivity implements View.OnClickListe
static final int CASE_STORAGE = 0x1; static final int CASE_STORAGE = 0x1;
static final int CASE_SMS = 0x2; static final int CASE_SMS = 0x2;
static final int CASE_LOCATION = 0x3;
private boolean askForSMS = false; private boolean askForSMS = false;
private boolean askForLocation = true;
ImageButton menuButton; ImageButton menuButton;
@ -95,9 +97,10 @@ public class MainActivity extends AppCompatActivity implements View.OnClickListe
final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
if (ev.lock) { if (ev.lock) {
mWakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "AAPS"); mWakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "AAPS");
mWakeLock.acquire(); if (!mWakeLock.isHeld())
mWakeLock.acquire();
} else { } else {
if (mWakeLock != null) if (mWakeLock != null && mWakeLock.isHeld())
mWakeLock.release(); mWakeLock.release();
} }
} }
@ -113,7 +116,7 @@ public class MainActivity extends AppCompatActivity implements View.OnClickListe
try { // activity may be destroyed try { // activity may be destroyed
setUpTabs(true); setUpTabs(true);
} catch (IllegalStateException e) { } catch (IllegalStateException e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
boolean lockScreen = BuildConfig.NSCLIENTOLNY && SP.getBoolean("lockscreen", false); boolean lockScreen = BuildConfig.NSCLIENTOLNY && SP.getBoolean("lockscreen", false);
if (lockScreen) if (lockScreen)
@ -201,12 +204,14 @@ public class MainActivity extends AppCompatActivity implements View.OnClickListe
protected void onResume() { protected void onResume() {
super.onResume(); super.onResume();
askForSMSPermissions(); askForSMSPermissions();
askForLocationPermissions();
} }
@Override @Override
public void onDestroy() { public void onDestroy() {
if (mWakeLock != null) if (mWakeLock != null)
mWakeLock.release(); if (mWakeLock.isHeld())
mWakeLock.release();
super.onDestroy(); super.onDestroy();
} }
@ -254,6 +259,17 @@ public class MainActivity extends AppCompatActivity implements View.OnClickListe
} }
} }
private synchronized void askForLocationPermissions() {
if (askForLocation) { //only when settings were changed an MainActivity resumes.
askForLocation = false;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
askForPermission(new String[]{Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION}, CASE_LOCATION);
}
}
}
private void askForPermission(String[] permission, Integer requestCode) { private void askForPermission(String[] permission, Integer requestCode) {
boolean test = false; boolean test = false;
for (int i = 0; i < permission.length; i++) { for (int i = 0; i < permission.length; i++) {
@ -277,6 +293,7 @@ public class MainActivity extends AppCompatActivity implements View.OnClickListe
alert.setPositiveButton(R.string.ok, null); alert.setPositiveButton(R.string.ok, null);
alert.show(); alert.show();
break; break;
case CASE_LOCATION:
case CASE_SMS: case CASE_SMS:
break; break;
} }
@ -319,6 +336,7 @@ public class MainActivity extends AppCompatActivity implements View.OnClickListe
@Override @Override
public void run() { public void run() {
Intent i = new Intent(v.getContext(), PreferencesActivity.class); Intent i = new Intent(v.getContext(), PreferencesActivity.class);
i.putExtra("id", -1);
startActivity(i); startActivity(i);
} }
}, null); }, null);
@ -351,7 +369,7 @@ public class MainActivity extends AppCompatActivity implements View.OnClickListe
case R.id.nav_about: case R.id.nav_about:
AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext()); AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
builder.setTitle(getString(R.string.app_name) + " " + BuildConfig.VERSION); builder.setTitle(getString(R.string.app_name) + " " + BuildConfig.VERSION);
if (Config.NSCLIENT) if (Config.NSCLIENT|| Config.G5UPLOADER)
builder.setIcon(R.mipmap.yellowowl); builder.setIcon(R.mipmap.yellowowl);
else else
builder.setIcon(R.mipmap.blueowl); builder.setIcon(R.mipmap.blueowl);

View file

@ -1,9 +1,9 @@
package info.nightscout.androidaps; package info.nightscout.androidaps;
import android.app.Application; import android.app.Application;
import android.content.Intent;
import android.content.IntentFilter; import android.content.IntentFilter;
import android.content.res.Resources; import android.content.res.Resources;
import android.os.SystemClock;
import android.support.annotation.Nullable; import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager; import android.support.v4.content.LocalBroadcastManager;
@ -12,6 +12,7 @@ import com.crashlytics.android.answers.Answers;
import com.crashlytics.android.answers.CustomEvent; import com.crashlytics.android.answers.CustomEvent;
import com.j256.ormlite.android.apptools.OpenHelperManager; import com.j256.ormlite.android.apptools.OpenHelperManager;
import com.squareup.otto.Bus; import com.squareup.otto.Bus;
import com.squareup.otto.LoggingBus;
import com.squareup.otto.ThreadEnforcer; import com.squareup.otto.ThreadEnforcer;
import org.slf4j.Logger; import org.slf4j.Logger;
@ -23,48 +24,48 @@ import info.nightscout.androidaps.Services.Intents;
import info.nightscout.androidaps.db.DatabaseHelper; import info.nightscout.androidaps.db.DatabaseHelper;
import info.nightscout.androidaps.interfaces.InsulinInterface; import info.nightscout.androidaps.interfaces.InsulinInterface;
import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.plugins.Actions.ActionsFragment; import info.nightscout.androidaps.plugins.Actions.ActionsFragment;
import info.nightscout.androidaps.plugins.Careportal.CareportalFragment; import info.nightscout.androidaps.plugins.Careportal.CareportalPlugin;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderFragment; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderFragment;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.ConstraintsObjectives.ObjectivesFragment; import info.nightscout.androidaps.plugins.ConstraintsObjectives.ObjectivesPlugin;
import info.nightscout.androidaps.plugins.ConstraintsSafety.SafetyPlugin; import info.nightscout.androidaps.plugins.ConstraintsSafety.SafetyPlugin;
import info.nightscout.androidaps.plugins.InsulinFastacting.InsulinFastactingFragment; import info.nightscout.androidaps.plugins.Food.FoodPlugin;
import info.nightscout.androidaps.plugins.InsulinFastactingProlonged.InsulinFastactingProlongedFragment; import info.nightscout.androidaps.plugins.Insulin.InsulinFastactingPlugin;
import info.nightscout.androidaps.plugins.InsulinOrefCurves.InsulinOrefFreePeakFragment; import info.nightscout.androidaps.plugins.Insulin.InsulinFastactingProlongedPlugin;
import info.nightscout.androidaps.plugins.InsulinOrefCurves.InsulinOrefRapidActingFragment; import info.nightscout.androidaps.plugins.Insulin.InsulinOrefFreePeakPlugin;
import info.nightscout.androidaps.plugins.InsulinOrefCurves.InsulinOrefUltraRapidActingFragment; import info.nightscout.androidaps.plugins.Insulin.InsulinOrefRapidActingPlugin;
import info.nightscout.androidaps.plugins.Insulin.InsulinOrefUltraRapidActingPlugin;
import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin; import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin;
import info.nightscout.androidaps.plugins.Loop.LoopFragment; import info.nightscout.androidaps.plugins.Loop.LoopPlugin;
import info.nightscout.androidaps.plugins.NSClientInternal.NSClientInternalFragment; import info.nightscout.androidaps.plugins.NSClientInternal.NSClientInternalPlugin;
import info.nightscout.androidaps.plugins.NSClientInternal.receivers.AckAlarmReceiver; import info.nightscout.androidaps.plugins.NSClientInternal.receivers.AckAlarmReceiver;
import info.nightscout.androidaps.plugins.OpenAPSAMA.OpenAPSAMAFragment; import info.nightscout.androidaps.plugins.OpenAPSAMA.OpenAPSAMAPlugin;
import info.nightscout.androidaps.plugins.OpenAPSMA.OpenAPSMAFragment; import info.nightscout.androidaps.plugins.OpenAPSMA.OpenAPSMAPlugin;
import info.nightscout.androidaps.plugins.Overview.OverviewFragment; import info.nightscout.androidaps.plugins.Overview.OverviewPlugin;
import info.nightscout.androidaps.plugins.Persistentnotification.PersistentNotificationPlugin; import info.nightscout.androidaps.plugins.Persistentnotification.PersistentNotificationPlugin;
import info.nightscout.androidaps.plugins.ProfileCircadianPercentage.CircadianPercentageProfileFragment; import info.nightscout.androidaps.plugins.ProfileCircadianPercentage.CircadianPercentageProfileFragment;
import info.nightscout.androidaps.plugins.ProfileLocal.LocalProfileFragment; import info.nightscout.androidaps.plugins.ProfileLocal.LocalProfileFragment;
import info.nightscout.androidaps.plugins.ProfileNS.NSProfileFragment; import info.nightscout.androidaps.plugins.ProfileNS.NSProfilePlugin;
import info.nightscout.androidaps.plugins.ProfileSimple.SimpleProfileFragment; import info.nightscout.androidaps.plugins.ProfileSimple.SimpleProfilePlugin;
import info.nightscout.androidaps.plugins.PumpDanaR.DanaRFragment; import info.nightscout.androidaps.plugins.PumpCombo.ComboPlugin;
import info.nightscout.androidaps.plugins.PumpDanaR.services.DanaRExecutionService; import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPlugin;
import info.nightscout.androidaps.plugins.PumpDanaRKorean.DanaRKoreanFragment; import info.nightscout.androidaps.plugins.PumpDanaRKorean.DanaRKoreanPlugin;
import info.nightscout.androidaps.plugins.PumpDanaRKorean.services.DanaRKoreanExecutionService; import info.nightscout.androidaps.plugins.PumpDanaRS.DanaRSPlugin;
import info.nightscout.androidaps.plugins.PumpDanaRv2.DanaRv2Fragment; import info.nightscout.androidaps.plugins.PumpDanaRv2.DanaRv2Plugin;
import info.nightscout.androidaps.plugins.PumpDanaRv2.services.DanaRv2ExecutionService;
import info.nightscout.androidaps.plugins.PumpMDI.MDIPlugin; import info.nightscout.androidaps.plugins.PumpMDI.MDIPlugin;
import info.nightscout.androidaps.plugins.PumpVirtual.VirtualPumpPlugin; import info.nightscout.androidaps.plugins.PumpVirtual.VirtualPumpPlugin;
import info.nightscout.androidaps.plugins.SensitivityAAPS.SensitivityAAPSPlugin; import info.nightscout.androidaps.plugins.SensitivityAAPS.SensitivityAAPSPlugin;
import info.nightscout.androidaps.plugins.SensitivityOref0.SensitivityOref0Plugin; import info.nightscout.androidaps.plugins.SensitivityOref0.SensitivityOref0Plugin;
import info.nightscout.androidaps.plugins.SensitivityWeightedAverage.SensitivityWeightedAveragePlugin; import info.nightscout.androidaps.plugins.SensitivityWeightedAverage.SensitivityWeightedAveragePlugin;
import info.nightscout.androidaps.plugins.SmsCommunicator.SmsCommunicatorFragment; import info.nightscout.androidaps.plugins.SmsCommunicator.SmsCommunicatorPlugin;
import info.nightscout.androidaps.plugins.SourceDexcomG5.SourceDexcomG5Plugin;
import info.nightscout.androidaps.plugins.SourceGlimp.SourceGlimpPlugin; import info.nightscout.androidaps.plugins.SourceGlimp.SourceGlimpPlugin;
import info.nightscout.androidaps.plugins.SourceMM640g.SourceMM640gPlugin; import info.nightscout.androidaps.plugins.SourceMM640g.SourceMM640gPlugin;
import info.nightscout.androidaps.plugins.SourceNSClient.SourceNSClientPlugin; import info.nightscout.androidaps.plugins.SourceNSClient.SourceNSClientPlugin;
import info.nightscout.androidaps.plugins.SourceXdrip.SourceXdripPlugin; import info.nightscout.androidaps.plugins.SourceXdrip.SourceXdripPlugin;
import info.nightscout.androidaps.plugins.Treatments.TreatmentsFragment; import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin;
import info.nightscout.androidaps.plugins.Wear.WearFragment; import info.nightscout.androidaps.plugins.Wear.WearPlugin;
import info.nightscout.androidaps.plugins.XDripStatusline.StatuslinePlugin; import info.nightscout.androidaps.plugins.XDripStatusline.StatuslinePlugin;
import info.nightscout.androidaps.receivers.DataReceiver; import info.nightscout.androidaps.receivers.DataReceiver;
import info.nightscout.androidaps.receivers.KeepAliveReceiver; import info.nightscout.androidaps.receivers.KeepAliveReceiver;
@ -100,7 +101,8 @@ public class MainApp extends Application {
log.info("Version: " + BuildConfig.VERSION_NAME); log.info("Version: " + BuildConfig.VERSION_NAME);
log.info("BuildVersion: " + BuildConfig.BUILDVERSION); log.info("BuildVersion: " + BuildConfig.BUILDVERSION);
sBus = new Bus(ThreadEnforcer.ANY); sBus = Config.logEvents ? new LoggingBus(ThreadEnforcer.ANY) : new Bus(ThreadEnforcer.ANY);
sInstance = this; sInstance = this;
sResources = getResources(); sResources = getResources();
@ -109,47 +111,53 @@ public class MainApp extends Application {
if (pluginsList == null) { if (pluginsList == null) {
pluginsList = new ArrayList<>(); pluginsList = new ArrayList<>();
// Register all tabs in app here // Register all tabs in app here
pluginsList.add(OverviewFragment.getPlugin()); pluginsList.add(OverviewPlugin.getPlugin());
pluginsList.add(IobCobCalculatorPlugin.getPlugin()); pluginsList.add(IobCobCalculatorPlugin.getPlugin());
if (Config.ACTION) pluginsList.add(ActionsFragment.getPlugin()); if (Config.ACTION) pluginsList.add(ActionsFragment.getPlugin());
pluginsList.add(InsulinFastactingFragment.getPlugin()); pluginsList.add(InsulinFastactingPlugin.getPlugin());
pluginsList.add(InsulinFastactingProlongedFragment.getPlugin()); pluginsList.add(InsulinFastactingProlongedPlugin.getPlugin());
pluginsList.add(InsulinOrefRapidActingFragment.getPlugin()); pluginsList.add(InsulinOrefRapidActingPlugin.getPlugin());
pluginsList.add(InsulinOrefUltraRapidActingFragment.getPlugin()); pluginsList.add(InsulinOrefUltraRapidActingPlugin.getPlugin());
pluginsList.add(InsulinOrefFreePeakFragment.getPlugin()); pluginsList.add(InsulinOrefFreePeakPlugin.getPlugin());
pluginsList.add(SensitivityOref0Plugin.getPlugin()); pluginsList.add(SensitivityOref0Plugin.getPlugin());
//pluginsList.add(SensitivityAAPSPlugin.getPlugin()); pluginsList.add(SensitivityAAPSPlugin.getPlugin());
//pluginsList.add(SensitivityWeightedAveragePlugin.getPlugin()); pluginsList.add(SensitivityWeightedAveragePlugin.getPlugin());
if (Config.DANAR) pluginsList.add(DanaRFragment.getPlugin()); if (Config.DANAR) pluginsList.add(DanaRPlugin.getPlugin());
if (Config.DANAR) pluginsList.add(DanaRKoreanFragment.getPlugin()); if (Config.DANAR) pluginsList.add(DanaRKoreanPlugin.getPlugin());
if (Config.DANARv2) pluginsList.add(DanaRv2Fragment.getPlugin()); if (Config.DANAR) pluginsList.add(DanaRv2Plugin.getPlugin());
pluginsList.add(CareportalFragment.getPlugin()); if (Config.DANAR) pluginsList.add(DanaRSPlugin.getPlugin());
if (Config.COMBO) pluginsList.add(ComboPlugin.getPlugin());
pluginsList.add(CareportalPlugin.getPlugin());
if (Config.MDI) pluginsList.add(MDIPlugin.getPlugin()); if (Config.MDI) pluginsList.add(MDIPlugin.getPlugin());
if (Config.VIRTUALPUMP) pluginsList.add(VirtualPumpPlugin.getInstance()); if (Config.VIRTUALPUMP) pluginsList.add(VirtualPumpPlugin.getPlugin());
if (Config.LOOPENABLED) pluginsList.add(LoopFragment.getPlugin()); if (Config.APS) pluginsList.add(LoopPlugin.getPlugin());
if (Config.OPENAPSENABLED) pluginsList.add(OpenAPSMAFragment.getPlugin()); if (Config.APS) pluginsList.add(OpenAPSMAPlugin.getPlugin());
if (Config.OPENAPSENABLED) pluginsList.add(OpenAPSAMAFragment.getPlugin()); if (Config.APS) pluginsList.add(OpenAPSAMAPlugin.getPlugin());
pluginsList.add(NSProfileFragment.getPlugin()); pluginsList.add(NSProfilePlugin.getPlugin());
if (Config.OTHERPROFILES) pluginsList.add(SimpleProfileFragment.getPlugin()); if (Config.OTHERPROFILES) pluginsList.add(SimpleProfilePlugin.getPlugin());
if (Config.OTHERPROFILES) pluginsList.add(LocalProfileFragment.getPlugin()); if (Config.OTHERPROFILES) pluginsList.add(LocalProfileFragment.getPlugin());
if (Config.OTHERPROFILES) if (Config.OTHERPROFILES)
pluginsList.add(CircadianPercentageProfileFragment.getPlugin()); pluginsList.add(CircadianPercentageProfileFragment.getPlugin());
pluginsList.add(TreatmentsFragment.getPlugin()); pluginsList.add(TreatmentsPlugin.getPlugin());
if (Config.SAFETY) pluginsList.add(SafetyPlugin.getPlugin()); if (Config.SAFETY) pluginsList.add(SafetyPlugin.getPlugin());
if (Config.APS) pluginsList.add(ObjectivesFragment.getPlugin()); if (Config.APS) pluginsList.add(ObjectivesPlugin.getPlugin());
if (!Config.NSCLIENT) if (!Config.NSCLIENT && !Config.G5UPLOADER)
pluginsList.add(SourceXdripPlugin.getPlugin()); pluginsList.add(SourceXdripPlugin.getPlugin());
pluginsList.add(SourceNSClientPlugin.getPlugin()); if (!Config.G5UPLOADER)
if (!Config.NSCLIENT) pluginsList.add(SourceNSClientPlugin.getPlugin());
if (!Config.NSCLIENT && !Config.G5UPLOADER)
pluginsList.add(SourceMM640gPlugin.getPlugin()); pluginsList.add(SourceMM640gPlugin.getPlugin());
if (!Config.NSCLIENT) if (!Config.NSCLIENT && !Config.G5UPLOADER)
pluginsList.add(SourceGlimpPlugin.getPlugin()); pluginsList.add(SourceGlimpPlugin.getPlugin());
if (Config.SMSCOMMUNICATORENABLED) pluginsList.add(SmsCommunicatorFragment.getPlugin()); if (!Config.NSCLIENT)
pluginsList.add(SourceDexcomG5Plugin.getPlugin());
if (Config.SMSCOMMUNICATORENABLED) pluginsList.add(SmsCommunicatorPlugin.getPlugin());
pluginsList.add(FoodPlugin.getPlugin());
if (Config.WEAR) pluginsList.add(WearFragment.getPlugin(this)); pluginsList.add(WearPlugin.initPlugin(this));
pluginsList.add(StatuslinePlugin.getPlugin(this)); pluginsList.add(StatuslinePlugin.initPlugin(this));
pluginsList.add(new PersistentNotificationPlugin(this)); pluginsList.add(new PersistentNotificationPlugin(this));
pluginsList.add(NSClientInternalFragment.getPlugin()); pluginsList.add(NSClientInternalPlugin.getPlugin());
pluginsList.add(sConfigBuilder = ConfigBuilderFragment.getPlugin()); pluginsList.add(sConfigBuilder = ConfigBuilderFragment.getPlugin());
@ -161,22 +169,14 @@ public class MainApp extends Application {
else else
Answers.getInstance().logCustom(new CustomEvent("AppStart")); Answers.getInstance().logCustom(new CustomEvent("AppStart"));
new Thread(new Runnable() {
startKeepAliveService();
Thread t = new Thread(new Runnable() {
@Override @Override
public void run() { public void run() {
try { SystemClock.sleep(5000);
Thread.sleep(5000); ConfigBuilderPlugin.getCommandQueue().readStatus("Initialization", null);
} catch (InterruptedException e) { startKeepAliveService();
}
PumpInterface pump = MainApp.getConfigBuilder();
if (pump != null)
pump.refreshDataFromPump("Initialization");
} }
}); }).start();
t.start();
} }
@ -185,6 +185,9 @@ public class MainApp extends Application {
lbm.registerReceiver(dataReceiver, new IntentFilter(Intents.ACTION_NEW_TREATMENT)); lbm.registerReceiver(dataReceiver, new IntentFilter(Intents.ACTION_NEW_TREATMENT));
lbm.registerReceiver(dataReceiver, new IntentFilter(Intents.ACTION_CHANGED_TREATMENT)); lbm.registerReceiver(dataReceiver, new IntentFilter(Intents.ACTION_CHANGED_TREATMENT));
lbm.registerReceiver(dataReceiver, new IntentFilter(Intents.ACTION_REMOVED_TREATMENT)); lbm.registerReceiver(dataReceiver, new IntentFilter(Intents.ACTION_REMOVED_TREATMENT));
lbm.registerReceiver(dataReceiver, new IntentFilter(Intents.ACTION_NEW_FOOD));
lbm.registerReceiver(dataReceiver, new IntentFilter(Intents.ACTION_CHANGED_FOOD));
lbm.registerReceiver(dataReceiver, new IntentFilter(Intents.ACTION_REMOVED_FOOD));
lbm.registerReceiver(dataReceiver, new IntentFilter(Intents.ACTION_NEW_SGV)); lbm.registerReceiver(dataReceiver, new IntentFilter(Intents.ACTION_NEW_SGV));
lbm.registerReceiver(dataReceiver, new IntentFilter(Intents.ACTION_NEW_PROFILE)); lbm.registerReceiver(dataReceiver, new IntentFilter(Intents.ACTION_NEW_PROFILE));
lbm.registerReceiver(dataReceiver, new IntentFilter(Intents.ACTION_NEW_STATUS)); lbm.registerReceiver(dataReceiver, new IntentFilter(Intents.ACTION_NEW_STATUS));
@ -205,11 +208,6 @@ public class MainApp extends Application {
private void startKeepAliveService() { private void startKeepAliveService() {
if (keepAliveReceiver == null) { if (keepAliveReceiver == null) {
keepAliveReceiver = new KeepAliveReceiver(); keepAliveReceiver = new KeepAliveReceiver();
if (Config.DANAR) {
startService(new Intent(this, DanaRExecutionService.class));
startService(new Intent(this, DanaRKoreanExecutionService.class));
startService(new Intent(this, DanaRv2ExecutionService.class));
}
keepAliveReceiver.setAlarm(this); keepAliveReceiver.setAlarm(this);
} }
} }
@ -217,7 +215,7 @@ public class MainApp extends Application {
public void stopKeepAliveService() { public void stopKeepAliveService() {
if (keepAliveReceiver != null) if (keepAliveReceiver != null)
keepAliveReceiver.cancelAlarm(this); KeepAliveReceiver.cancelAlarm(this);
} }
public static Bus bus() { public static Bus bus() {

View file

@ -4,27 +4,34 @@ import android.content.SharedPreferences;
import android.os.Bundle; import android.os.Bundle;
import android.preference.EditTextPreference; import android.preference.EditTextPreference;
import android.preference.ListPreference; import android.preference.ListPreference;
import android.preference.MultiSelectListPreference;
import android.preference.Preference; import android.preference.Preference;
import android.preference.PreferenceActivity; import android.preference.PreferenceActivity;
import android.preference.PreferenceFragment; import android.preference.PreferenceFragment;
import android.preference.PreferenceGroup; import android.preference.PreferenceGroup;
import android.preference.PreferenceManager; import android.preference.PreferenceManager;
import android.text.TextUtils;
import info.nightscout.androidaps.events.EventPreferenceChange; import info.nightscout.androidaps.events.EventPreferenceChange;
import info.nightscout.androidaps.events.EventRefreshGui; import info.nightscout.androidaps.events.EventRefreshGui;
import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.plugins.InsulinOrefCurves.InsulinOrefFreePeakPlugin; import info.nightscout.androidaps.plugins.Careportal.CareportalPlugin;
import info.nightscout.androidaps.plugins.PumpDanaR.BluetoothDevicePreference; import info.nightscout.androidaps.plugins.ConstraintsSafety.SafetyPlugin;
import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPlugin; import info.nightscout.androidaps.plugins.Insulin.InsulinOrefFreePeakPlugin;
import info.nightscout.androidaps.plugins.PumpDanaRKorean.DanaRKoreanPlugin; import info.nightscout.androidaps.plugins.Loop.LoopPlugin;
import info.nightscout.androidaps.plugins.NSClientInternal.NSClientInternalPlugin; import info.nightscout.androidaps.plugins.NSClientInternal.NSClientInternalPlugin;
import info.nightscout.androidaps.plugins.OpenAPSAMA.OpenAPSAMAPlugin; import info.nightscout.androidaps.plugins.OpenAPSAMA.OpenAPSAMAPlugin;
import info.nightscout.androidaps.plugins.OpenAPSMA.OpenAPSMAPlugin;
import info.nightscout.androidaps.plugins.PumpCombo.ComboPlugin;
import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPlugin;
import info.nightscout.androidaps.plugins.PumpDanaRKorean.DanaRKoreanPlugin;
import info.nightscout.androidaps.plugins.PumpDanaRS.DanaRSPlugin;
import info.nightscout.androidaps.plugins.PumpDanaRv2.DanaRv2Plugin; import info.nightscout.androidaps.plugins.PumpDanaRv2.DanaRv2Plugin;
import info.nightscout.androidaps.plugins.PumpVirtual.VirtualPumpPlugin; import info.nightscout.androidaps.plugins.PumpVirtual.VirtualPumpPlugin;
import info.nightscout.androidaps.plugins.SensitivityAAPS.SensitivityAAPSPlugin; import info.nightscout.androidaps.plugins.SensitivityAAPS.SensitivityAAPSPlugin;
import info.nightscout.androidaps.plugins.SensitivityOref0.SensitivityOref0Plugin; import info.nightscout.androidaps.plugins.SensitivityOref0.SensitivityOref0Plugin;
import info.nightscout.androidaps.plugins.SensitivityWeightedAverage.SensitivityWeightedAveragePlugin; import info.nightscout.androidaps.plugins.SensitivityWeightedAverage.SensitivityWeightedAveragePlugin;
import info.nightscout.androidaps.plugins.SmsCommunicator.SmsCommunicatorPlugin;
import info.nightscout.androidaps.plugins.SourceDexcomG5.SourceDexcomG5Plugin;
import info.nightscout.androidaps.plugins.Wear.WearPlugin; import info.nightscout.androidaps.plugins.Wear.WearPlugin;
import info.nightscout.androidaps.plugins.XDripStatusline.StatuslinePlugin; import info.nightscout.androidaps.plugins.XDripStatusline.StatuslinePlugin;
import info.nightscout.utils.LocaleHelper; import info.nightscout.utils.LocaleHelper;
@ -38,6 +45,9 @@ public class PreferencesActivity extends PreferenceActivity implements SharedPre
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
myPreferenceFragment = new MyPreferenceFragment(); myPreferenceFragment = new MyPreferenceFragment();
Bundle args = new Bundle();
args.putInt("id", getIntent().getIntExtra("id", -1));
myPreferenceFragment.setArguments(args);
getFragmentManager().beginTransaction().replace(android.R.id.content, myPreferenceFragment).commit(); getFragmentManager().beginTransaction().replace(android.R.id.content, myPreferenceFragment).commit();
PreferenceManager.getDefaultSharedPreferences(this).registerOnSharedPreferenceChangeListener(this); PreferenceManager.getDefaultSharedPreferences(this).registerOnSharedPreferenceChangeListener(this);
} }
@ -61,7 +71,7 @@ public class PreferencesActivity extends PreferenceActivity implements SharedPre
} }
private static void updatePrefSummary(Preference pref) { private static void updatePrefSummary(Preference pref) {
if (pref instanceof ListPreference || pref instanceof BluetoothDevicePreference) { if (pref instanceof ListPreference) {
ListPreference listPref = (ListPreference) pref; ListPreference listPref = (ListPreference) pref;
pref.setSummary(listPref.getEntry()); pref.setSummary(listPref.getEntry());
} }
@ -69,15 +79,15 @@ public class PreferencesActivity extends PreferenceActivity implements SharedPre
EditTextPreference editTextPref = (EditTextPreference) pref; EditTextPreference editTextPref = (EditTextPreference) pref;
if (pref.getKey().contains("password") || pref.getKey().contains("secret")) { if (pref.getKey().contains("password") || pref.getKey().contains("secret")) {
pref.setSummary("******"); pref.setSummary("******");
} else if (pref.getKey().equals(MainApp.sResources.getString(R.string.key_danars_name))) {
pref.setSummary(SP.getString(R.string.key_danars_name, ""));
} else if (editTextPref.getText() != null && !editTextPref.getText().equals("")) { } else if (editTextPref.getText() != null && !editTextPref.getText().equals("")) {
((EditTextPreference) pref).setDialogMessage(editTextPref.getDialogMessage()); ((EditTextPreference) pref).setDialogMessage(editTextPref.getDialogMessage());
pref.setSummary(editTextPref.getText()); pref.setSummary(editTextPref.getText());
} else if (pref.getKey().contains("smscommunicator_allowednumbers") && TextUtils.isEmpty(editTextPref.getText().trim())) {
pref.setSummary(MainApp.sResources.getString(R.string.smscommunicator_allowednumbers_summary));
} }
} }
if (pref instanceof MultiSelectListPreference) {
EditTextPreference editTextPref = (EditTextPreference) pref;
pref.setSummary(editTextPref.getText());
}
} }
public static void initSummary(Preference p) { public static void initSummary(Preference p) {
@ -92,85 +102,100 @@ public class PreferencesActivity extends PreferenceActivity implements SharedPre
} }
public static class MyPreferenceFragment extends PreferenceFragment { public static class MyPreferenceFragment extends PreferenceFragment {
private Integer id;
@Override
public void setArguments(Bundle args) {
super.setArguments(args);
id = args.getInt("id");
}
void addPreferencesFromResourceIfEnabled(PluginBase p, int type) {
if (p.isEnabled(type) && p.getPreferencesId() != -1)
addPreferencesFromResource(p.getPreferencesId());
}
@Override @Override
public void onCreate(final Bundle savedInstanceState) { public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
if (Config.ALLPREFERENCES) {
addPreferencesFromResource(R.xml.pref_password); if (savedInstanceState != null && savedInstanceState.containsKey("id")) {
} id = savedInstanceState.getInt("id");
addPreferencesFromResource(R.xml.pref_age);
addPreferencesFromResource(R.xml.pref_language);
if (Config.ALLPREFERENCES) {
addPreferencesFromResource(R.xml.pref_quickwizard);
}
addPreferencesFromResource(R.xml.pref_careportal);
if (Config.ALLPREFERENCES) {
addPreferencesFromResource(R.xml.pref_treatments);
}
if (Config.APS)
addPreferencesFromResource(R.xml.pref_closedmode);
if (Config.OPENAPSENABLED) {
addPreferencesFromResource(R.xml.pref_openapsma);
if (MainApp.getSpecificPlugin(OpenAPSAMAPlugin.class) != null && MainApp.getSpecificPlugin(OpenAPSAMAPlugin.class).isEnabled(PluginBase.APS))
addPreferencesFromResource(R.xml.pref_openapsama);
}
if (MainApp.getSpecificPlugin(SensitivityAAPSPlugin.class) != null && MainApp.getSpecificPlugin(SensitivityAAPSPlugin.class).isEnabled(PluginBase.SENSITIVITY)
|| MainApp.getSpecificPlugin(SensitivityWeightedAveragePlugin.class) != null && MainApp.getSpecificPlugin(SensitivityWeightedAveragePlugin.class).isEnabled(PluginBase.SENSITIVITY))
addPreferencesFromResource(R.xml.pref_absorption_aaps);
if (MainApp.getSpecificPlugin(SensitivityOref0Plugin.class) != null && MainApp.getSpecificPlugin(SensitivityOref0Plugin.class).isEnabled(PluginBase.SENSITIVITY))
addPreferencesFromResource(R.xml.pref_absorption_oref0);
if (Config.ALLPREFERENCES) {
addPreferencesFromResource(R.xml.pref_profile);
}
if (Config.DANAR) {
DanaRPlugin danaRPlugin = MainApp.getSpecificPlugin(DanaRPlugin.class);
DanaRKoreanPlugin danaRKoreanPlugin = MainApp.getSpecificPlugin(DanaRKoreanPlugin.class);
DanaRv2Plugin danaRv2Plugin = MainApp.getSpecificPlugin(DanaRv2Plugin.class);
if (danaRPlugin.isEnabled(PluginBase.PUMP) || danaRKoreanPlugin.isEnabled(PluginBase.PUMP)) {
addPreferencesFromResource(R.xml.pref_danar);
}
if (danaRv2Plugin != null && danaRv2Plugin.isEnabled(PluginBase.PUMP)) {
addPreferencesFromResource(R.xml.pref_danarv2);
}
if (danaRPlugin.isEnabled(PluginBase.PROFILE) || danaRKoreanPlugin.isEnabled(PluginBase.PROFILE) || danaRv2Plugin != null && danaRv2Plugin.isEnabled(PluginBase.PROFILE)) {
addPreferencesFromResource(R.xml.pref_danarprofile);
}
}
VirtualPumpPlugin virtualPumpPlugin = MainApp.getSpecificPlugin(VirtualPumpPlugin.class);
if (virtualPumpPlugin != null && virtualPumpPlugin.isEnabled(PluginBase.PUMP)) {
addPreferencesFromResource(R.xml.pref_virtualpump);
}
InsulinOrefFreePeakPlugin insulinOrefFreePeakPlugin = MainApp.getSpecificPlugin(InsulinOrefFreePeakPlugin.class);
if(insulinOrefFreePeakPlugin.isEnabled(PluginBase.INSULIN)){
addPreferencesFromResource(R.xml.pref_insulinoreffreepeak);
} }
NSClientInternalPlugin nsClientInternalPlugin = MainApp.getSpecificPlugin(NSClientInternalPlugin.class); if (id != -1) {
if (nsClientInternalPlugin != null && nsClientInternalPlugin.isEnabled(PluginBase.GENERAL)) { addPreferencesFromResource(id);
addPreferencesFromResource(R.xml.pref_nsclientinternal); addPreferencesFromResource(R.xml.pref_advanced);
} } else {
if (Config.SMSCOMMUNICATORENABLED) if (!Config.NSCLIENT && !Config.G5UPLOADER) {
addPreferencesFromResource(R.xml.pref_smscommunicator); addPreferencesFromResource(R.xml.pref_password);
if (Config.ALLPREFERENCES) {
addPreferencesFromResource(R.xml.pref_others);
}
addPreferencesFromResource(R.xml.pref_advanced);
if (Config.WEAR) {
WearPlugin wearPlugin = MainApp.getSpecificPlugin(WearPlugin.class);
if (wearPlugin != null && wearPlugin.isEnabled(PluginBase.GENERAL)) {
addPreferencesFromResource(R.xml.pref_wear);
} }
} addPreferencesFromResource(R.xml.pref_age);
addPreferencesFromResource(R.xml.pref_language);
StatuslinePlugin statuslinePlugin = MainApp.getSpecificPlugin(StatuslinePlugin.class); if (!Config.NSCLIENT && !Config.G5UPLOADER) {
if (statuslinePlugin != null && statuslinePlugin.isEnabled(PluginBase.GENERAL)) { addPreferencesFromResource(R.xml.pref_quickwizard);
addPreferencesFromResource(R.xml.pref_xdripstatus); }
addPreferencesFromResourceIfEnabled(SourceDexcomG5Plugin.getPlugin(), PluginBase.BGSOURCE);
addPreferencesFromResourceIfEnabled(CareportalPlugin.getPlugin(), PluginBase.GENERAL);
addPreferencesFromResourceIfEnabled(SafetyPlugin.getPlugin(), PluginBase.CONSTRAINTS);
if (Config.APS) {
addPreferencesFromResourceIfEnabled(LoopPlugin.getPlugin(), PluginBase.LOOP);
addPreferencesFromResourceIfEnabled(OpenAPSMAPlugin.getPlugin(), PluginBase.APS);
addPreferencesFromResourceIfEnabled(OpenAPSAMAPlugin.getPlugin(), PluginBase.APS);
}
addPreferencesFromResourceIfEnabled(SensitivityAAPSPlugin.getPlugin(), PluginBase.SENSITIVITY);
addPreferencesFromResourceIfEnabled(SensitivityWeightedAveragePlugin.getPlugin(), PluginBase.SENSITIVITY);
addPreferencesFromResourceIfEnabled(SensitivityOref0Plugin.getPlugin(), PluginBase.SENSITIVITY);
if (Config.DANAR) {
addPreferencesFromResourceIfEnabled(DanaRPlugin.getPlugin(), PluginBase.PUMP);
addPreferencesFromResourceIfEnabled(DanaRKoreanPlugin.getPlugin(), PluginBase.PUMP);
addPreferencesFromResourceIfEnabled(DanaRv2Plugin.getPlugin(), PluginBase.PUMP);
addPreferencesFromResourceIfEnabled(DanaRSPlugin.getPlugin(), PluginBase.PUMP);
if (DanaRPlugin.getPlugin().isEnabled(PluginBase.PROFILE)
|| DanaRKoreanPlugin.getPlugin().isEnabled(PluginBase.PROFILE)
|| DanaRv2Plugin.getPlugin().isEnabled(PluginBase.PROFILE)
|| DanaRSPlugin.getPlugin().isEnabled(PluginBase.PROFILE)) {
addPreferencesFromResource(R.xml.pref_danarprofile);
}
}
if (!Config.NSCLIENT && !Config.G5UPLOADER) {
addPreferencesFromResourceIfEnabled(VirtualPumpPlugin.getPlugin(), PluginBase.PUMP);
}
/* No usable settings yet
if (Config.COMBO) {
addPreferencesFromResourceIfEnabled(ComboPlugin.getPlugin(), PluginBase.PUMP);
}
*/
addPreferencesFromResourceIfEnabled(InsulinOrefFreePeakPlugin.getPlugin(), PluginBase.INSULIN);
addPreferencesFromResourceIfEnabled(NSClientInternalPlugin.getPlugin(), PluginBase.GENERAL);
addPreferencesFromResourceIfEnabled(SmsCommunicatorPlugin.getPlugin(), PluginBase.GENERAL);
if (!Config.NSCLIENT && !Config.G5UPLOADER) {
addPreferencesFromResource(R.xml.pref_others);
}
addPreferencesFromResource(R.xml.pref_advanced);
addPreferencesFromResourceIfEnabled(WearPlugin.getPlugin(), PluginBase.GENERAL);
addPreferencesFromResourceIfEnabled(StatuslinePlugin.getPlugin(), PluginBase.GENERAL);
} }
initSummary(getPreferenceScreen()); initSummary(getPreferenceScreen());
} }
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("id", id);
}
public Preference getPreference(String key) { public Preference getPreference(String key) {
return findPreference(key); return findPreference(key);
} }

View file

@ -50,7 +50,7 @@ public class AlarmSoundService extends Service {
player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength()); player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
afd.close(); afd.close();
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
player.setLooping(true); // Set looping player.setLooping(true); // Set looping
player.setVolume(100, 100); player.setVolume(100, 100);
@ -59,7 +59,7 @@ public class AlarmSoundService extends Service {
player.prepare(); player.prepare();
player.start(); player.start();
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
return START_STICKY; return START_STICKY;

View file

@ -24,13 +24,14 @@ import info.nightscout.androidaps.plugins.NSClientInternal.data.NSMbg;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSSgv; import info.nightscout.androidaps.plugins.NSClientInternal.data.NSSgv;
import info.nightscout.androidaps.data.ProfileStore; import info.nightscout.androidaps.data.ProfileStore;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSSettingsStatus; import info.nightscout.androidaps.plugins.NSClientInternal.data.NSSettingsStatus;
import info.nightscout.androidaps.plugins.Overview.Notification; import info.nightscout.androidaps.plugins.Overview.notifications.Notification;
import info.nightscout.androidaps.plugins.Overview.OverviewPlugin; import info.nightscout.androidaps.plugins.Overview.OverviewPlugin;
import info.nightscout.androidaps.plugins.Overview.events.EventDismissNotification; import info.nightscout.androidaps.plugins.Overview.events.EventDismissNotification;
import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification; import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.ProfileNS.NSProfilePlugin; import info.nightscout.androidaps.plugins.ProfileNS.NSProfilePlugin;
import info.nightscout.androidaps.plugins.PumpDanaR.activities.DanaRNSHistorySync; import info.nightscout.androidaps.plugins.PumpDanaR.activities.DanaRNSHistorySync;
import info.nightscout.androidaps.plugins.SmsCommunicator.events.EventNewSMS; import info.nightscout.androidaps.plugins.SmsCommunicator.events.EventNewSMS;
import info.nightscout.androidaps.plugins.SourceDexcomG5.SourceDexcomG5Plugin;
import info.nightscout.androidaps.plugins.SourceGlimp.SourceGlimpPlugin; import info.nightscout.androidaps.plugins.SourceGlimp.SourceGlimpPlugin;
import info.nightscout.androidaps.plugins.SourceMM640g.SourceMM640gPlugin; import info.nightscout.androidaps.plugins.SourceMM640g.SourceMM640gPlugin;
import info.nightscout.androidaps.plugins.SourceNSClient.SourceNSClientPlugin; import info.nightscout.androidaps.plugins.SourceNSClient.SourceNSClientPlugin;
@ -38,6 +39,7 @@ import info.nightscout.androidaps.plugins.SourceXdrip.SourceXdripPlugin;
import info.nightscout.androidaps.receivers.DataReceiver; import info.nightscout.androidaps.receivers.DataReceiver;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSDeviceStatus; import info.nightscout.androidaps.plugins.NSClientInternal.data.NSDeviceStatus;
import info.nightscout.utils.BundleLogger; import info.nightscout.utils.BundleLogger;
import info.nightscout.utils.NSUpload;
import info.nightscout.utils.SP; import info.nightscout.utils.SP;
@ -48,6 +50,7 @@ public class DataService extends IntentService {
boolean nsClientEnabled = true; boolean nsClientEnabled = true;
boolean mm640gEnabled = false; boolean mm640gEnabled = false;
boolean glimpEnabled = false; boolean glimpEnabled = false;
boolean dexcomG5Enabled = false;
public DataService() { public DataService() {
super("DataService"); super("DataService");
@ -64,21 +67,31 @@ public class DataService extends IntentService {
nsClientEnabled = false; nsClientEnabled = false;
mm640gEnabled = false; mm640gEnabled = false;
glimpEnabled = false; glimpEnabled = false;
dexcomG5Enabled = false;
} else if (ConfigBuilderPlugin.getActiveBgSource().getClass().equals(SourceNSClientPlugin.class)) { } else if (ConfigBuilderPlugin.getActiveBgSource().getClass().equals(SourceNSClientPlugin.class)) {
xDripEnabled = false; xDripEnabled = false;
nsClientEnabled = true; nsClientEnabled = true;
mm640gEnabled = false; mm640gEnabled = false;
glimpEnabled = false; glimpEnabled = false;
dexcomG5Enabled = false;
} else if (ConfigBuilderPlugin.getActiveBgSource().getClass().equals(SourceMM640gPlugin.class)) { } else if (ConfigBuilderPlugin.getActiveBgSource().getClass().equals(SourceMM640gPlugin.class)) {
xDripEnabled = false; xDripEnabled = false;
nsClientEnabled = false; nsClientEnabled = false;
mm640gEnabled = true; mm640gEnabled = true;
glimpEnabled = false; glimpEnabled = false;
dexcomG5Enabled = false;
} else if (ConfigBuilderPlugin.getActiveBgSource().getClass().equals(SourceGlimpPlugin.class)) { } else if (ConfigBuilderPlugin.getActiveBgSource().getClass().equals(SourceGlimpPlugin.class)) {
xDripEnabled = false; xDripEnabled = false;
nsClientEnabled = false; nsClientEnabled = false;
mm640gEnabled = false; mm640gEnabled = false;
glimpEnabled = true; glimpEnabled = true;
dexcomG5Enabled = false;
} else if (ConfigBuilderPlugin.getActiveBgSource().getClass().equals(SourceDexcomG5Plugin.class)) {
xDripEnabled = false;
nsClientEnabled = false;
mm640gEnabled = false;
glimpEnabled = false;
dexcomG5Enabled = true;
} }
boolean isNSProfile = ConfigBuilderPlugin.getActiveProfileInterface().getClass().equals(NSProfilePlugin.class); boolean isNSProfile = ConfigBuilderPlugin.getActiveProfileInterface().getClass().equals(NSProfilePlugin.class);
@ -99,6 +112,10 @@ public class DataService extends IntentService {
if (glimpEnabled) { if (glimpEnabled) {
handleNewDataFromGlimp(intent); handleNewDataFromGlimp(intent);
} }
} else if (Intents.DEXCOMG5_BG.equals(action)) {
if (dexcomG5Enabled) {
handleNewDataFromDexcomG5(intent);
}
} else if (Intents.ACTION_NEW_SGV.equals(action)) { } else if (Intents.ACTION_NEW_SGV.equals(action)) {
// always handle SGV if NS-Client is the source // always handle SGV if NS-Client is the source
if (nsClientEnabled) { if (nsClientEnabled) {
@ -116,6 +133,9 @@ public class DataService extends IntentService {
Intents.ACTION_REMOVED_TREATMENT.equals(action) || Intents.ACTION_REMOVED_TREATMENT.equals(action) ||
Intents.ACTION_NEW_STATUS.equals(action) || Intents.ACTION_NEW_STATUS.equals(action) ||
Intents.ACTION_NEW_DEVICESTATUS.equals(action) || Intents.ACTION_NEW_DEVICESTATUS.equals(action) ||
Intents.ACTION_NEW_FOOD.equals(action) ||
Intents.ACTION_CHANGED_FOOD.equals(action) ||
Intents.ACTION_REMOVED_FOOD.equals(action) ||
Intents.ACTION_NEW_CAL.equals(action) || Intents.ACTION_NEW_CAL.equals(action) ||
Intents.ACTION_NEW_MBG.equals(action)) Intents.ACTION_NEW_MBG.equals(action))
) { ) {
@ -184,6 +204,37 @@ public class DataService extends IntentService {
MainApp.getDbHelper().createIfNotExists(bgReading, "GLIMP"); MainApp.getDbHelper().createIfNotExists(bgReading, "GLIMP");
} }
private void handleNewDataFromDexcomG5(Intent intent) {
// onHandleIntent Bundle{ data => [{"m_time":1511939180,"m_trend":"NotComputable","m_value":335}]; android.support.content.wakelockid => 95; }Bundle
Bundle bundle = intent.getExtras();
if (bundle == null) return;
BgReading bgReading = new BgReading();
String data = bundle.getString("data");
log.debug("Received Dexcom Data", data);
try {
JSONArray jsonArray = new JSONArray(data);
log.debug("Received Dexcom Data size:" + jsonArray.length());
for(int i = 0; i < jsonArray.length(); i++) {
JSONObject json = jsonArray.getJSONObject(i);
bgReading.value = json.getInt("m_value");
bgReading.direction = json.getString("m_trend");
bgReading.date = json.getLong("m_time") * 1000L;
bgReading.raw = 0;
boolean isNew = MainApp.getDbHelper().createIfNotExists(bgReading, "DexcomG5");
if (isNew && SP.getBoolean(R.string.key_dexcomg5_nsupload, false)) {
NSUpload.uploadBg(bgReading);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
private void handleNewDataFromMM640g(Intent intent) { private void handleNewDataFromMM640g(Intent intent) {
Bundle bundle = intent.getExtras(); Bundle bundle = intent.getExtras();
if (bundle == null) return; if (bundle == null) return;
@ -244,7 +295,7 @@ public class DataService extends IntentService {
MainApp.bus().post(new EventDismissNotification(Notification.OLD_NSCLIENT)); MainApp.bus().post(new EventDismissNotification(Notification.OLD_NSCLIENT));
} }
} catch (PackageManager.NameNotFoundException e) { } catch (PackageManager.NameNotFoundException e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
if (ConfigBuilderPlugin.nightscoutVersionCode < Config.SUPPORTEDNSVERSION) { if (ConfigBuilderPlugin.nightscoutVersionCode < Config.SUPPORTEDNSVERSION) {
Notification notification = new Notification(Notification.OLD_NS, MainApp.sResources.getString(R.string.unsupportednsversion), Notification.URGENT); Notification notification = new Notification(Notification.OLD_NS, MainApp.sResources.getString(R.string.unsupportednsversion), Notification.URGENT);
@ -269,7 +320,7 @@ public class DataService extends IntentService {
if (targetlow != null) if (targetlow != null)
OverviewPlugin.bgTargetLow = targetlow; OverviewPlugin.bgTargetLow = targetlow;
} catch (JSONException e) { } catch (JSONException e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
} }
} }
@ -298,7 +349,7 @@ public class DataService extends IntentService {
} }
} }
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
} }
// Handle profile // Handle profile
@ -313,10 +364,11 @@ public class DataService extends IntentService {
if (Config.logIncommingData) if (Config.logIncommingData)
log.debug("Received profileStore: " + activeProfile + " " + profile); log.debug("Received profileStore: " + activeProfile + " " + profile);
} catch (JSONException e) { } catch (JSONException e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
} }
if (intent.getAction().equals(Intents.ACTION_NEW_TREATMENT)) {
if (intent.getAction().equals(Intents.ACTION_NEW_TREATMENT) || intent.getAction().equals(Intents.ACTION_CHANGED_TREATMENT)) {
try { try {
if (bundles.containsKey("treatment")) { if (bundles.containsKey("treatment")) {
String trstring = bundles.getString("treatment"); String trstring = bundles.getString("treatment");
@ -332,28 +384,7 @@ public class DataService extends IntentService {
} }
} }
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); log.error("Unhandled exception", e);
}
}
if (intent.getAction().equals(Intents.ACTION_CHANGED_TREATMENT)) {
try {
if (bundles.containsKey("treatment")) {
String trstring = bundles.getString("treatment");
handleAddChangeDataFromNS(trstring);
}
if (bundles.containsKey("treatments")) {
String trstring = bundles.getString("treatments");
JSONArray jsonArray = new JSONArray(trstring);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject trJson = jsonArray.getJSONObject(i);
String trstr = trJson.toString();
handleAddChangeDataFromNS(trstr);
}
}
} catch (Exception e) {
e.printStackTrace();
} }
} }
@ -376,7 +407,7 @@ public class DataService extends IntentService {
} }
} }
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
} }
@ -401,7 +432,7 @@ public class DataService extends IntentService {
} }
} }
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
} }
@ -430,9 +461,59 @@ public class DataService extends IntentService {
} }
} }
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
} }
if (intent.getAction().equals(Intents.ACTION_NEW_FOOD) || intent.getAction().equals(Intents.ACTION_CHANGED_FOOD)) {
try {
if (bundles.containsKey("food")) {
String trstring = bundles.getString("food");
handleAddChangeFoodRecord(new JSONObject(trstring));
}
if (bundles.containsKey("foods")) {
String trstring = bundles.getString("foods");
JSONArray jsonArray = new JSONArray(trstring);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject trJson = jsonArray.getJSONObject(i);
handleAddChangeFoodRecord(trJson);
}
}
} catch (Exception e) {
log.error("Unhandled exception", e);
}
}
if (intent.getAction().equals(Intents.ACTION_REMOVED_FOOD)) {
try {
if (bundles.containsKey("food")) {
String trstring = bundles.getString("food");
JSONObject trJson = new JSONObject(trstring);
String _id = trJson.getString("_id");
handleRemovedFoodRecord(_id);
}
if (bundles.containsKey("foods")) {
String trstring = bundles.getString("foods");
JSONArray jsonArray = new JSONArray(trstring);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject trJson = jsonArray.getJSONObject(i);
String _id = trJson.getString("_id");
handleRemovedFoodRecord(_id);
}
}
} catch (Exception e) {
log.error("Unhandled exception", e);
}
}
}
private void handleRemovedFoodRecord(String _id) {
MainApp.getDbHelper().foodHelper.deleteFoodById(_id);
}
public void handleAddChangeFoodRecord(JSONObject trJson) throws JSONException {
MainApp.getDbHelper().foodHelper.createFoodFromJsonIfNotExists(trJson);
} }
private void handleRemovedRecordFromNS(String _id) { private void handleRemovedRecordFromNS(String _id) {

View file

@ -8,6 +8,9 @@ public interface Intents {
String ACTION_NEW_PROFILE = "info.nightscout.client.NEW_PROFILE"; String ACTION_NEW_PROFILE = "info.nightscout.client.NEW_PROFILE";
String ACTION_NEW_SGV = "info.nightscout.client.NEW_SGV"; String ACTION_NEW_SGV = "info.nightscout.client.NEW_SGV";
String ACTION_NEW_DEVICESTATUS = "info.nightscout.client.NEW_DEVICESTATUS"; String ACTION_NEW_DEVICESTATUS = "info.nightscout.client.NEW_DEVICESTATUS";
String ACTION_NEW_FOOD = "info.nightscout.client.NEW_FOOD";
String ACTION_CHANGED_FOOD = "info.nightscout.client.CHANGED_FOOD";
String ACTION_REMOVED_FOOD = "info.nightscout.client.REMOVED_FOOD";
String ACTION_NEW_MBG = "info.nightscout.client.NEW_MBG"; String ACTION_NEW_MBG = "info.nightscout.client.NEW_MBG";
String ACTION_NEW_CAL = "info.nightscout.client.NEW_CAL"; String ACTION_NEW_CAL = "info.nightscout.client.NEW_CAL";
String ACTION_NEW_STATUS = "info.nightscout.client.NEW_STATUS"; String ACTION_NEW_STATUS = "info.nightscout.client.NEW_STATUS";
@ -42,4 +45,6 @@ public interface Intents {
String ACTION_REMOTE_CALIBRATION = "com.eveningoutpost.dexdrip.NewCalibration"; String ACTION_REMOTE_CALIBRATION = "com.eveningoutpost.dexdrip.NewCalibration";
String GLIMP_BG = "it.ct.glicemia.ACTION_GLUCOSE_MEASURED"; String GLIMP_BG = "it.ct.glicemia.ACTION_GLUCOSE_MEASURED";
String DEXCOMG5_BG = "com.dexcom.cgm.DATA";
} }

View file

@ -29,4 +29,14 @@ public class DetailedBolusInfo {
public Context context = null; // context for progress dialog public Context context = null; // context for progress dialog
public long pumpId = 0; // id of record if comming from pump history (not a newly created treatment) public long pumpId = 0; // id of record if comming from pump history (not a newly created treatment)
public boolean isSMB = false; // is a Super-MicroBolus public boolean isSMB = false; // is a Super-MicroBolus
@Override
public String toString() {
return new Date(date).toLocaleString() +
" insulin: " + insulin +
" carbs: " + carbs +
" isValid: " + isValid +
" carbTime: " + carbTime +
" isSMB: " + isSMB;
}
} }

View file

@ -2,6 +2,8 @@ package info.nightscout.androidaps.data;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Date; import java.util.Date;
@ -9,6 +11,8 @@ import info.nightscout.utils.DateUtil;
import info.nightscout.utils.Round; import info.nightscout.utils.Round;
public class IobTotal { public class IobTotal {
private static Logger log = LoggerFactory.getLogger(IobTotal.class);
public double iob; public double iob;
public double activity; public double activity;
public double bolussnooze; public double bolussnooze;
@ -86,7 +90,7 @@ public class IobTotal {
json.put("activity", activity); json.put("activity", activity);
json.put("time", DateUtil.toISOString(new Date())); json.put("time", DateUtil.toISOString(new Date()));
} catch (JSONException e) { } catch (JSONException e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
return json; return json;
} }
@ -100,7 +104,7 @@ public class IobTotal {
json.put("activity", activity); json.put("activity", activity);
json.put("time", DateUtil.toISOString(new Date(time))); json.put("time", DateUtil.toISOString(new Date(time)));
} catch (JSONException e) { } catch (JSONException e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
return json; return json;
} }

View file

@ -12,13 +12,12 @@ import org.slf4j.LoggerFactory;
import java.text.DecimalFormat; import java.text.DecimalFormat;
import java.util.Calendar; import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone; import java.util.TimeZone;
import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.plugins.Overview.Notification; import info.nightscout.androidaps.plugins.Overview.notifications.Notification;
import info.nightscout.androidaps.plugins.Overview.events.EventDismissNotification; import info.nightscout.androidaps.plugins.Overview.events.EventDismissNotification;
import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification; import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification;
import info.nightscout.utils.DecimalFormatter; import info.nightscout.utils.DecimalFormatter;
@ -29,19 +28,24 @@ public class Profile {
private JSONObject json; private JSONObject json;
private String units = null; private String units = null;
double dia = Constants.defaultDIA; private double dia = Constants.defaultDIA;
TimeZone timeZone = TimeZone.getDefault(); private TimeZone timeZone = TimeZone.getDefault();
JSONArray isf; private JSONArray isf;
private LongSparseArray<Double> isf_v = null; // oldest at index 0 private LongSparseArray<Double> isf_v = null; // oldest at index 0
JSONArray ic; private JSONArray ic;
private LongSparseArray<Double> ic_v = null; // oldest at index 0 private LongSparseArray<Double> ic_v = null; // oldest at index 0
JSONArray basal; private JSONArray basal;
private LongSparseArray<Double> basal_v = null; // oldest at index 0 private LongSparseArray<Double> basal_v = null; // oldest at index 0
JSONArray targetLow; private JSONArray targetLow;
JSONArray targetHigh; private LongSparseArray<Double> targetLow_v = null; // oldest at index 0
private JSONArray targetHigh;
private LongSparseArray<Double> targetHigh_v = null; // oldest at index 0
private int percentage = 100;
private int timeshift = 0;
public Profile(JSONObject json, String units) { public Profile(JSONObject json, String units) {
this(json); this(json, 100, 0);
if (this.units == null) { if (this.units == null) {
if (units != null) if (units != null)
this.units = units; this.units = units;
@ -52,7 +56,9 @@ public class Profile {
} }
} }
public Profile(JSONObject json) { public Profile(JSONObject json, int percentage, int timeshift) {
this.percentage = percentage;
this.timeshift = timeshift;
this.json = json; this.json = json;
try { try {
if (json.has("units")) if (json.has("units"))
@ -109,7 +115,7 @@ public class Profile {
MainApp.bus().post(new EventDismissNotification(Notification.TARGET_MISSING)); MainApp.bus().post(new EventDismissNotification(Notification.TARGET_MISSING));
} }
} catch (JSONException e) { } catch (JSONException e) {
e.printStackTrace(); log.error("Unhandled exception", e);
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.sResources.getString(R.string.invalidprofile)); ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.sResources.getString(R.string.invalidprofile));
} }
} }
@ -129,7 +135,7 @@ public class Profile {
try { try {
json.put("units", units); json.put("units", units);
} catch (JSONException e) { } catch (JSONException e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
return json; return json;
} }
@ -148,17 +154,25 @@ public class Profile {
} }
private LongSparseArray<Double> convertToSparseArray(JSONArray array) { private LongSparseArray<Double> convertToSparseArray(JSONArray array) {
double multiplier = getMultiplier(array);
LongSparseArray<Double> sparse = new LongSparseArray<>(); LongSparseArray<Double> sparse = new LongSparseArray<>();
for (Integer index = 0; index < array.length(); index++) { for (Integer index = 0; index < array.length(); index++) {
try { try {
JSONObject o = array.getJSONObject(index); JSONObject o = array.getJSONObject(index);
long tas = o.getLong("timeAsSeconds"); long tas = getShitfTimeSecs((int) o.getLong("timeAsSeconds"));
Double value = o.getDouble("value"); Double value = o.getDouble("value") * multiplier;
sparse.put(tas, value); sparse.put(tas, value);
} catch (JSONException e) { } catch (JSONException e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
} }
// check if start is at 0 (midnight)
// and add last value before midnight if not
if (sparse.keyAt(0) != 0) {
sparse.put(0, sparse.valueAt(sparse.size() - 1));
}
return sparse; return sparse;
} }
@ -176,13 +190,53 @@ public class Profile {
} }
lastValue = value; lastValue = value;
} catch (JSONException e) { } catch (JSONException e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
} }
return lastValue; return lastValue;
} }
private Double getValueToTime(LongSparseArray<Double> array, long timeAsSeconds) { Integer getShitfTimeSecs(Integer originalTime) {
Integer shiftedTime = originalTime + timeshift * 60 * 60;
shiftedTime = (shiftedTime + 24 * 60 * 60) % (24 * 60 * 60);
if (timeshift != 0)
log.debug("(Sec) Original time: " + originalTime + " ShiftedTime: " + shiftedTime);
return shiftedTime;
}
private double getMultiplier(LongSparseArray<Double> array) {
double multiplier = 1d;
if (array == isf_v)
multiplier = 100d / percentage;
else if (array == ic_v)
multiplier = 100d / percentage;
else if (array == basal_v)
multiplier = percentage / 100d;
else
log.error("Unknown array type");
return multiplier;
}
private double getMultiplier(JSONArray array) {
double multiplier = 1d;
if (array == isf)
multiplier = 100d / percentage;
else if (array == ic)
multiplier = 100d / percentage;
else if (array == basal)
multiplier = percentage / 100d;
else if (array == targetLow)
multiplier = 1d;
else if (array == targetHigh)
multiplier = 1d;
else
log.error("Unknown array type");
return multiplier;
}
private Double getValueToTime(LongSparseArray<Double> array, Integer timeAsSeconds) {
Double lastValue = null; Double lastValue = null;
for (Integer index = 0; index < array.size(); index++) { for (Integer index = 0; index < array.size(); index++) {
@ -197,26 +251,29 @@ public class Profile {
return lastValue; return lastValue;
} }
private String getValuesList(JSONArray array, JSONArray array2, DecimalFormat format, String units) { private String format_HH_MM(Integer timeAsSeconds) {
String time;
int hour = timeAsSeconds / 60 / 60;
int minutes = (timeAsSeconds - hour * 60 * 60) / 60;
DecimalFormat df = new DecimalFormat("00");
time = df.format(hour) + ":" + df.format(minutes);
return time;
}
private String getValuesList(LongSparseArray<Double> array, LongSparseArray<Double> array2, DecimalFormat format, String units) {
String retValue = ""; String retValue = "";
for (Integer index = 0; index < array.length(); index++) { for (Integer index = 0; index < array.size(); index++) {
try { retValue += format_HH_MM((int) array.keyAt(index));
JSONObject o = array.getJSONObject(index); retValue += " ";
retValue += o.getString("time"); retValue += format.format(array.valueAt(index));
retValue += " "; if (array2 != null) {
retValue += format.format(o.getDouble("value")); retValue += " - ";
if (array2 != null) { retValue += format.format(array2.valueAt(index));
JSONObject o2 = array2.getJSONObject(index);
retValue += " - ";
retValue += format.format(o2.getDouble("value"));
}
retValue += " " + units;
if (index + 1 < array.length())
retValue += "\n";
} catch (JSONException e) {
e.printStackTrace();
} }
retValue += " " + units;
if (index + 1 < array.size())
retValue += "\n";
} }
return retValue; return retValue;
} }
@ -236,7 +293,7 @@ public class Profile {
} }
public String getIsfList() { public String getIsfList() {
return getValuesList(isf, null, new DecimalFormat("0.0"), getUnits() + "/U"); return getValuesList(isf_v, null, new DecimalFormat("0.0"), getUnits() + "/U");
} }
public Double getIc() { public Double getIc() {
@ -254,7 +311,7 @@ public class Profile {
} }
public String getIcList() { public String getIcList() {
return getValuesList(ic, null, new DecimalFormat("0.0"), " g/U"); return getValuesList(ic_v, null, new DecimalFormat("0.0"), " g/U");
} }
public Double getBasal() { public Double getBasal() {
@ -272,7 +329,7 @@ public class Profile {
} }
public String getBasalList() { public String getBasalList() {
return getValuesList(basal, null, new DecimalFormat("0.00"), "U"); return getValuesList(basal_v, null, new DecimalFormat("0.00"), "U");
} }
public class BasalValue { public class BasalValue {
@ -286,20 +343,14 @@ public class Profile {
} }
public BasalValue[] getBasalValues() { public BasalValue[] getBasalValues() {
try { BasalValue[] ret = new BasalValue[basal_v.size()];
BasalValue[] ret = new BasalValue[basal.length()];
for (Integer index = 0; index < basal.length(); index++) { for (Integer index = 0; index < basal_v.size(); index++) {
JSONObject o = basal.getJSONObject(index); Integer tas = (int) basal_v.keyAt(index);
Integer tas = o.getInt("timeAsSeconds"); Double value = basal_v.valueAt(index);
Double value = o.getDouble("value"); ret[index] = new BasalValue(tas, value);
ret[index] = new BasalValue(tas, value);
}
return ret;
} catch (JSONException e) {
e.printStackTrace();
} }
return new BasalValue[0]; return ret;
} }
public Double getTargetLow() { public Double getTargetLow() {
@ -311,7 +362,9 @@ public class Profile {
} }
public Double getTargetLow(Integer timeAsSeconds) { public Double getTargetLow(Integer timeAsSeconds) {
return getValueToTime(targetLow, timeAsSeconds); if (targetLow_v == null)
targetLow_v = convertToSparseArray(targetLow);
return getValueToTime(targetLow_v, timeAsSeconds);
} }
public Double getTargetHigh() { public Double getTargetHigh() {
@ -323,11 +376,13 @@ public class Profile {
} }
public Double getTargetHigh(Integer timeAsSeconds) { public Double getTargetHigh(Integer timeAsSeconds) {
return getValueToTime(targetHigh, timeAsSeconds); if (targetHigh_v == null)
targetHigh_v = convertToSparseArray(targetHigh);
return getValueToTime(targetHigh_v, timeAsSeconds);
} }
public String getTargetList() { public String getTargetList() {
return getValuesList(targetLow, targetHigh, new DecimalFormat("0.0"), getUnits()); return getValuesList(targetLow_v, targetHigh_v, new DecimalFormat("0.0"), getUnits());
} }
public double getMaxDailyBasal() { public double getMaxDailyBasal() {
@ -350,18 +405,6 @@ public class Profile {
return (int) (passed / 1000); return (int) (passed / 1000);
} }
public static Integer secondsFromMidnight(Date date) {
Calendar c = Calendar.getInstance();
long now = date.getTime();
c.setTime(date);
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
long passed = now - c.getTimeInMillis();
return (int) (passed / 1000);
}
public static Integer secondsFromMidnight(long date) { public static Integer secondsFromMidnight(long date) {
Calendar c = Calendar.getInstance(); Calendar c = Calendar.getInstance();
c.setTimeInMillis(date); c.setTimeInMillis(date);
@ -410,4 +453,29 @@ public class Profile {
return toUnitsString(lowMgdl, lowMmol, units) + " - " + toUnitsString(highMgdl, highMmol, units); return toUnitsString(lowMgdl, lowMmol, units) + " - " + toUnitsString(highMgdl, highMmol, units);
} }
public double percentageBasalSum() {
double result = 0d;
for (int i = 0; i < 24; i++) {
result += getBasal((Integer) (i * 60 * 60));
}
return result;
}
public double baseBasalSum() {
double result = 0d;
for (int i = 0; i < 24; i++) {
result += getBasal((Integer) (i * 60 * 60)) / getMultiplier(basal_v);
}
return result;
}
public int getPercentage() {
return percentage;
}
public int getTimeshift() {
return timeshift;
}
} }

View file

@ -50,7 +50,7 @@ public class ProfileStore {
} }
} }
} catch (JSONException e) { } catch (JSONException e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
return profile; return profile;
} }
@ -65,7 +65,7 @@ public class ProfileStore {
return defaultProfileName; return defaultProfileName;
} }
} catch (JSONException e) { } catch (JSONException e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
return defaultProfileName; return defaultProfileName;
} }
@ -90,7 +90,7 @@ public class ProfileStore {
} }
} }
} catch (JSONException e) { } catch (JSONException e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
return profile; return profile;
} }
@ -108,7 +108,7 @@ public class ProfileStore {
ret.add(profileName); ret.add(profileName);
} }
} catch (JSONException e) { } catch (JSONException e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
return ret; return ret;

View file

@ -5,6 +5,8 @@ import android.text.Spanned;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
@ -12,6 +14,8 @@ import info.nightscout.utils.DecimalFormatter;
import info.nightscout.utils.Round; import info.nightscout.utils.Round;
public class PumpEnactResult extends Object { public class PumpEnactResult extends Object {
private static Logger log = LoggerFactory.getLogger(PumpEnactResult.class);
public boolean success = false; // request was processed successfully (but possible no change was needed) public boolean success = false; // request was processed successfully (but possible no change was needed)
public boolean enacted = false; // request was processed successfully and change has been made public boolean enacted = false; // request was processed successfully and change has been made
public String comment = ""; public String comment = "";
@ -28,6 +32,61 @@ public class PumpEnactResult extends Object {
public boolean queued = false; public boolean queued = false;
public PumpEnactResult success(boolean success) {
this.success = success;
return this;
}
public PumpEnactResult enacted(boolean enacted) {
this.enacted = enacted;
return this;
}
public PumpEnactResult comment(String comment) {
this.comment = comment;
return this;
}
public PumpEnactResult duration(Integer duration) {
this.duration = duration;
return this;
}
public PumpEnactResult absolute(Double absolute) {
this.absolute = absolute;
return this;
}
public PumpEnactResult percent(Integer percent) {
this.percent = percent;
return this;
}
public PumpEnactResult isPercent(boolean isPercent) {
this.isPercent = isPercent;
return this;
}
public PumpEnactResult isTempCancel(boolean isTempCancel) {
this.isTempCancel = isTempCancel;
return this;
}
public PumpEnactResult bolusDelivered(Double bolusDelivered) {
this.bolusDelivered = bolusDelivered;
return this;
}
public PumpEnactResult carbsDelivered(Double carbsDelivered) {
this.carbsDelivered = carbsDelivered;
return this;
}
public PumpEnactResult queued(boolean queued) {
this.queued = queued;
return this;
}
public String log() { public String log() {
return "Success: " + success + " Enacted: " + enacted + " Comment: " + comment + " Duration: " + duration + " Absolute: " + absolute + " Percent: " + percent + " IsPercent: " + isPercent + " Queued: " + queued; return "Success: " + success + " Enacted: " + enacted + " Comment: " + comment + " Duration: " + duration + " Absolute: " + absolute + " Percent: " + percent + " IsPercent: " + isPercent + " Queued: " + queued;
} }
@ -101,7 +160,7 @@ public class PumpEnactResult extends Object {
result.put("duration", duration); result.put("duration", duration);
} }
} catch (JSONException e) { } catch (JSONException e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
return result; return result;
} }

View file

@ -96,7 +96,9 @@ public class BgReading implements DataPointWithLabelInterface {
direction.compareTo("NOT COMPUTABLE") == 0 || direction.compareTo("NOT COMPUTABLE") == 0 ||
direction.compareTo("OUT_OF_RANGE") == 0 || direction.compareTo("OUT_OF_RANGE") == 0 ||
direction.compareTo("OUT OF RANGE") == 0 || direction.compareTo("OUT OF RANGE") == 0 ||
direction.compareTo("NONE") == 0) { direction.compareTo("NONE") == 0 ||
direction.compareTo("NotComputable") == 0
) {
return true; return true;
} else { } else {
return false; return false;

View file

@ -142,7 +142,7 @@ public class CareportalEvent implements DataPointWithLabelInterface {
JSONObject object = new JSONObject(json); JSONObject object = new JSONObject(json);
mbg = object.getDouble("mgdl"); mbg = object.getDouble("mgdl");
} catch (JSONException e) { } catch (JSONException e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
return Profile.fromMgdlToUnits(mbg, units); return Profile.fromMgdlToUnits(mbg, units);
} }
@ -155,7 +155,7 @@ public class CareportalEvent implements DataPointWithLabelInterface {
units = object.getString("units"); units = object.getString("units");
} }
} catch (JSONException e) { } catch (JSONException e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
if (glucose != 0d) { if (glucose != 0d) {
double mmol = 0d; double mmol = 0d;
@ -186,7 +186,7 @@ public class CareportalEvent implements DataPointWithLabelInterface {
if (object.has("notes")) if (object.has("notes"))
return object.getString("notes"); return object.getString("notes");
} catch (JSONException e) { } catch (JSONException e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
return Translator.translate(eventType); return Translator.translate(eventType);
} }
@ -198,7 +198,7 @@ public class CareportalEvent implements DataPointWithLabelInterface {
if (object.has("duration")) if (object.has("duration"))
return object.getInt("duration") * 60 * 1000L; return object.getInt("duration") * 60 * 1000L;
} catch (JSONException e) { } catch (JSONException e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
return 0; return 0;
} }

View file

@ -33,6 +33,7 @@ import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.events.EventCareportalEventChange; import info.nightscout.androidaps.events.EventCareportalEventChange;
import info.nightscout.androidaps.events.EventExtendedBolusChange; import info.nightscout.androidaps.events.EventExtendedBolusChange;
import info.nightscout.androidaps.events.EventFoodDatabaseChanged;
import info.nightscout.androidaps.events.EventNewBG; import info.nightscout.androidaps.events.EventNewBG;
import info.nightscout.androidaps.events.EventProfileSwitchChange; import info.nightscout.androidaps.events.EventProfileSwitchChange;
import info.nightscout.androidaps.events.EventRefreshOverview; import info.nightscout.androidaps.events.EventRefreshOverview;
@ -59,6 +60,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
public static final String DATABASE_DBREQUESTS = "DBRequests"; public static final String DATABASE_DBREQUESTS = "DBRequests";
public static final String DATABASE_CAREPORTALEVENTS = "CareportalEvents"; public static final String DATABASE_CAREPORTALEVENTS = "CareportalEvents";
public static final String DATABASE_PROFILESWITCHES = "ProfileSwitches"; public static final String DATABASE_PROFILESWITCHES = "ProfileSwitches";
public static final String DATABASE_FOODS = "Foods";
private static final int DATABASE_VERSION = 8; private static final int DATABASE_VERSION = 8;
@ -85,6 +87,8 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
private static final ScheduledExecutorService profileSwitchEventWorker = Executors.newSingleThreadScheduledExecutor(); private static final ScheduledExecutorService profileSwitchEventWorker = Executors.newSingleThreadScheduledExecutor();
private static ScheduledFuture<?> scheduledProfileSwitchEventPost = null; private static ScheduledFuture<?> scheduledProfileSwitchEventPost = null;
public FoodHelper foodHelper = new FoodHelper(this);
public DatabaseHelper(Context context) { public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION); super(context, DATABASE_NAME, null, DATABASE_VERSION);
onCreate(getWritableDatabase(), getConnectionSource()); onCreate(getWritableDatabase(), getConnectionSource());
@ -104,6 +108,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
TableUtils.createTableIfNotExists(connectionSource, ExtendedBolus.class); TableUtils.createTableIfNotExists(connectionSource, ExtendedBolus.class);
TableUtils.createTableIfNotExists(connectionSource, CareportalEvent.class); TableUtils.createTableIfNotExists(connectionSource, CareportalEvent.class);
TableUtils.createTableIfNotExists(connectionSource, ProfileSwitch.class); TableUtils.createTableIfNotExists(connectionSource, ProfileSwitch.class);
TableUtils.createTableIfNotExists(connectionSource, Food.class);
} catch (SQLException e) { } catch (SQLException e) {
log.error("Can't create database", e); log.error("Can't create database", e);
throw new RuntimeException(e); throw new RuntimeException(e);
@ -128,6 +133,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
TableUtils.dropTable(connectionSource, ExtendedBolus.class, true); TableUtils.dropTable(connectionSource, ExtendedBolus.class, true);
TableUtils.dropTable(connectionSource, CareportalEvent.class, true); TableUtils.dropTable(connectionSource, CareportalEvent.class, true);
TableUtils.dropTable(connectionSource, ProfileSwitch.class, true); TableUtils.dropTable(connectionSource, ProfileSwitch.class, true);
TableUtils.dropTable(connectionSource, Food.class, true);
onCreate(database, connectionSource); onCreate(database, connectionSource);
} }
} catch (SQLException e) { } catch (SQLException e) {
@ -205,9 +211,10 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
TableUtils.createTableIfNotExists(connectionSource, ExtendedBolus.class); TableUtils.createTableIfNotExists(connectionSource, ExtendedBolus.class);
TableUtils.createTableIfNotExists(connectionSource, CareportalEvent.class); TableUtils.createTableIfNotExists(connectionSource, CareportalEvent.class);
TableUtils.createTableIfNotExists(connectionSource, ProfileSwitch.class); TableUtils.createTableIfNotExists(connectionSource, ProfileSwitch.class);
foodHelper.resetFood();
updateEarliestDataChange(0); updateEarliestDataChange(0);
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
VirtualPumpPlugin.setFakingStatus(true); VirtualPumpPlugin.setFakingStatus(true);
scheduleBgChange(); // trigger refresh scheduleBgChange(); // trigger refresh
@ -217,6 +224,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
scheduleTemporaryTargetChange(); scheduleTemporaryTargetChange();
scheduleCareportalEventChange(); scheduleCareportalEventChange();
scheduleProfileSwitchChange(); scheduleProfileSwitchChange();
foodHelper.scheduleFoodChange();
new java.util.Timer().schedule( new java.util.Timer().schedule(
new java.util.TimerTask() { new java.util.TimerTask() {
@Override @Override
@ -234,7 +242,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
TableUtils.createTableIfNotExists(connectionSource, Treatment.class); TableUtils.createTableIfNotExists(connectionSource, Treatment.class);
updateEarliestDataChange(0); updateEarliestDataChange(0);
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
scheduleTreatmentChange(); scheduleTreatmentChange();
} }
@ -244,7 +252,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
TableUtils.dropTable(connectionSource, TempTarget.class, true); TableUtils.dropTable(connectionSource, TempTarget.class, true);
TableUtils.createTableIfNotExists(connectionSource, TempTarget.class); TableUtils.createTableIfNotExists(connectionSource, TempTarget.class);
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
scheduleTemporaryTargetChange(); scheduleTemporaryTargetChange();
} }
@ -255,7 +263,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
TableUtils.createTableIfNotExists(connectionSource, TemporaryBasal.class); TableUtils.createTableIfNotExists(connectionSource, TemporaryBasal.class);
updateEarliestDataChange(0); updateEarliestDataChange(0);
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
VirtualPumpPlugin.setFakingStatus(false); VirtualPumpPlugin.setFakingStatus(false);
scheduleTemporaryBasalChange(); scheduleTemporaryBasalChange();
@ -267,7 +275,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
TableUtils.createTableIfNotExists(connectionSource, ExtendedBolus.class); TableUtils.createTableIfNotExists(connectionSource, ExtendedBolus.class);
updateEarliestDataChange(0); updateEarliestDataChange(0);
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
scheduleExtendedBolusChange(); scheduleExtendedBolusChange();
} }
@ -277,7 +285,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
TableUtils.dropTable(connectionSource, CareportalEvent.class, true); TableUtils.dropTable(connectionSource, CareportalEvent.class, true);
TableUtils.createTableIfNotExists(connectionSource, CareportalEvent.class); TableUtils.createTableIfNotExists(connectionSource, CareportalEvent.class);
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
scheduleCareportalEventChange(); scheduleCareportalEventChange();
} }
@ -287,7 +295,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
TableUtils.dropTable(connectionSource, ProfileSwitch.class, true); TableUtils.dropTable(connectionSource, ProfileSwitch.class, true);
TableUtils.createTableIfNotExists(connectionSource, ProfileSwitch.class); TableUtils.createTableIfNotExists(connectionSource, ProfileSwitch.class);
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
scheduleProfileSwitchChange(); scheduleProfileSwitchChange();
} }
@ -335,7 +343,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
} }
// ------------------- BgReading handling ----------------------- // ------------------- BgReading handling -----------------------
public void createIfNotExists(BgReading bgReading, String from) { public boolean createIfNotExists(BgReading bgReading, String from) {
try { try {
bgReading.date = roundDateToSec(bgReading.date); bgReading.date = roundDateToSec(bgReading.date);
BgReading old = getDaoBgReadings().queryForId(bgReading.date); BgReading old = getDaoBgReadings().queryForId(bgReading.date);
@ -343,18 +351,20 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
getDaoBgReadings().create(bgReading); getDaoBgReadings().create(bgReading);
log.debug("BG: New record from: " + from + " " + bgReading.toString()); log.debug("BG: New record from: " + from + " " + bgReading.toString());
scheduleBgChange(); scheduleBgChange();
return; return true;
} }
if (!old.isEqual(bgReading)) { if (!old.isEqual(bgReading)) {
log.debug("BG: Similiar found: " + old.toString());
old.copyFrom(bgReading); old.copyFrom(bgReading);
getDaoBgReadings().update(old); getDaoBgReadings().update(old);
log.debug("BG: Updating record from: " + from + " " + old.toString()); log.debug("BG: Updating record from: " + from + " New data: " + old.toString());
scheduleBgChange(); scheduleBgChange();
return; return false;
} }
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
return false;
} }
private static void scheduleBgChange() { private static void scheduleBgChange() {
@ -430,7 +440,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
bgReadings = daoBgreadings.query(preparedQuery); bgReadings = daoBgreadings.query(preparedQuery);
return bgReadings; return bgReadings;
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
return new ArrayList<BgReading>(); return new ArrayList<BgReading>();
} }
@ -441,7 +451,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
try { try {
getDaoDbRequest().create(dbr); getDaoDbRequest().create(dbr);
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
} }
@ -449,7 +459,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
try { try {
return getDaoDbRequest().delete(dbr); return getDaoDbRequest().delete(dbr);
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
return 0; return 0;
} }
@ -458,7 +468,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
try { try {
return getDaoDbRequest().deleteById(nsClientId); return getDaoDbRequest().deleteById(nsClientId);
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
return 0; return 0;
} }
@ -478,7 +488,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
return delete(dbList.get(0)); return delete(dbList.get(0));
} }
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
return 0; return 0;
} }
@ -487,7 +497,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
try { try {
TableUtils.clearTable(connectionSource, DbRequest.class); TableUtils.clearTable(connectionSource, DbRequest.class);
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
} }
@ -495,7 +505,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
try { try {
return getDaoDbRequest().closeableIterator(); return getDaoDbRequest().closeableIterator();
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); log.error("Unhandled exception", e);
return null; return null;
} }
} }
@ -583,7 +593,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
return true; return true;
} }
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
return false; return false;
} }
@ -593,7 +603,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
getDaoTreatments().delete(treatment); getDaoTreatments().delete(treatment);
updateEarliestDataChange(treatment.date); updateEarliestDataChange(treatment.date);
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
scheduleTreatmentChange(); scheduleTreatmentChange();
} }
@ -603,7 +613,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
getDaoTreatments().update(treatment); getDaoTreatments().update(treatment);
updateEarliestDataChange(treatment.date); updateEarliestDataChange(treatment.date);
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
scheduleTreatmentChange(); scheduleTreatmentChange();
} }
@ -636,7 +646,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
return trList.get(0); return trList.get(0);
} }
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
return null; return null;
} }
@ -655,8 +665,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
class PostRunnable implements Runnable { class PostRunnable implements Runnable {
public void run() { public void run() {
log.debug("Firing EventTreatmentChange"); log.debug("Firing EventTreatmentChange");
MainApp.bus().post(new EventReloadTreatmentData()); MainApp.bus().post(new EventReloadTreatmentData(new EventTreatmentChange()));
MainApp.bus().post(new EventTreatmentChange());
if (earliestDataChange != null) if (earliestDataChange != null)
MainApp.bus().post(new EventNewHistoryData(earliestDataChange)); MainApp.bus().post(new EventNewHistoryData(earliestDataChange));
earliestDataChange = null; earliestDataChange = null;
@ -673,6 +682,24 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
} }
@Nullable
public Treatment getTreatmentByDate(long mills) {
try {
Dao<Treatment, Long> daoTreatments = getDaoTreatments();
List<Treatment> treatments;
QueryBuilder<Treatment, Long> queryBuilder = daoTreatments.queryBuilder();
Where where = queryBuilder.where();
where.eq("date", mills);
PreparedQuery<Treatment> preparedQuery = queryBuilder.prepare();
treatments = daoTreatments.query(preparedQuery);
// date is unique
return treatments.isEmpty() ? null : treatments.get(0);
} catch (SQLException e) {
log.error("Unhandled exception", e);
return null;
}
}
public List<Treatment> getTreatmentDataFromTime(long mills, boolean ascending) { public List<Treatment> getTreatmentDataFromTime(long mills, boolean ascending) {
try { try {
Dao<Treatment, Long> daoTreatments = getDaoTreatments(); Dao<Treatment, Long> daoTreatments = getDaoTreatments();
@ -685,7 +712,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
treatments = daoTreatments.query(preparedQuery); treatments = daoTreatments.query(preparedQuery);
return treatments; return treatments;
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
return new ArrayList<Treatment>(); return new ArrayList<Treatment>();
} }
@ -715,7 +742,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
} }
createOrUpdate(treatment); createOrUpdate(treatment);
} catch (JSONException e) { } catch (JSONException e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
} }
@ -733,7 +760,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
tempTargets = daoTempTargets.query(preparedQuery); tempTargets = daoTempTargets.query(preparedQuery);
return tempTargets; return tempTargets;
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
return new ArrayList<TempTarget>(); return new ArrayList<TempTarget>();
} }
@ -787,7 +814,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
return true; return true;
} }
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
return false; return false;
} }
@ -797,7 +824,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
getDaoTempTargets().delete(tempTarget); getDaoTempTargets().delete(tempTarget);
scheduleTemporaryTargetChange(); scheduleTemporaryTargetChange();
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
} }
@ -847,7 +874,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
tempTarget.source = Source.NIGHTSCOUT; tempTarget.source = Source.NIGHTSCOUT;
createOrUpdate(tempTarget); createOrUpdate(tempTarget);
} catch (JSONException e) { } catch (JSONException e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
} }
@ -874,7 +901,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
return null; return null;
} }
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
return null; return null;
} }
@ -885,7 +912,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
try { try {
getDaoDanaRHistory().createOrUpdate(record); getDaoDanaRHistory().createOrUpdate(record);
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
} }
@ -900,7 +927,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
PreparedQuery<DanaRHistoryRecord> preparedQuery = queryBuilder.prepare(); PreparedQuery<DanaRHistoryRecord> preparedQuery = queryBuilder.prepare();
historyList = getDaoDanaRHistory().query(preparedQuery); historyList = getDaoDanaRHistory().query(preparedQuery);
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); log.error("Unhandled exception", e);
historyList = new ArrayList<>(); historyList = new ArrayList<>();
} }
return historyList; return historyList;
@ -927,7 +954,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
} }
} }
} catch (SQLException | JSONException e) { } catch (SQLException | JSONException e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
} }
@ -1013,7 +1040,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
return true; return true;
} }
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
return false; return false;
} }
@ -1023,11 +1050,28 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
getDaoTemporaryBasal().delete(tempBasal); getDaoTemporaryBasal().delete(tempBasal);
updateEarliestDataChange(tempBasal.date); updateEarliestDataChange(tempBasal.date);
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
scheduleTemporaryBasalChange(); scheduleTemporaryBasalChange();
} }
@Nullable
public TemporaryBasal getTemporaryBasalsDataByDate(long startTime) {
try {
List<TemporaryBasal> tempbasals;
QueryBuilder<TemporaryBasal, Long> queryBuilder = getDaoTemporaryBasal().queryBuilder();
Where where = queryBuilder.where();
where.eq("date", startTime);
PreparedQuery<TemporaryBasal> preparedQuery = queryBuilder.prepare();
tempbasals = getDaoTemporaryBasal().query(preparedQuery);
// date is unique
return tempbasals.isEmpty() ? null : tempbasals.get(0);
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return null;
}
public List<TemporaryBasal> getTemporaryBasalsDataFromTime(long mills, boolean ascending) { public List<TemporaryBasal> getTemporaryBasalsDataFromTime(long mills, boolean ascending) {
try { try {
List<TemporaryBasal> tempbasals; List<TemporaryBasal> tempbasals;
@ -1039,7 +1083,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
tempbasals = getDaoTemporaryBasal().query(preparedQuery); tempbasals = getDaoTemporaryBasal().query(preparedQuery);
return tempbasals; return tempbasals;
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
return new ArrayList<TemporaryBasal>(); return new ArrayList<TemporaryBasal>();
} }
@ -1132,7 +1176,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
createOrUpdate(tempBasal); createOrUpdate(tempBasal);
} }
} catch (JSONException e) { } catch (JSONException e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
} }
@ -1161,7 +1205,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
return list.get(0); return list.get(0);
} }
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
return null; return null;
} }
@ -1242,7 +1286,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
return true; return true;
} }
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
return false; return false;
} }
@ -1252,7 +1296,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
getDaoExtendedBolus().delete(extendedBolus); getDaoExtendedBolus().delete(extendedBolus);
updateEarliestDataChange(extendedBolus.date); updateEarliestDataChange(extendedBolus.date);
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
scheduleExtendedBolusChange(); scheduleExtendedBolusChange();
} }
@ -1268,7 +1312,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
extendedBoluses = getDaoExtendedBolus().query(preparedQuery); extendedBoluses = getDaoExtendedBolus().query(preparedQuery);
return extendedBoluses; return extendedBoluses;
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
return new ArrayList<ExtendedBolus>(); return new ArrayList<ExtendedBolus>();
} }
@ -1298,7 +1342,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
return null; return null;
} }
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
return null; return null;
} }
@ -1344,12 +1388,12 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
return; return;
} }
extendedBolus.date = trJson.getLong("mills"); extendedBolus.date = trJson.getLong("mills");
extendedBolus.durationInMinutes = trJson.getInt("duration"); extendedBolus.durationInMinutes = trJson.has("duration") ? trJson.getInt("duration") : 0;
extendedBolus.insulin = trJson.getDouble("relative"); extendedBolus.insulin = trJson.getDouble("relative");
extendedBolus._id = trJson.getString("_id"); extendedBolus._id = trJson.getString("_id");
createOrUpdate(extendedBolus); createOrUpdate(extendedBolus);
} catch (SQLException | JSONException e) { } catch (SQLException | JSONException e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
} }
@ -1357,8 +1401,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
class PostRunnable implements Runnable { class PostRunnable implements Runnable {
public void run() { public void run() {
log.debug("Firing EventExtendedBolusChange"); log.debug("Firing EventExtendedBolusChange");
MainApp.bus().post(new EventReloadTreatmentData()); MainApp.bus().post(new EventReloadTreatmentData(new EventExtendedBolusChange()));
MainApp.bus().post(new EventExtendedBolusChange());
if (earliestDataChange != null) if (earliestDataChange != null)
MainApp.bus().post(new EventNewHistoryData(earliestDataChange)); MainApp.bus().post(new EventNewHistoryData(earliestDataChange));
earliestDataChange = null; earliestDataChange = null;
@ -1383,7 +1426,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
try { try {
getDaoCareportalEvents().createOrUpdate(careportalEvent); getDaoCareportalEvents().createOrUpdate(careportalEvent);
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
scheduleCareportalEventChange(); scheduleCareportalEventChange();
} }
@ -1392,7 +1435,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
try { try {
getDaoCareportalEvents().delete(careportalEvent); getDaoCareportalEvents().delete(careportalEvent);
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
scheduleCareportalEventChange(); scheduleCareportalEventChange();
} }
@ -1413,7 +1456,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
else else
return null; return null;
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
return null; return null;
} }
@ -1429,7 +1472,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
careportalEvents = getDaoCareportalEvents().query(preparedQuery); careportalEvents = getDaoCareportalEvents().query(preparedQuery);
return careportalEvents; return careportalEvents;
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
return new ArrayList<CareportalEvent>(); return new ArrayList<CareportalEvent>();
} }
@ -1453,7 +1496,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
log.debug("CareportalEvent not found database: " + _id); log.debug("CareportalEvent not found database: " + _id);
} }
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
} }
@ -1486,7 +1529,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
careportalEvent._id = trJson.getString("_id"); careportalEvent._id = trJson.getString("_id");
createOrUpdate(careportalEvent); createOrUpdate(careportalEvent);
} catch (SQLException | JSONException e) { } catch (SQLException | JSONException e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
} }
@ -1521,7 +1564,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
profileSwitches = daoProfileSwitch.query(preparedQuery); profileSwitches = daoProfileSwitch.query(preparedQuery);
return profileSwitches; return profileSwitches;
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
return new ArrayList<ProfileSwitch>(); return new ArrayList<ProfileSwitch>();
} }
@ -1535,9 +1578,10 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
old = getDaoProfileSwitch().queryForId(profileSwitch.date); old = getDaoProfileSwitch().queryForId(profileSwitch.date);
if (old != null) { if (old != null) {
if (!old.isEqual(profileSwitch)) { if (!old.isEqual(profileSwitch)) {
profileSwitch.source = old.source;
profileSwitch.profileName = old.profileName; // preserver profileName to prevent multiple CPP extension
getDaoProfileSwitch().delete(old); // need to delete/create because date may change too getDaoProfileSwitch().delete(old); // need to delete/create because date may change too
old.copyFrom(profileSwitch); getDaoProfileSwitch().create(profileSwitch);
getDaoProfileSwitch().create(old);
log.debug("PROFILESWITCH: Updating record by date from: " + Source.getString(profileSwitch.source) + " " + old.toString()); log.debug("PROFILESWITCH: Updating record by date from: " + Source.getString(profileSwitch.source) + " " + old.toString());
scheduleProfileSwitchChange(); scheduleProfileSwitchChange();
return true; return true;
@ -1575,7 +1619,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
return true; return true;
} }
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
return false; return false;
} }
@ -1585,7 +1629,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
getDaoProfileSwitch().delete(profileSwitch); getDaoProfileSwitch().delete(profileSwitch);
scheduleProfileSwitchChange(); scheduleProfileSwitchChange();
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
} }
@ -1640,7 +1684,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
profileSwitch.profilePlugin = trJson.getString("profilePlugin"); profileSwitch.profilePlugin = trJson.getString("profilePlugin");
createOrUpdate(profileSwitch); createOrUpdate(profileSwitch);
} catch (JSONException e) { } catch (JSONException e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
} }
@ -1667,9 +1711,10 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
return null; return null;
} }
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
return null; return null;
} }
// ---------------- Food handling ---------------
} }

View file

@ -77,7 +77,7 @@ public class DbRequest {
if (_id != null) object.put("_id", _id); if (_id != null) object.put("_id", _id);
if (nsClientID != null) object.put("nsClientID", nsClientID); if (nsClientID != null) object.put("nsClientID", nsClientID);
} catch (JSONException e) { } catch (JSONException e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
return object; return object;
} }
@ -96,7 +96,7 @@ public class DbRequest {
if (jsonObject.has("nsClientID")) if (jsonObject.has("nsClientID"))
result.nsClientID = jsonObject.getString("nsClientID"); result.nsClientID = jsonObject.getString("nsClientID");
} catch (JSONException e) { } catch (JSONException e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
return result; return result;
} }

View file

@ -0,0 +1,107 @@
package info.nightscout.androidaps.db;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Objects;
/**
* Created by mike on 20.09.2017.
*/
@DatabaseTable(tableName = DatabaseHelper.DATABASE_FOODS)
public class Food {
private static Logger log = LoggerFactory.getLogger(Food.class);
@DatabaseField(id = true)
public long key;
@DatabaseField
public boolean isValid = true;
@DatabaseField
public String _id; // NS _id
@DatabaseField
public String name;
@DatabaseField
public String category;
@DatabaseField
public String subcategory;
// Example:
// name="juice" portion=250 units="ml" carbs=12
// means 250ml of juice has 12g of carbs
@DatabaseField
public double portion; // common portion in "units"
@DatabaseField
public int carbs; // in grams
@DatabaseField
public int fat = 0; // in grams
@DatabaseField
public int protein = 0; // in grams
@DatabaseField
public int energy = 0; // in kJ
@DatabaseField
public String units = "g";
@DatabaseField
public int gi; // not used yet
public Food() {
key = System.currentTimeMillis();
}
public boolean isEqual(Food other) {
if (portion != other.portion)
return false;
if (carbs != other.carbs)
return false;
if (fat != other.fat)
return false;
if (protein != other.protein)
return false;
if (energy != other.energy)
return false;
if (gi != other.gi)
return false;
if (!Objects.equals(_id, other._id))
return false;
if (!Objects.equals(name, other.name))
return false;
if (!Objects.equals(category, other.category))
return false;
if (!Objects.equals(subcategory, other.subcategory))
return false;
if (!Objects.equals(units, other.units))
return false;
return true;
}
public void copyFrom(Food other) {
isValid = other.isValid;
_id = other._id;
name = other.name;
category = other.category;
subcategory = other.subcategory;
portion = other.portion;
carbs = other.carbs;
fat = other.fat;
protein = other.protein;
energy = other.energy;
units = other.units;
gi = other.gi;
}
}

View file

@ -0,0 +1,207 @@
package info.nightscout.androidaps.db;
import com.j256.ormlite.android.AndroidConnectionSource;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.stmt.PreparedQuery;
import com.j256.ormlite.stmt.QueryBuilder;
import com.j256.ormlite.stmt.Where;
import com.j256.ormlite.table.TableUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.events.EventFoodDatabaseChanged;
/**
* Created by mike on 24.09.2017.
*/
public class FoodHelper {
private static Logger log = LoggerFactory.getLogger(FoodHelper.class);
DatabaseHelper databaseHelper;
private static final ScheduledExecutorService foodEventWorker = Executors.newSingleThreadScheduledExecutor();
private static ScheduledFuture<?> scheduledFoodEventPost = null;
public FoodHelper(DatabaseHelper databaseHelper) {
this.databaseHelper = databaseHelper;
}
private Dao<Food, Long> getDaoFood() throws SQLException {
return databaseHelper.getDao(Food.class);
}
public void resetFood() {
try {
TableUtils.dropTable(databaseHelper.getConnectionSource(), Food.class, true);
TableUtils.createTableIfNotExists(databaseHelper.getConnectionSource(), Food.class);
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
scheduleFoodChange();
}
public List<Food> getFoodData() {
try {
Dao<Food, Long> daoFood = getDaoFood();
List<Food> foods;
QueryBuilder<Food, Long> queryBuilder = daoFood.queryBuilder();
PreparedQuery<Food> preparedQuery = queryBuilder.prepare();
foods = daoFood.query(preparedQuery);
return foods;
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return new ArrayList<>();
}
public boolean createOrUpdate(Food food) {
try {
// find by NS _id
if (food._id != null) {
Food old;
QueryBuilder<Food, Long> queryBuilder = getDaoFood().queryBuilder();
Where where = queryBuilder.where();
where.eq("_id", food._id);
PreparedQuery<Food> preparedQuery = queryBuilder.prepare();
List<Food> found = getDaoFood().query(preparedQuery);
if (found.size() > 0) {
old = found.get(0);
if (!old.isEqual(food)) {
getDaoFood().delete(old); // need to delete/create because date may change too
old.copyFrom(food);
getDaoFood().create(old);
log.debug("FOOD: Updating record by _id: " + old.toString());
scheduleFoodChange();
return true;
} else {
return false;
}
}
}
getDaoFood().createOrUpdate(food);
log.debug("FOOD: New record: " + food.toString());
scheduleFoodChange();
return true;
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return false;
}
public void delete(Food food) {
try {
getDaoFood().delete(food);
scheduleFoodChange();
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
}
public static void scheduleFoodChange() {
class PostRunnable implements Runnable {
public void run() {
log.debug("Firing EventFoodChange");
MainApp.bus().post(new EventFoodDatabaseChanged());
scheduledFoodEventPost = null;
}
}
// prepare task for execution in 1 sec
// cancel waiting task to prevent sending multiple posts
if (scheduledFoodEventPost != null)
scheduledFoodEventPost.cancel(false);
Runnable task = new PostRunnable();
final int sec = 1;
scheduledFoodEventPost = foodEventWorker.schedule(task, sec, TimeUnit.SECONDS);
}
/*
{
"_id": "551ee3ad368e06e80856e6a9",
"type": "food",
"category": "Zakladni",
"subcategory": "Napoje",
"name": "Mleko",
"portion": 250,
"carbs": 12,
"gi": 1,
"created_at": "2015-04-14T06:59:16.500Z",
"unit": "ml"
}
*/
public void createFoodFromJsonIfNotExists(JSONObject trJson) {
try {
Food food = new Food();
if (trJson.has("type") && trJson.getString("type").equals("food")) {
if (trJson.has("_id"))
food._id = trJson.getString("_id");
if (trJson.has("category"))
food.category = trJson.getString("category");
if (trJson.has("subcategory"))
food.subcategory = trJson.getString("subcategory");
if (trJson.has("name"))
food.name = trJson.getString("name");
if (trJson.has("unit"))
food.units = trJson.getString("unit");
if (trJson.has("portion"))
food.portion = trJson.getDouble("portion");
if (trJson.has("carbs"))
food.carbs = trJson.getInt("carbs");
if (trJson.has("gi"))
food.gi = trJson.getInt("gi");
if (trJson.has("energy"))
food.energy = trJson.getInt("energy");
if (trJson.has("protein"))
food.protein = trJson.getInt("protein");
if (trJson.has("fat"))
food.fat = trJson.getInt("fat");
}
createOrUpdate(food);
} catch (JSONException e) {
log.error("Unhandled exception", e);
}
}
public void deleteFoodById(String _id) {
Food stored = findFoodById(_id);
if (stored != null) {
log.debug("FOOD: Removing Food record from database: " + stored.toString());
delete(stored);
scheduleFoodChange();
}
}
public Food findFoodById(String _id) {
try {
QueryBuilder<Food, Long> queryBuilder = getDaoFood().queryBuilder();
Where where = queryBuilder.where();
where.eq("_id", _id);
PreparedQuery<Food> preparedQuery = queryBuilder.prepare();
List<Food> list = getDaoFood().query(preparedQuery);
if (list.size() == 1) {
return list.get(0);
} else {
return null;
}
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return null;
}
}

View file

@ -10,14 +10,15 @@ import org.json.JSONObject;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.util.Date;
import java.util.Objects; import java.util.Objects;
import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.interfaces.Interval; import info.nightscout.androidaps.interfaces.Interval;
import info.nightscout.androidaps.plugins.Overview.graphExtensions.DataPointWithLabelInterface; import info.nightscout.androidaps.plugins.Overview.graphExtensions.DataPointWithLabelInterface;
import info.nightscout.androidaps.plugins.Overview.graphExtensions.PointsWithLabelGraphSeries; import info.nightscout.androidaps.plugins.Overview.graphExtensions.PointsWithLabelGraphSeries;
import info.nightscout.androidaps.plugins.ProfileLocal.LocalProfilePlugin;
import info.nightscout.utils.DateUtil; import info.nightscout.utils.DateUtil;
import info.nightscout.utils.DecimalFormatter;
@DatabaseTable(tableName = DatabaseHelper.DATABASE_PROFILESWITCHES) @DatabaseTable(tableName = DatabaseHelper.DATABASE_PROFILESWITCHES)
public class ProfileSwitch implements Interval, DataPointWithLabelInterface { public class ProfileSwitch implements Interval, DataPointWithLabelInterface {
@ -58,13 +59,27 @@ public class ProfileSwitch implements Interval, DataPointWithLabelInterface {
public Profile getProfileObject() { public Profile getProfileObject() {
if (profile == null) if (profile == null)
try { try {
profile = new Profile(new JSONObject(profileJson)); profile = new Profile(new JSONObject(profileJson), percentage, timeshift);
} catch (JSONException e) { } catch (JSONException e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
return profile; return profile;
} }
public String getCustomizedName() {
String name = profileName;
if(LocalProfilePlugin.LOCAL_PROFILE.equals(name)){
name = DecimalFormatter.to2Decimal(getProfileObject().percentageBasalSum()) + "U ";
}
if (isCPP) {
name += "(" + percentage + "%";
if (timeshift != 0)
name += "," + timeshift + "h";
name += ")";
}
return name;
}
public boolean isEqual(ProfileSwitch other) { public boolean isEqual(ProfileSwitch other) {
if (date != other.date) { if (date != other.date) {
return false; return false;
@ -179,7 +194,7 @@ public class ProfileSwitch implements Interval, DataPointWithLabelInterface {
@Override @Override
public String getLabel() { public String getLabel() {
return profileName; return getCustomizedName();
} }
@Override @Override

View file

@ -0,0 +1,16 @@
package info.nightscout.androidaps.events;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
/** Base class for all events posted on the event bus. */
public abstract class Event {
static {
ReflectionToStringBuilder.setDefaultStyle(ToStringStyle.SHORT_PREFIX_STYLE);
}
@Override
public String toString() {
return ReflectionToStringBuilder.toString(this);
}
}

View file

@ -3,5 +3,5 @@ package info.nightscout.androidaps.events;
/** /**
* Created by mike on 07.07.2016. * Created by mike on 07.07.2016.
*/ */
public class EventAppExit { public class EventAppExit extends Event {
} }

View file

@ -4,7 +4,7 @@ package info.nightscout.androidaps.events;
* Created by adrian on 07/02/17. * Created by adrian on 07/02/17.
*/ */
public class EventBolusRequested { public class EventBolusRequested extends Event {
private double amount; private double amount;
public EventBolusRequested (double amount){ public EventBolusRequested (double amount){

View file

@ -4,5 +4,5 @@ package info.nightscout.androidaps.events;
* Created by mike on 25.05.2017. * Created by mike on 25.05.2017.
*/ */
public class EventCareportalEventChange { public class EventCareportalEventChange extends Event {
} }

View file

@ -4,5 +4,5 @@ package info.nightscout.androidaps.events;
* Created by mike on 17.02.2017. * Created by mike on 17.02.2017.
*/ */
public class EventConfigBuilderChange { public class EventConfigBuilderChange extends Event {
} }

View file

@ -4,5 +4,5 @@ package info.nightscout.androidaps.events;
* Created by mike on 15.05.2017. * Created by mike on 15.05.2017.
*/ */
public class EventExtendedBolusChange { public class EventExtendedBolusChange extends Event {
} }

View file

@ -0,0 +1,8 @@
package info.nightscout.androidaps.events;
/**
* Created by mike on 20.09.2017.
*/
public class EventFoodDatabaseChanged extends Event {
}

View file

@ -4,5 +4,5 @@ package info.nightscout.androidaps.events;
* Created by mike on 13.12.2016. * Created by mike on 13.12.2016.
*/ */
public class EventInitializationChanged { public class EventInitializationChanged extends Event {
} }

View file

@ -0,0 +1,5 @@
package info.nightscout.androidaps.events;
/** Supeclass for all events concerned with input or output into or from the LoopPlugin. */
public abstract class EventLoop extends Event {
}

View file

@ -3,5 +3,5 @@ package info.nightscout.androidaps.events;
/** /**
* Created by mike on 05.06.2016. * Created by mike on 05.06.2016.
*/ */
public class EventNewBG { public class EventNewBG extends EventLoop {
} }

View file

@ -3,5 +3,5 @@ package info.nightscout.androidaps.events;
/** /**
* Created by mike on 04.06.2016. * Created by mike on 04.06.2016.
*/ */
public class EventNewBasalProfile { public class EventNewBasalProfile extends Event {
} }

View file

@ -5,7 +5,7 @@ import info.nightscout.androidaps.MainApp;
/** /**
* Created by mike on 19.06.2016. * Created by mike on 19.06.2016.
*/ */
public class EventPreferenceChange { public class EventPreferenceChange extends Event {
public String changedKey; public String changedKey;
public EventPreferenceChange(String key) { public EventPreferenceChange(String key) {
changedKey = key; changedKey = key;

View file

@ -4,5 +4,5 @@ package info.nightscout.androidaps.events;
* Created by mike on 02.06.2017. * Created by mike on 02.06.2017.
*/ */
public class EventProfileSwitchChange { public class EventProfileSwitchChange extends Event {
} }

View file

@ -7,7 +7,7 @@ import info.nightscout.androidaps.R;
* Created by mike on 19.02.2017. * Created by mike on 19.02.2017.
*/ */
public class EventPumpStatusChanged { public class EventPumpStatusChanged extends Event {
public static final int CONNECTING = 0; public static final int CONNECTING = 0;
public static final int CONNECTED = 1; public static final int CONNECTED = 1;
public static final int PERFORMING = 2; public static final int PERFORMING = 2;
@ -18,14 +18,24 @@ public class EventPumpStatusChanged {
public int sSecondsElapsed = 0; public int sSecondsElapsed = 0;
public String sPerfomingAction = ""; public String sPerfomingAction = "";
public static String error = "";
public EventPumpStatusChanged(int status) { public EventPumpStatusChanged(int status) {
sStatus = status; sStatus = status;
sSecondsElapsed = 0; sSecondsElapsed = 0;
error = "";
} }
public EventPumpStatusChanged(int status, int secondsElapsed) { public EventPumpStatusChanged(int status, int secondsElapsed) {
sStatus = status; sStatus = status;
sSecondsElapsed = secondsElapsed; sSecondsElapsed = secondsElapsed;
error = "";
}
public EventPumpStatusChanged(int status, String error) {
sStatus = status;
sSecondsElapsed = 0;
this.error = error;
} }
public EventPumpStatusChanged(String action) { public EventPumpStatusChanged(String action) {

View file

@ -3,5 +3,5 @@ package info.nightscout.androidaps.events;
/** /**
* Created by mike on 13.06.2016. * Created by mike on 13.06.2016.
*/ */
public class EventRefreshGui { public class EventRefreshGui extends Event {
} }

View file

@ -4,7 +4,7 @@ package info.nightscout.androidaps.events;
* Created by mike on 16.06.2017. * Created by mike on 16.06.2017.
*/ */
public class EventRefreshOverview { public class EventRefreshOverview extends Event {
public String from; public String from;
public EventRefreshOverview(String from) { public EventRefreshOverview(String from) {

View file

@ -4,5 +4,5 @@ package info.nightscout.androidaps.events;
* Created by mike on 12.06.2017. * Created by mike on 12.06.2017.
*/ */
public class EventReloadProfileSwitchData { public class EventReloadProfileSwitchData extends Event {
} }

View file

@ -4,5 +4,5 @@ package info.nightscout.androidaps.events;
* Created by mike on 29.05.2017. * Created by mike on 29.05.2017.
*/ */
public class EventReloadTempBasalData { public class EventReloadTempBasalData extends Event {
} }

View file

@ -4,5 +4,10 @@ package info.nightscout.androidaps.events;
* Created by mike on 29.05.2017. * Created by mike on 29.05.2017.
*/ */
public class EventReloadTreatmentData { public class EventReloadTreatmentData extends Event {
public Object next;
public EventReloadTreatmentData(Object next) {
this.next = next;
}
} }

View file

@ -3,5 +3,5 @@ package info.nightscout.androidaps.events;
/** /**
* Created by mike on 05.06.2016. * Created by mike on 05.06.2016.
*/ */
public class EventTempBasalChange { public class EventTempBasalChange extends EventLoop {
} }

View file

@ -4,5 +4,5 @@ package info.nightscout.androidaps.events;
* Created by mike on 13.01.2017. * Created by mike on 13.01.2017.
*/ */
public class EventTempTargetChange { public class EventTempTargetChange extends Event {
} }

View file

@ -3,5 +3,5 @@ package info.nightscout.androidaps.events;
/** /**
* Created by mike on 04.06.2016. * Created by mike on 04.06.2016.
*/ */
public class EventTreatmentChange { public class EventTreatmentChange extends EventLoop {
} }

View file

@ -0,0 +1,5 @@
package info.nightscout.androidaps.events;
/** Base class for events to update the UI, mostly a specific tab. */
public abstract class EventUpdateGui extends Event {
}

View file

@ -1,9 +1,12 @@
package info.nightscout.androidaps.interfaces; package info.nightscout.androidaps.interfaces;
import info.nightscout.androidaps.data.PumpEnactResult;
/** /**
* Created by mike on 12.06.2017. * Created by mike on 12.06.2017.
*/ */
public interface DanaRInterface { public interface DanaRInterface {
boolean loadHistory(byte type); PumpEnactResult loadHistory(byte type); // for history browser
PumpEnactResult loadEvents(); // events history to build treatments from
} }

View file

@ -30,4 +30,5 @@ public interface PluginBase {
boolean showInList(int type); boolean showInList(int type);
void setFragmentEnabled(int type, boolean fragmentEnabled); void setFragmentEnabled(int type, boolean fragmentEnabled);
void setFragmentVisible(int type, boolean fragmentVisible); void setFragmentVisible(int type, boolean fragmentVisible);
int getPreferencesId();
} }

View file

@ -1,5 +1,7 @@
package info.nightscout.androidaps.interfaces; package info.nightscout.androidaps.interfaces;
import android.support.annotation.NonNull;
import org.json.JSONObject; import org.json.JSONObject;
import java.util.Date; import java.util.Date;
@ -16,27 +18,31 @@ public interface PumpInterface {
boolean isInitialized(); boolean isInitialized();
boolean isSuspended(); boolean isSuspended();
boolean isBusy(); boolean isBusy();
boolean isConnected();
boolean isConnecting();
void connect(String reason);
void disconnect(String reason);
void stopConnecting();
void getPumpStatus();
// Upload to pump new basal profile // Upload to pump new basal profile
int SUCCESS = 0; PumpEnactResult setNewBasalProfile(Profile profile);
int FAILED = 1;
int NOT_NEEDED = 2;
int setNewBasalProfile(Profile profile);
boolean isThisProfileSet(Profile profile); boolean isThisProfileSet(Profile profile);
Date lastDataTime(); Date lastDataTime();
void refreshDataFromPump(String reason);
double getBaseBasalRate(); // base basal rate, not temp basal double getBaseBasalRate(); // base basal rate, not temp basal
PumpEnactResult deliverTreatment(DetailedBolusInfo detailedBolusInfo); PumpEnactResult deliverTreatment(DetailedBolusInfo detailedBolusInfo);
void stopBolusDelivering(); void stopBolusDelivering();
PumpEnactResult setTempBasalAbsolute(Double absoluteRate, Integer durationInMinutes, boolean force); PumpEnactResult setTempBasalAbsolute(Double absoluteRate, Integer durationInMinutes, boolean enforceNew);
PumpEnactResult setTempBasalPercent(Integer percent, Integer durationInMinutes); PumpEnactResult setTempBasalPercent(Integer percent, Integer durationInMinutes);
PumpEnactResult setExtendedBolus(Double insulin, Integer durationInMinutes); PumpEnactResult setExtendedBolus(Double insulin, Integer durationInMinutes);
//some pumps might set a very short temp close to 100% as cancelling a temp can be noisy //some pumps might set a very short temp close to 100% as cancelling a temp can be noisy
//when the cancel request is requested by the user (forced), the pump should always do a real cancel //when the cancel request is requested by the user (forced), the pump should always do a real cancel
PumpEnactResult cancelTempBasal(boolean force); PumpEnactResult cancelTempBasal(boolean enforceNew);
PumpEnactResult cancelExtendedBolus(); PumpEnactResult cancelExtendedBolus();
// Status to be passed to NS // Status to be passed to NS

View file

@ -52,6 +52,7 @@ public interface TreatmentsInterface {
boolean addToHistoryTreatment(DetailedBolusInfo detailedBolusInfo); boolean addToHistoryTreatment(DetailedBolusInfo detailedBolusInfo);
TempTarget getTempTargetFromHistory();
TempTarget getTempTargetFromHistory(long time); TempTarget getTempTargetFromHistory(long time);
Intervals<TempTarget> getTempTargetsFromHistory(); Intervals<TempTarget> getTempTargetsFromHistory();

View file

@ -3,8 +3,6 @@ package info.nightscout.androidaps.plugins.Actions;
import android.app.Activity; import android.app.Activity;
import android.os.Bundle; import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.support.v4.app.Fragment; import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentManager;
import android.view.LayoutInflater; import android.view.LayoutInflater;
@ -12,6 +10,7 @@ import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
import android.widget.Button; import android.widget.Button;
import com.crashlytics.android.Crashlytics;
import com.crashlytics.android.answers.Answers; import com.crashlytics.android.answers.Answers;
import com.crashlytics.android.answers.CustomEvent; import com.crashlytics.android.answers.CustomEvent;
import com.squareup.otto.Subscribe; import com.squareup.otto.Subscribe;
@ -33,6 +32,7 @@ import info.nightscout.androidaps.plugins.Careportal.CareportalFragment;
import info.nightscout.androidaps.plugins.Careportal.Dialogs.NewNSTreatmentDialog; import info.nightscout.androidaps.plugins.Careportal.Dialogs.NewNSTreatmentDialog;
import info.nightscout.androidaps.plugins.Careportal.OptionsToShow; import info.nightscout.androidaps.plugins.Careportal.OptionsToShow;
import info.nightscout.androidaps.plugins.Common.SubscriberFragment; import info.nightscout.androidaps.plugins.Common.SubscriberFragment;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
/** /**
* A simple {@link Fragment} subclass. * A simple {@link Fragment} subclass.
@ -53,42 +53,40 @@ public class ActionsFragment extends SubscriberFragment implements View.OnClickL
Button tempBasalCancel; Button tempBasalCancel;
Button fill; Button fill;
private static Handler sHandler;
private static HandlerThread sHandlerThread;
public ActionsFragment() { public ActionsFragment() {
super(); super();
if (sHandlerThread == null) {
sHandlerThread = new HandlerThread(ActionsFragment.class.getSimpleName());
sHandlerThread.start();
sHandler = new Handler(sHandlerThread.getLooper());
}
} }
@Override @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) { Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.actions_fragment, container, false); try {
View view = inflater.inflate(R.layout.actions_fragment, container, false);
profileSwitch = (Button) view.findViewById(R.id.actions_profileswitch); profileSwitch = (Button) view.findViewById(R.id.actions_profileswitch);
tempTarget = (Button) view.findViewById(R.id.actions_temptarget); tempTarget = (Button) view.findViewById(R.id.actions_temptarget);
extendedBolus = (Button) view.findViewById(R.id.actions_extendedbolus); extendedBolus = (Button) view.findViewById(R.id.actions_extendedbolus);
extendedBolusCancel = (Button) view.findViewById(R.id.actions_extendedbolus_cancel); extendedBolusCancel = (Button) view.findViewById(R.id.actions_extendedbolus_cancel);
tempBasal = (Button) view.findViewById(R.id.actions_settempbasal); tempBasal = (Button) view.findViewById(R.id.actions_settempbasal);
tempBasalCancel = (Button) view.findViewById(R.id.actions_canceltempbasal); tempBasalCancel = (Button) view.findViewById(R.id.actions_canceltempbasal);
fill = (Button) view.findViewById(R.id.actions_fill); fill = (Button) view.findViewById(R.id.actions_fill);
profileSwitch.setOnClickListener(this); profileSwitch.setOnClickListener(this);
tempTarget.setOnClickListener(this); tempTarget.setOnClickListener(this);
extendedBolus.setOnClickListener(this); extendedBolus.setOnClickListener(this);
extendedBolusCancel.setOnClickListener(this); extendedBolusCancel.setOnClickListener(this);
tempBasal.setOnClickListener(this); tempBasal.setOnClickListener(this);
tempBasalCancel.setOnClickListener(this); tempBasalCancel.setOnClickListener(this);
fill.setOnClickListener(this); fill.setOnClickListener(this);
updateGUI(); updateGUI();
return view; return view;
} catch (Exception e) {
Crashlytics.logException(e);
}
return null;
} }
@Subscribe @Subscribe
@ -128,14 +126,15 @@ public class ActionsFragment extends SubscriberFragment implements View.OnClickL
fill.setVisibility(View.GONE); fill.setVisibility(View.GONE);
return; return;
} }
final PumpInterface pump = ConfigBuilderPlugin.getActivePump();
boolean allowProfileSwitch = MainApp.getConfigBuilder().getActiveProfileInterface().getProfile().getProfileList().size() > 1; boolean allowProfileSwitch = MainApp.getConfigBuilder().getActiveProfileInterface().getProfile().getProfileList().size() > 1;
if (!MainApp.getConfigBuilder().getPumpDescription().isSetBasalProfileCapable || !MainApp.getConfigBuilder().isInitialized() || MainApp.getConfigBuilder().isSuspended() || !allowProfileSwitch) if (!pump.getPumpDescription().isSetBasalProfileCapable || !pump.isInitialized() || pump.isSuspended() || !allowProfileSwitch)
profileSwitch.setVisibility(View.GONE); profileSwitch.setVisibility(View.GONE);
else else
profileSwitch.setVisibility(View.VISIBLE); profileSwitch.setVisibility(View.VISIBLE);
if (!MainApp.getConfigBuilder().getPumpDescription().isExtendedBolusCapable || !MainApp.getConfigBuilder().isInitialized() || MainApp.getConfigBuilder().isSuspended() || MainApp.getConfigBuilder().isFakingTempsByExtendedBoluses()) { if (!pump.getPumpDescription().isExtendedBolusCapable || !pump.isInitialized() || pump.isSuspended() || pump.isFakingTempsByExtendedBoluses()) {
extendedBolus.setVisibility(View.GONE); extendedBolus.setVisibility(View.GONE);
extendedBolusCancel.setVisibility(View.GONE); extendedBolusCancel.setVisibility(View.GONE);
} else { } else {
@ -151,7 +150,7 @@ public class ActionsFragment extends SubscriberFragment implements View.OnClickL
} }
if (!MainApp.getConfigBuilder().getPumpDescription().isTempBasalCapable || !MainApp.getConfigBuilder().isInitialized() || MainApp.getConfigBuilder().isSuspended()) { if (!pump.getPumpDescription().isTempBasalCapable || !pump.isInitialized() || pump.isSuspended()) {
tempBasal.setVisibility(View.GONE); tempBasal.setVisibility(View.GONE);
tempBasalCancel.setVisibility(View.GONE); tempBasalCancel.setVisibility(View.GONE);
} else { } else {
@ -159,14 +158,14 @@ public class ActionsFragment extends SubscriberFragment implements View.OnClickL
tempBasal.setVisibility(View.GONE); tempBasal.setVisibility(View.GONE);
tempBasalCancel.setVisibility(View.VISIBLE); tempBasalCancel.setVisibility(View.VISIBLE);
final TemporaryBasal activeTemp = MainApp.getConfigBuilder().getTempBasalFromHistory(System.currentTimeMillis()); final TemporaryBasal activeTemp = MainApp.getConfigBuilder().getTempBasalFromHistory(System.currentTimeMillis());
tempBasalCancel.setText(MainApp.instance().getString(R.string.cancel) + "\n" + activeTemp.toStringShort()); tempBasalCancel.setText(MainApp.instance().getString(R.string.cancel) + " " + activeTemp.toStringShort());
} else { } else {
tempBasal.setVisibility(View.VISIBLE); tempBasal.setVisibility(View.VISIBLE);
tempBasalCancel.setVisibility(View.GONE); tempBasalCancel.setVisibility(View.GONE);
} }
} }
if (!MainApp.getConfigBuilder().getPumpDescription().isRefillingCapable || !MainApp.getConfigBuilder().isInitialized() || MainApp.getConfigBuilder().isSuspended()) if (!pump.getPumpDescription().isRefillingCapable || !pump.isInitialized() || pump.isSuspended())
fill.setVisibility(View.GONE); fill.setVisibility(View.GONE);
else else
fill.setVisibility(View.VISIBLE); fill.setVisibility(View.VISIBLE);
@ -183,18 +182,17 @@ public class ActionsFragment extends SubscriberFragment implements View.OnClickL
@Override @Override
public void onClick(View view) { public void onClick(View view) {
FragmentManager manager = getFragmentManager(); FragmentManager manager = getFragmentManager();
final PumpInterface pump = MainApp.getConfigBuilder();
switch (view.getId()) { switch (view.getId()) {
case R.id.actions_profileswitch: case R.id.actions_profileswitch:
NewNSTreatmentDialog newDialog = new NewNSTreatmentDialog(); NewNSTreatmentDialog newDialog = new NewNSTreatmentDialog();
final OptionsToShow profileswitch = CareportalFragment.profileswitch; final OptionsToShow profileswitch = CareportalFragment.PROFILESWITCH;
profileswitch.executeProfileSwitch = true; profileswitch.executeProfileSwitch = true;
newDialog.setOptions(profileswitch, R.string.careportal_profileswitch); newDialog.setOptions(profileswitch, R.string.careportal_profileswitch);
newDialog.show(manager, "NewNSTreatmentDialog"); newDialog.show(manager, "NewNSTreatmentDialog");
break; break;
case R.id.actions_temptarget: case R.id.actions_temptarget:
NewNSTreatmentDialog newTTDialog = new NewNSTreatmentDialog(); NewNSTreatmentDialog newTTDialog = new NewNSTreatmentDialog();
final OptionsToShow temptarget = CareportalFragment.temptarget; final OptionsToShow temptarget = CareportalFragment.TEMPTARGET;
temptarget.executeTempTarget = true; temptarget.executeTempTarget = true;
newTTDialog.setOptions(temptarget, R.string.careportal_temporarytarget); newTTDialog.setOptions(temptarget, R.string.careportal_temporarytarget);
newTTDialog.show(manager, "NewNSTreatmentDialog"); newTTDialog.show(manager, "NewNSTreatmentDialog");
@ -205,24 +203,14 @@ public class ActionsFragment extends SubscriberFragment implements View.OnClickL
break; break;
case R.id.actions_extendedbolus_cancel: case R.id.actions_extendedbolus_cancel:
if (MainApp.getConfigBuilder().isInHistoryExtendedBoluslInProgress()) { if (MainApp.getConfigBuilder().isInHistoryExtendedBoluslInProgress()) {
sHandler.post(new Runnable() { ConfigBuilderPlugin.getCommandQueue().cancelExtended(null);
@Override Answers.getInstance().logCustom(new CustomEvent("CancelExtended"));
public void run() {
pump.cancelExtendedBolus();
Answers.getInstance().logCustom(new CustomEvent("CancelExtended"));
}
});
} }
break; break;
case R.id.actions_canceltempbasal: case R.id.actions_canceltempbasal:
if (MainApp.getConfigBuilder().isTempBasalInProgress()) { if (MainApp.getConfigBuilder().isTempBasalInProgress()) {
sHandler.post(new Runnable() { ConfigBuilderPlugin.getCommandQueue().cancelTempBasal(true, null);
@Override Answers.getInstance().logCustom(new CustomEvent("CancelTemp"));
public void run() {
pump.cancelTempBasal(true);
Answers.getInstance().logCustom(new CustomEvent("CancelTemp"));
}
});
} }
break; break;
case R.id.actions_settempbasal: case R.id.actions_settempbasal:

View file

@ -10,8 +10,8 @@ import info.nightscout.androidaps.interfaces.PluginBase;
public class ActionsPlugin implements PluginBase { public class ActionsPlugin implements PluginBase {
boolean fragmentEnabled = true; private boolean fragmentEnabled = true;
boolean fragmentVisible = true; private boolean fragmentVisible = true;
@Override @Override
public int getType() { public int getType() {
@ -74,4 +74,9 @@ public class ActionsPlugin implements PluginBase {
if (type == GENERAL) this.fragmentVisible = fragmentVisible; if (type == GENERAL) this.fragmentVisible = fragmentVisible;
} }
@Override
public int getPreferencesId() {
return -1;
}
} }

View file

@ -2,11 +2,8 @@ package info.nightscout.androidaps.plugins.Actions.dialogs;
import android.content.Context; import android.content.Context;
import android.content.DialogInterface; import android.content.DialogInterface;
import android.content.SharedPreferences; import android.content.Intent;
import android.os.Bundle; import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.preference.PreferenceManager;
import android.support.v4.app.DialogFragment; import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog; import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater; import android.view.LayoutInflater;
@ -16,44 +13,40 @@ import android.view.ViewGroup;
import android.view.Window; import android.view.Window;
import android.view.WindowManager; import android.view.WindowManager;
import android.widget.Button; import android.widget.Button;
import android.widget.TextView;
import com.crashlytics.android.answers.Answers; import com.crashlytics.android.answers.Answers;
import com.crashlytics.android.answers.CustomEvent; import com.crashlytics.android.answers.CustomEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.text.DecimalFormat; import java.text.DecimalFormat;
import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.DetailedBolusInfo; import info.nightscout.androidaps.data.DetailedBolusInfo;
import info.nightscout.androidaps.data.PumpEnactResult;
import info.nightscout.androidaps.db.Source; import info.nightscout.androidaps.db.Source;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.Overview.Dialogs.ErrorHelperActivity;
import info.nightscout.androidaps.queue.Callback;
import info.nightscout.utils.DecimalFormatter; import info.nightscout.utils.DecimalFormatter;
import info.nightscout.utils.PlusMinusEditText; import info.nightscout.utils.NumberPicker;
import info.nightscout.utils.SP; import info.nightscout.utils.SP;
import info.nightscout.utils.SafeParse; import info.nightscout.utils.SafeParse;
public class FillDialog extends DialogFragment implements OnClickListener { public class FillDialog extends DialogFragment implements OnClickListener {
private static Logger log = LoggerFactory.getLogger(FillDialog.class);
Button deliverButton; Button deliverButton;
TextView insulin;
double amount1 = 0d; double amount1 = 0d;
double amount2 = 0d; double amount2 = 0d;
double amount3 = 0d; double amount3 = 0d;
PlusMinusEditText editInsulin; NumberPicker editInsulin;
Handler mHandler;
public static HandlerThread mHandlerThread;
public FillDialog() { public FillDialog() {
mHandlerThread = new HandlerThread(FillDialog.class.getSimpleName());
mHandlerThread.start();
this.mHandler = new Handler(mHandlerThread.getLooper());
} }
@Override @Override
@ -67,10 +60,10 @@ public class FillDialog extends DialogFragment implements OnClickListener {
getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE); getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN); getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
insulin = (TextView) view.findViewById(R.id.treatments_newtreatment_insulinamount);
Double maxInsulin = MainApp.getConfigBuilder().applyBolusConstraints(Constants.bolusOnlyForCheckLimit); Double maxInsulin = MainApp.getConfigBuilder().applyBolusConstraints(Constants.bolusOnlyForCheckLimit);
double bolusstep = MainApp.getConfigBuilder().getPumpDescription().bolusStep; double bolusstep = ConfigBuilderPlugin.getActivePump().getPumpDescription().bolusStep;
editInsulin = new PlusMinusEditText(view, R.id.treatments_newtreatment_insulinamount, R.id.treatments_newtreatment_insulinamount_plus, R.id.treatments_newtreatment_insulinamount_minus, 0d, 0d, maxInsulin, bolusstep, new DecimalFormat("0.00"), false); editInsulin = (NumberPicker) view.findViewById(R.id.treatments_newtreatment_insulinamount);
editInsulin.setParams(0d, 0d, maxInsulin, bolusstep, new DecimalFormat("0.00"), false);
//setup preset buttons //setup preset buttons
Button button1 = (Button) view.findViewById(R.id.fill_preset_button1); Button button1 = (Button) view.findViewById(R.id.fill_preset_button1);
@ -82,21 +75,21 @@ public class FillDialog extends DialogFragment implements OnClickListener {
amount2 = SP.getDouble("fill_button2", 0d); amount2 = SP.getDouble("fill_button2", 0d);
amount3 = SP.getDouble("fill_button3", 0d); amount3 = SP.getDouble("fill_button3", 0d);
if(amount1 >0) { if (amount1 > 0) {
button1.setVisibility(View.VISIBLE); button1.setVisibility(View.VISIBLE);
button1.setText(DecimalFormatter.to2Decimal(amount1) + "U"); button1.setText(DecimalFormatter.to2Decimal(amount1) + "U");
button1.setOnClickListener(this); button1.setOnClickListener(this);
} else { } else {
button1.setVisibility(View.GONE); button1.setVisibility(View.GONE);
} }
if(amount2 >0) { if (amount2 > 0) {
button2.setVisibility(View.VISIBLE); button2.setVisibility(View.VISIBLE);
button2.setText(DecimalFormatter.to2Decimal(amount2) + "U"); button2.setText(DecimalFormatter.to2Decimal(amount2) + "U");
button2.setOnClickListener(this); button2.setOnClickListener(this);
} else { } else {
button2.setVisibility(View.GONE); button2.setVisibility(View.GONE);
} }
if(amount3 >0) { if (amount3 > 0) {
button3.setVisibility(View.VISIBLE); button3.setVisibility(View.VISIBLE);
button3.setText(DecimalFormatter.to2Decimal(amount3) + "U"); button3.setText(DecimalFormatter.to2Decimal(amount3) + "U");
button3.setOnClickListener(this); button3.setOnClickListener(this);
@ -104,7 +97,7 @@ public class FillDialog extends DialogFragment implements OnClickListener {
button3.setVisibility(View.GONE); button3.setVisibility(View.GONE);
} }
if (button1.getVisibility() == View.GONE && button2.getVisibility() == View.GONE && button3.getVisibility() == View.GONE ) { if (button1.getVisibility() == View.GONE && button2.getVisibility() == View.GONE && button3.getVisibility() == View.GONE) {
divider.setVisibility(View.GONE); divider.setVisibility(View.GONE);
} }
return view; return view;
@ -121,7 +114,7 @@ public class FillDialog extends DialogFragment implements OnClickListener {
public void onClick(View view) { public void onClick(View view) {
switch (view.getId()) { switch (view.getId()) {
case R.id.treatments_newtreatment_deliverbutton: case R.id.treatments_newtreatment_deliverbutton:
Double insulin = SafeParse.stringToDouble(this.insulin.getText().toString()); Double insulin = SafeParse.stringToDouble(editInsulin.getText().toString());
confirmAndDeliver(insulin); confirmAndDeliver(insulin);
break; break;
case R.id.fill_preset_button1: case R.id.fill_preset_button1:
@ -157,22 +150,21 @@ public class FillDialog extends DialogFragment implements OnClickListener {
builder.setPositiveButton(getString(R.string.primefill), new DialogInterface.OnClickListener() { builder.setPositiveButton(getString(R.string.primefill), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) { public void onClick(DialogInterface dialog, int id) {
if (finalInsulinAfterConstraints > 0) { if (finalInsulinAfterConstraints > 0) {
final ConfigBuilderPlugin pump = MainApp.getConfigBuilder(); DetailedBolusInfo detailedBolusInfo = new DetailedBolusInfo();
mHandler.post(new Runnable() { detailedBolusInfo.insulin = finalInsulinAfterConstraints;
detailedBolusInfo.context = context;
detailedBolusInfo.source = Source.USER;
detailedBolusInfo.isValid = false; // do not count it in IOB (for pump history)
ConfigBuilderPlugin.getCommandQueue().bolus(detailedBolusInfo, new Callback() {
@Override @Override
public void run() { public void run() {
DetailedBolusInfo detailedBolusInfo = new DetailedBolusInfo();
detailedBolusInfo.insulin = finalInsulinAfterConstraints;
detailedBolusInfo.context = context;
detailedBolusInfo.source = Source.USER;
detailedBolusInfo.isValid = false; // do not count it in IOB (for pump history)
PumpEnactResult result = pump.deliverTreatment(detailedBolusInfo);
if (!result.success) { if (!result.success) {
AlertDialog.Builder builder = new AlertDialog.Builder(context); Intent i = new Intent(MainApp.instance(), ErrorHelperActivity.class);
builder.setTitle(MainApp.sResources.getString(R.string.treatmentdeliveryerror)); i.putExtra("soundid", R.raw.boluserror);
builder.setMessage(result.comment); i.putExtra("status", result.comment);
builder.setPositiveButton(MainApp.sResources.getString(R.string.ok), null); i.putExtra("title", MainApp.sResources.getString(R.string.treatmentdeliveryerror));
builder.show(); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
MainApp.instance().startActivity(i);
} }
} }
}); });
@ -183,8 +175,8 @@ public class FillDialog extends DialogFragment implements OnClickListener {
builder.setNegativeButton(getString(R.string.cancel), null); builder.setNegativeButton(getString(R.string.cancel), null);
builder.show(); builder.show();
dismiss(); dismiss();
} catch (Exception e) { } catch (RuntimeException e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
} }

View file

@ -2,43 +2,38 @@ package info.nightscout.androidaps.plugins.Actions.dialogs;
import android.content.Context; import android.content.Context;
import android.content.DialogInterface; import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle; import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.support.v4.app.DialogFragment; import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog; import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater; import android.view.LayoutInflater;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import com.crashlytics.android.answers.Answers; import com.crashlytics.android.answers.Answers;
import com.crashlytics.android.answers.CustomEvent; import com.crashlytics.android.answers.CustomEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.text.DecimalFormat; import java.text.DecimalFormat;
import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.PumpEnactResult; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.plugins.Overview.Dialogs.ErrorHelperActivity;
import info.nightscout.utils.PlusMinusEditText; import info.nightscout.androidaps.queue.Callback;
import info.nightscout.utils.NumberPicker;
import info.nightscout.utils.SafeParse; import info.nightscout.utils.SafeParse;
public class NewExtendedBolusDialog extends DialogFragment implements View.OnClickListener { public class NewExtendedBolusDialog extends DialogFragment implements View.OnClickListener {
private static Logger log = LoggerFactory.getLogger(NewExtendedBolusDialog.class);
PlusMinusEditText editInsulin; NumberPicker editInsulin;
PlusMinusEditText editDuration; NumberPicker editDuration;
Handler mHandler;
public static HandlerThread mHandlerThread;
public NewExtendedBolusDialog() { public NewExtendedBolusDialog() {
mHandlerThread = new HandlerThread(NewExtendedBolusDialog.class.getSimpleName());
mHandlerThread.start();
this.mHandler = new Handler(mHandlerThread.getLooper());
} }
@Override @Override
@ -49,11 +44,13 @@ public class NewExtendedBolusDialog extends DialogFragment implements View.OnCli
View view = inflater.inflate(R.layout.overview_newextendedbolus_dialog, container, false); View view = inflater.inflate(R.layout.overview_newextendedbolus_dialog, container, false);
Double maxInsulin = MainApp.getConfigBuilder().applyBolusConstraints(Constants.bolusOnlyForCheckLimit); Double maxInsulin = MainApp.getConfigBuilder().applyBolusConstraints(Constants.bolusOnlyForCheckLimit);
editInsulin = new PlusMinusEditText(view, R.id.overview_newextendedbolus_insulin, R.id.overview_newextendedbolus_insulin_plus, R.id.overview_newextendedbolus_insulin_minus, 0d, 0d, maxInsulin, 0.1d, new DecimalFormat("0.00"), false); editInsulin = (NumberPicker) view.findViewById(R.id.overview_newextendedbolus_insulin);
editInsulin.setParams(0d, 0d, maxInsulin, 0.1d, new DecimalFormat("0.00"), false);
double extendedDurationStep = MainApp.getConfigBuilder().getPumpDescription().extendedBolusDurationStep; double extendedDurationStep = ConfigBuilderPlugin.getActivePump().getPumpDescription().extendedBolusDurationStep;
double extendedMaxDuration = MainApp.getConfigBuilder().getPumpDescription().extendedBolusMaxDuration; double extendedMaxDuration = ConfigBuilderPlugin.getActivePump().getPumpDescription().extendedBolusMaxDuration;
editDuration = new PlusMinusEditText(view, R.id.overview_newextendedbolus_duration, R.id.overview_newextendedbolus_duration_plus, R.id.overview_newextendedbolus_duration_minus, extendedDurationStep, extendedDurationStep, extendedMaxDuration, extendedDurationStep, new DecimalFormat("0"), false); editDuration = (NumberPicker) view.findViewById(R.id.overview_newextendedbolus_duration);
editDuration.setParams(extendedDurationStep, extendedDurationStep, extendedMaxDuration, extendedDurationStep, new DecimalFormat("0"), false);
view.findViewById(R.id.ok).setOnClickListener(this); view.findViewById(R.id.ok).setOnClickListener(this);
view.findViewById(R.id.cancel).setOnClickListener(this); view.findViewById(R.id.cancel).setOnClickListener(this);
@ -93,17 +90,16 @@ public class NewExtendedBolusDialog extends DialogFragment implements View.OnCli
builder.setMessage(confirmMessage); builder.setMessage(confirmMessage);
builder.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() { builder.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) { public void onClick(DialogInterface dialog, int id) {
final PumpInterface pump = MainApp.getConfigBuilder(); ConfigBuilderPlugin.getCommandQueue().extendedBolus(finalInsulin, finalDurationInMinutes, new Callback() {
mHandler.post(new Runnable() {
@Override @Override
public void run() { public void run() {
PumpEnactResult result = pump.setExtendedBolus(finalInsulin, finalDurationInMinutes);
if (!result.success) { if (!result.success) {
AlertDialog.Builder builder = new AlertDialog.Builder(context); Intent i = new Intent(MainApp.instance(), ErrorHelperActivity.class);
builder.setTitle(context.getString(R.string.treatmentdeliveryerror)); i.putExtra("soundid", R.raw.boluserror);
builder.setMessage(result.comment); i.putExtra("status", result.comment);
builder.setPositiveButton(context.getString(R.string.ok), null); i.putExtra("title", MainApp.sResources.getString(R.string.treatmentdeliveryerror));
builder.show(); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
MainApp.instance().startActivity(i);
} }
} }
}); });
@ -115,7 +111,7 @@ public class NewExtendedBolusDialog extends DialogFragment implements View.OnCli
dismiss(); dismiss();
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
break; break;
case R.id.cancel: case R.id.cancel:

View file

@ -1,11 +1,9 @@
package info.nightscout.androidaps.plugins.Actions.dialogs; package info.nightscout.androidaps.plugins.Actions.dialogs;
import android.app.Activity;
import android.content.Context; import android.content.Context;
import android.content.DialogInterface; import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle; import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.support.v4.app.DialogFragment; import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog; import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater; import android.view.LayoutInflater;
@ -14,24 +12,27 @@ import android.view.ViewGroup;
import android.widget.LinearLayout; import android.widget.LinearLayout;
import android.widget.RadioButton; import android.widget.RadioButton;
import android.widget.RadioGroup; import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import com.crashlytics.android.answers.Answers; import com.crashlytics.android.answers.Answers;
import com.crashlytics.android.answers.CustomEvent; import com.crashlytics.android.answers.CustomEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.text.DecimalFormat; import java.text.DecimalFormat;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.PumpEnactResult;
import info.nightscout.androidaps.interfaces.PumpDescription;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.interfaces.PumpDescription;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.Overview.Dialogs.ErrorHelperActivity;
import info.nightscout.androidaps.queue.Callback;
import info.nightscout.utils.NumberPicker; import info.nightscout.utils.NumberPicker;
import info.nightscout.utils.PlusMinusEditText;
import info.nightscout.utils.SafeParse; import info.nightscout.utils.SafeParse;
public class NewTempBasalDialog extends DialogFragment implements View.OnClickListener, RadioGroup.OnCheckedChangeListener { public class NewTempBasalDialog extends DialogFragment implements View.OnClickListener, RadioGroup.OnCheckedChangeListener {
private static Logger log = LoggerFactory.getLogger(NewTempBasalDialog.class);
RadioButton percentRadio; RadioButton percentRadio;
RadioButton absoluteRadio; RadioButton absoluteRadio;
@ -45,13 +46,7 @@ public class NewTempBasalDialog extends DialogFragment implements View.OnClickLi
NumberPicker basalAbsolute; NumberPicker basalAbsolute;
NumberPicker duration; NumberPicker duration;
Handler mHandler;
public static HandlerThread mHandlerThread;
public NewTempBasalDialog() { public NewTempBasalDialog() {
mHandlerThread = new HandlerThread(NewTempBasalDialog.class.getSimpleName());
mHandlerThread.start();
this.mHandler = new Handler(mHandlerThread.getLooper());
} }
@Override @Override
@ -68,9 +63,9 @@ public class NewTempBasalDialog extends DialogFragment implements View.OnClickLi
absoluteRadio = (RadioButton) view.findViewById(R.id.overview_newtempbasal_absolute_radio); absoluteRadio = (RadioButton) view.findViewById(R.id.overview_newtempbasal_absolute_radio);
typeSelectorLayout = (LinearLayout) view.findViewById(R.id.overview_newtempbasal_typeselector_layout); typeSelectorLayout = (LinearLayout) view.findViewById(R.id.overview_newtempbasal_typeselector_layout);
PumpDescription pumpDescription = MainApp.getConfigBuilder().getPumpDescription(); PumpDescription pumpDescription = ConfigBuilderPlugin.getActivePump().getPumpDescription();
basalPercent = (NumberPicker) view.findViewById(R.id.overview_newtempbasal_basalpercentinput); basalPercent = (NumberPicker) view.findViewById(R.id.overview_newtempbasal_basalpercentinput);
double maxTempPercent = pumpDescription.maxTempPercent; double maxTempPercent = pumpDescription.maxTempPercent;
double tempPercentStep = pumpDescription.tempPercentStep; double tempPercentStep = pumpDescription.tempPercentStep;
basalPercent.setParams(100d, 0d, maxTempPercent, tempPercentStep, new DecimalFormat("0"), true); basalPercent.setParams(100d, 0d, maxTempPercent, tempPercentStep, new DecimalFormat("0"), true);
@ -141,37 +136,29 @@ public class NewTempBasalDialog extends DialogFragment implements View.OnClickLi
final Double finalBasal = absolute; final Double finalBasal = absolute;
final int finalDurationInMinutes = durationInMinutes; final int finalDurationInMinutes = durationInMinutes;
final Context context = getContext(); AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(this.getContext().getString(R.string.confirmation)); builder.setTitle(this.getContext().getString(R.string.confirmation));
builder.setMessage(confirmMessage); builder.setMessage(confirmMessage);
builder.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() { builder.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) { public void onClick(DialogInterface dialog, int id) {
final PumpInterface pump = MainApp.getConfigBuilder(); Callback callback = new Callback() {
mHandler.post(new Runnable() {
@Override @Override
public void run() { public void run() {
PumpEnactResult result;
if (setAsPercent) {
result = pump.setTempBasalPercent(finalBasalPercent, finalDurationInMinutes);
} else {
result = pump.setTempBasalAbsolute(finalBasal, finalDurationInMinutes, false);
}
if (!result.success) { if (!result.success) {
if (context instanceof Activity) { Intent i = new Intent(MainApp.instance(), ErrorHelperActivity.class);
Activity activity = (Activity) context; i.putExtra("soundid", R.raw.boluserror);
if (activity.isFinishing()) { i.putExtra("status", result.comment);
return; i.putExtra("title", MainApp.sResources.getString(R.string.tempbasaldeliveryerror));
} i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
} MainApp.instance().startActivity(i);
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(MainApp.sResources.getString(R.string.tempbasaldeliveryerror));
builder.setMessage(result.comment);
builder.setPositiveButton(MainApp.sResources.getString(R.string.ok), null);
builder.show();
} }
} }
}); };
if (setAsPercent) {
ConfigBuilderPlugin.getCommandQueue().tempBasalPercent(finalBasalPercent, finalDurationInMinutes, callback);
} else {
ConfigBuilderPlugin.getCommandQueue().tempBasalAbsolute(finalBasal, finalDurationInMinutes, true, callback);
}
Answers.getInstance().logCustom(new CustomEvent("TempBasal")); Answers.getInstance().logCustom(new CustomEvent("TempBasal"));
} }
}); });
@ -180,7 +167,7 @@ public class NewTempBasalDialog extends DialogFragment implements View.OnClickLi
dismiss(); dismiss();
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
break; break;
case R.id.cancel: case R.id.cancel:

View file

@ -3,103 +3,118 @@ package info.nightscout.androidaps.plugins.Careportal;
import android.app.Activity; import android.app.Activity;
import android.os.Bundle; import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentManager;
import android.text.Layout;
import android.view.LayoutInflater; import android.view.LayoutInflater;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView; import android.widget.TextView;
import com.crashlytics.android.Crashlytics;
import com.squareup.otto.Subscribe; import com.squareup.otto.Subscribe;
import info.nightscout.androidaps.BuildConfig; import info.nightscout.androidaps.BuildConfig;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.ProfileStore;
import info.nightscout.androidaps.db.CareportalEvent; import info.nightscout.androidaps.db.CareportalEvent;
import info.nightscout.androidaps.events.EventCareportalEventChange; import info.nightscout.androidaps.events.EventCareportalEventChange;
import info.nightscout.androidaps.plugins.Careportal.Dialogs.NewNSTreatmentDialog; import info.nightscout.androidaps.plugins.Careportal.Dialogs.NewNSTreatmentDialog;
import info.nightscout.androidaps.plugins.Common.SubscriberFragment; import info.nightscout.androidaps.plugins.Common.SubscriberFragment;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.Overview.OverviewFragment; import info.nightscout.androidaps.plugins.Overview.OverviewFragment;
public class CareportalFragment extends SubscriberFragment implements View.OnClickListener { public class CareportalFragment extends SubscriberFragment implements View.OnClickListener {
static CareportalPlugin careportalPlugin;
TextView iage; TextView iage;
TextView cage; TextView cage;
TextView sage; TextView sage;
TextView pbage; TextView pbage;
View statsLayout; View statsLayout;
LinearLayout butonsLayout;
View noProfileView;
static public CareportalPlugin getPlugin() { // date,bg,insulin,carbs,prebolus,duration,percent,absolute,profile,split,temptarget
if (careportalPlugin == null) { public static final OptionsToShow BGCHECK = new OptionsToShow(R.id.careportal_bgcheck, R.string.careportal_bgcheck).date().bg();
careportalPlugin = new CareportalPlugin(); public static final OptionsToShow SNACKBOLUS = new OptionsToShow(R.id.careportal_snackbolus, R.string.careportal_snackbolus).date().bg().insulin().carbs().prebolus();
} public static final OptionsToShow MEALBOLUS = new OptionsToShow(R.id.careportal_mealbolus, R.string.careportal_mealbolus).date().bg().insulin().carbs().prebolus();
return careportalPlugin; public static final OptionsToShow CORRECTIONBOLUS = new OptionsToShow(R.id.careportal_correctionbolus, R.string.careportal_correctionbolus).date().bg().insulin().carbs().prebolus();
} public static final OptionsToShow CARBCORRECTION = new OptionsToShow(R.id.careportal_carbscorrection, R.string.careportal_carbscorrection).date().bg().carbs();
public static final OptionsToShow COMBOBOLUS = new OptionsToShow(R.id.careportal_combobolus, R.string.careportal_combobolus).date().bg().insulin().carbs().prebolus().duration().split();
// bg,insulin,carbs,prebolus,duration,percent,absolute,profile,split,temptarget public static final OptionsToShow ANNOUNCEMENT = new OptionsToShow(R.id.careportal_announcement, R.string.careportal_announcement).date().bg();
public static final OptionsToShow bgcheck = new OptionsToShow(R.id.careportal_bgcheck, R.string.careportal_bgcheck, true, true, true, false, false, false, false, false, false, false); public static final OptionsToShow NOTE = new OptionsToShow(R.id.careportal_note, R.string.careportal_note).date().bg().duration();
public static final OptionsToShow snackbolus = new OptionsToShow(R.id.careportal_snackbolus, R.string.careportal_snackbolus, true, true, true, true, false, false, false, false, false, false); public static final OptionsToShow QUESTION = new OptionsToShow(R.id.careportal_question, R.string.careportal_question).date().bg();
public static final OptionsToShow mealbolus = new OptionsToShow(R.id.careportal_mealbolus, R.string.careportal_mealbolus, true, true, true, true, false, false, false, false, false, false); public static final OptionsToShow EXERCISE = new OptionsToShow(R.id.careportal_exercise, R.string.careportal_exercise).date().duration();
public static final OptionsToShow correctionbolus = new OptionsToShow(R.id.careportal_correctionbolus, R.string.careportal_correctionbolus, true, true, true, true, false, false, false, false, false, false); public static final OptionsToShow SITECHANGE = new OptionsToShow(R.id.careportal_pumpsitechange, R.string.careportal_pumpsitechange).date().bg();
public static final OptionsToShow carbcorrection = new OptionsToShow(R.id.careportal_carbscorrection, R.string.careportal_carbscorrection, true, false, true, false, false, false, false, false, false, false); public static final OptionsToShow SENSORSTART = new OptionsToShow(R.id.careportal_cgmsensorstart, R.string.careportal_cgmsensorstart).date().bg();
public static final OptionsToShow combobolus = new OptionsToShow(R.id.careportal_combobolus, R.string.careportal_combobolus, true, true, true, true, true, false, false, false, true, false); public static final OptionsToShow SENSORCHANGE = new OptionsToShow(R.id.careportal_cgmsensorinsert, R.string.careportal_cgmsensorinsert).date().bg();
public static final OptionsToShow announcement = new OptionsToShow(R.id.careportal_announcement, R.string.careportal_announcement, true, false, false, false, false, false, false, false, false, false); public static final OptionsToShow INSULINCHANGE = new OptionsToShow(R.id.careportal_insulincartridgechange, R.string.careportal_insulincartridgechange).date().bg();
public static final OptionsToShow note = new OptionsToShow(R.id.careportal_note, R.string.careportal_note, true, false, false, false, true, false, false, false, false, false); public static final OptionsToShow PUMPBATTERYCHANGE = new OptionsToShow(R.id.careportal_pumpbatterychange, R.string.careportal_pumpbatterychange).date().bg();
public static final OptionsToShow question = new OptionsToShow(R.id.careportal_question, R.string.careportal_question, true, false, false, false, false, false, false, false, false, false); public static final OptionsToShow TEMPBASALSTART = new OptionsToShow(R.id.careportal_tempbasalstart, R.string.careportal_tempbasalstart).date().bg().duration().percent().absolute();
public static final OptionsToShow exercise = new OptionsToShow(R.id.careportal_exercise, R.string.careportal_exercise, false, false, false, false, true, false, false, false, false, false); public static final OptionsToShow TEMPBASALEND = new OptionsToShow(R.id.careportal_tempbasalend, R.string.careportal_tempbasalend).date().bg();
public static final OptionsToShow sitechange = new OptionsToShow(R.id.careportal_pumpsitechange, R.string.careportal_pumpsitechange, true, true, false, false, false, false, false, false, false, false); public static final OptionsToShow PROFILESWITCH = new OptionsToShow(R.id.careportal_profileswitch, R.string.careportal_profileswitch).date().duration().profile();
public static final OptionsToShow sensorstart = new OptionsToShow(R.id.careportal_cgmsensorstart, R.string.careportal_cgmsensorstart, true, false, false, false, false, false, false, false, false, false); public static final OptionsToShow PROFILESWITCHDIRECT = new OptionsToShow(R.id.careportal_profileswitch, R.string.careportal_profileswitch).duration().profile();
public static final OptionsToShow sensorchange = new OptionsToShow(R.id.careportal_cgmsensorinsert, R.string.careportal_cgmsensorinsert, true, false, false, false, false, false, false, false, false, false); public static final OptionsToShow OPENAPSOFFLINE = new OptionsToShow(R.id.careportal_openapsoffline, R.string.careportal_openapsoffline).date().duration();
public static final OptionsToShow insulinchange = new OptionsToShow(R.id.careportal_insulincartridgechange, R.string.careportal_insulincartridgechange, true, false, false, false, false, false, false, false, false, false); public static final OptionsToShow TEMPTARGET = new OptionsToShow(R.id.careportal_temporarytarget, R.string.careportal_temporarytarget).date().duration().tempTarget();
public static final OptionsToShow pumpbatterychange = new OptionsToShow(R.id.careportal_pumpbatterychange, R.string.careportal_pumpbatterychange, true, false, false, false, false, false, false, false, false, false);
public static final OptionsToShow tempbasalstart = new OptionsToShow(R.id.careportal_tempbasalstart, R.string.careportal_tempbasalstart, true, false, false, false, true, true, true, false, false, false);
public static final OptionsToShow tempbasalend = new OptionsToShow(R.id.careportal_tempbasalend, R.string.careportal_tempbasalend, true, false, false, false, false, false, false, false, false, false);
public static final OptionsToShow profileswitch = new OptionsToShow(R.id.careportal_profileswitch, R.string.careportal_profileswitch, true, false, false, false, true, false, false, true, false, false);
public static final OptionsToShow openapsoffline = new OptionsToShow(R.id.careportal_openapsoffline, R.string.careportal_openapsoffline, false, false, false, false, true, false, false, false, false, false);
public static final OptionsToShow temptarget = new OptionsToShow(R.id.careportal_temporarytarget, R.string.careportal_temporarytarget, false, false, false, false, true, false, false, false, false, true);
@Override @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) { Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.careportal_fragment, container, false); try {
View view = inflater.inflate(R.layout.careportal_fragment, container, false);
view.findViewById(R.id.careportal_bgcheck).setOnClickListener(this); view.findViewById(R.id.careportal_bgcheck).setOnClickListener(this);
view.findViewById(R.id.careportal_announcement).setOnClickListener(this); view.findViewById(R.id.careportal_announcement).setOnClickListener(this);
view.findViewById(R.id.careportal_cgmsensorinsert).setOnClickListener(this); view.findViewById(R.id.careportal_cgmsensorinsert).setOnClickListener(this);
view.findViewById(R.id.careportal_cgmsensorstart).setOnClickListener(this); view.findViewById(R.id.careportal_cgmsensorstart).setOnClickListener(this);
view.findViewById(R.id.careportal_combobolus).setOnClickListener(this); view.findViewById(R.id.careportal_combobolus).setOnClickListener(this);
view.findViewById(R.id.careportal_correctionbolus).setOnClickListener(this); view.findViewById(R.id.careportal_correctionbolus).setOnClickListener(this);
view.findViewById(R.id.careportal_carbscorrection).setOnClickListener(this); view.findViewById(R.id.careportal_carbscorrection).setOnClickListener(this);
view.findViewById(R.id.careportal_exercise).setOnClickListener(this); view.findViewById(R.id.careportal_exercise).setOnClickListener(this);
view.findViewById(R.id.careportal_insulincartridgechange).setOnClickListener(this); view.findViewById(R.id.careportal_insulincartridgechange).setOnClickListener(this);
view.findViewById(R.id.careportal_pumpbatterychange).setOnClickListener(this); view.findViewById(R.id.careportal_pumpbatterychange).setOnClickListener(this);
view.findViewById(R.id.careportal_mealbolus).setOnClickListener(this); view.findViewById(R.id.careportal_mealbolus).setOnClickListener(this);
view.findViewById(R.id.careportal_note).setOnClickListener(this); view.findViewById(R.id.careportal_note).setOnClickListener(this);
view.findViewById(R.id.careportal_profileswitch).setOnClickListener(this); view.findViewById(R.id.careportal_profileswitch).setOnClickListener(this);
view.findViewById(R.id.careportal_pumpsitechange).setOnClickListener(this); view.findViewById(R.id.careportal_pumpsitechange).setOnClickListener(this);
view.findViewById(R.id.careportal_question).setOnClickListener(this); view.findViewById(R.id.careportal_question).setOnClickListener(this);
view.findViewById(R.id.careportal_snackbolus).setOnClickListener(this); view.findViewById(R.id.careportal_snackbolus).setOnClickListener(this);
view.findViewById(R.id.careportal_tempbasalend).setOnClickListener(this); view.findViewById(R.id.careportal_tempbasalend).setOnClickListener(this);
view.findViewById(R.id.careportal_tempbasalstart).setOnClickListener(this); view.findViewById(R.id.careportal_tempbasalstart).setOnClickListener(this);
view.findViewById(R.id.careportal_openapsoffline).setOnClickListener(this); view.findViewById(R.id.careportal_openapsoffline).setOnClickListener(this);
view.findViewById(R.id.careportal_temporarytarget).setOnClickListener(this); view.findViewById(R.id.careportal_temporarytarget).setOnClickListener(this);
iage = (TextView) view.findViewById(R.id.careportal_insulinage); iage = (TextView) view.findViewById(R.id.careportal_insulinage);
cage = (TextView) view.findViewById(R.id.careportal_canulaage); cage = (TextView) view.findViewById(R.id.careportal_canulaage);
sage = (TextView) view.findViewById(R.id.careportal_sensorage); sage = (TextView) view.findViewById(R.id.careportal_sensorage);
pbage = (TextView) view.findViewById(R.id.careportal_pbage); pbage = (TextView) view.findViewById(R.id.careportal_pbage);
statsLayout = (View) view.findViewById(R.id.careportal_stats); statsLayout = view.findViewById(R.id.careportal_stats);
if (BuildConfig.NSCLIENTOLNY) noProfileView = view.findViewById(R.id.profileview_noprofile);
statsLayout.setVisibility(View.GONE); // visible on overview butonsLayout = (LinearLayout) view.findViewById(R.id.careportal_buttons);
updateGUI(); ProfileStore profileStore = ConfigBuilderPlugin.getActiveProfileInterface().getProfile();
return view; if (profileStore == null) {
noProfileView.setVisibility(View.VISIBLE);
butonsLayout.setVisibility(View.GONE);
} else {
noProfileView.setVisibility(View.GONE);
butonsLayout.setVisibility(View.VISIBLE);
}
if (Config.NSCLIENT || Config.G5UPLOADER)
statsLayout.setVisibility(View.GONE); // visible on overview
updateGUI();
return view;
} catch (Exception e) {
Crashlytics.logException(e);
}
return null;
} }
@Override @Override
@ -111,66 +126,66 @@ public class CareportalFragment extends SubscriberFragment implements View.OnCli
NewNSTreatmentDialog newDialog = new NewNSTreatmentDialog(); NewNSTreatmentDialog newDialog = new NewNSTreatmentDialog();
switch (id) { switch (id) {
case R.id.careportal_bgcheck: case R.id.careportal_bgcheck:
newDialog.setOptions(bgcheck, R.string.careportal_bgcheck); newDialog.setOptions(BGCHECK, R.string.careportal_bgcheck);
break; break;
case R.id.careportal_announcement: case R.id.careportal_announcement:
newDialog.setOptions(announcement, R.string.careportal_announcement); newDialog.setOptions(ANNOUNCEMENT, R.string.careportal_announcement);
break; break;
case R.id.careportal_cgmsensorinsert: case R.id.careportal_cgmsensorinsert:
newDialog.setOptions(sensorchange, R.string.careportal_cgmsensorinsert); newDialog.setOptions(SENSORCHANGE, R.string.careportal_cgmsensorinsert);
break; break;
case R.id.careportal_cgmsensorstart: case R.id.careportal_cgmsensorstart:
newDialog.setOptions(sensorstart, R.string.careportal_cgmsensorstart); newDialog.setOptions(SENSORSTART, R.string.careportal_cgmsensorstart);
break; break;
case R.id.careportal_combobolus: case R.id.careportal_combobolus:
newDialog.setOptions(combobolus, R.string.careportal_combobolus); newDialog.setOptions(COMBOBOLUS, R.string.careportal_combobolus);
break; break;
case R.id.careportal_correctionbolus: case R.id.careportal_correctionbolus:
newDialog.setOptions(correctionbolus, R.string.careportal_correctionbolus); newDialog.setOptions(CORRECTIONBOLUS, R.string.careportal_correctionbolus);
break; break;
case R.id.careportal_carbscorrection: case R.id.careportal_carbscorrection:
newDialog.setOptions(carbcorrection, R.string.careportal_carbscorrection); newDialog.setOptions(CARBCORRECTION, R.string.careportal_carbscorrection);
break; break;
case R.id.careportal_exercise: case R.id.careportal_exercise:
newDialog.setOptions(exercise, R.string.careportal_exercise); newDialog.setOptions(EXERCISE, R.string.careportal_exercise);
break; break;
case R.id.careportal_insulincartridgechange: case R.id.careportal_insulincartridgechange:
newDialog.setOptions(insulinchange, R.string.careportal_insulincartridgechange); newDialog.setOptions(INSULINCHANGE, R.string.careportal_insulincartridgechange);
break; break;
case R.id.careportal_pumpbatterychange: case R.id.careportal_pumpbatterychange:
newDialog.setOptions(pumpbatterychange, R.string.careportal_pumpbatterychange); newDialog.setOptions(PUMPBATTERYCHANGE, R.string.careportal_pumpbatterychange);
break; break;
case R.id.careportal_mealbolus: case R.id.careportal_mealbolus:
newDialog.setOptions(mealbolus, R.string.careportal_mealbolus); newDialog.setOptions(MEALBOLUS, R.string.careportal_mealbolus);
break; break;
case R.id.careportal_note: case R.id.careportal_note:
newDialog.setOptions(note, R.string.careportal_note); newDialog.setOptions(NOTE, R.string.careportal_note);
break; break;
case R.id.careportal_profileswitch: case R.id.careportal_profileswitch:
profileswitch.executeProfileSwitch = false; PROFILESWITCH.executeProfileSwitch = false;
newDialog.setOptions(profileswitch, R.string.careportal_profileswitch); newDialog.setOptions(PROFILESWITCH, R.string.careportal_profileswitch);
break; break;
case R.id.careportal_pumpsitechange: case R.id.careportal_pumpsitechange:
newDialog.setOptions(sitechange, R.string.careportal_pumpsitechange); newDialog.setOptions(SITECHANGE, R.string.careportal_pumpsitechange);
break; break;
case R.id.careportal_question: case R.id.careportal_question:
newDialog.setOptions(question, R.string.careportal_question); newDialog.setOptions(QUESTION, R.string.careportal_question);
break; break;
case R.id.careportal_snackbolus: case R.id.careportal_snackbolus:
newDialog.setOptions(snackbolus, R.string.careportal_snackbolus); newDialog.setOptions(SNACKBOLUS, R.string.careportal_snackbolus);
break; break;
case R.id.careportal_tempbasalstart: case R.id.careportal_tempbasalstart:
newDialog.setOptions(tempbasalstart, R.string.careportal_tempbasalstart); newDialog.setOptions(TEMPBASALSTART, R.string.careportal_tempbasalstart);
break; break;
case R.id.careportal_tempbasalend: case R.id.careportal_tempbasalend:
newDialog.setOptions(tempbasalend, R.string.careportal_tempbasalend); newDialog.setOptions(TEMPBASALEND, R.string.careportal_tempbasalend);
break; break;
case R.id.careportal_openapsoffline: case R.id.careportal_openapsoffline:
newDialog.setOptions(openapsoffline, R.string.careportal_openapsoffline); newDialog.setOptions(OPENAPSOFFLINE, R.string.careportal_openapsoffline);
break; break;
case R.id.careportal_temporarytarget: case R.id.careportal_temporarytarget:
temptarget.executeTempTarget = false; TEMPTARGET.executeTempTarget = false;
newDialog.setOptions(temptarget, R.string.careportal_temporarytarget); newDialog.setOptions(TEMPTARGET, R.string.careportal_temporarytarget);
break; break;
default: default:
newDialog = null; newDialog = null;

View file

@ -7,8 +7,17 @@ import info.nightscout.androidaps.interfaces.PluginBase;
public class CareportalPlugin implements PluginBase { public class CareportalPlugin implements PluginBase {
boolean fragmentEnabled = true; private boolean fragmentEnabled = true;
boolean fragmentVisible = true; private boolean fragmentVisible = true;
static CareportalPlugin careportalPlugin;
static public CareportalPlugin getPlugin() {
if (careportalPlugin == null) {
careportalPlugin = new CareportalPlugin();
}
return careportalPlugin;
}
@Override @Override
public int getType() { public int getType() {
@ -58,7 +67,7 @@ public class CareportalPlugin implements PluginBase {
@Override @Override
public boolean showInList(int type) { public boolean showInList(int type) {
return !Config.NSCLIENT; return !Config.NSCLIENT && !Config.G5UPLOADER;
} }
@Override @Override
@ -71,4 +80,9 @@ public class CareportalPlugin implements PluginBase {
if (type == GENERAL) this.fragmentVisible = fragmentVisible; if (type == GENERAL) this.fragmentVisible = fragmentVisible;
} }
@Override
public int getPreferencesId() {
return R.xml.pref_careportal;
}
} }

View file

@ -3,9 +3,8 @@ package info.nightscout.androidaps.plugins.Careportal.Dialogs;
import android.app.Activity; import android.app.Activity;
import android.content.DialogInterface; import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle; import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.support.v4.app.DialogFragment; import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog; import android.support.v7.app.AlertDialog;
import android.text.Editable; import android.text.Editable;
@ -14,7 +13,9 @@ import android.text.format.DateFormat;
import android.view.LayoutInflater; import android.view.LayoutInflater;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter; import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton; import android.widget.CompoundButton;
import android.widget.EditText; import android.widget.EditText;
import android.widget.LinearLayout; import android.widget.LinearLayout;
@ -49,10 +50,10 @@ import info.nightscout.androidaps.db.ProfileSwitch;
import info.nightscout.androidaps.db.Source; import info.nightscout.androidaps.db.Source;
import info.nightscout.androidaps.db.TempTarget; import info.nightscout.androidaps.db.TempTarget;
import info.nightscout.androidaps.events.EventNewBasalProfile; import info.nightscout.androidaps.events.EventNewBasalProfile;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.plugins.Careportal.OptionsToShow; import info.nightscout.androidaps.plugins.Careportal.OptionsToShow;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.ProfileCircadianPercentage.CircadianPercentageProfilePlugin; import info.nightscout.androidaps.plugins.Overview.Dialogs.ErrorHelperActivity;
import info.nightscout.androidaps.queue.Callback;
import info.nightscout.utils.DateUtil; import info.nightscout.utils.DateUtil;
import info.nightscout.utils.NSUpload; import info.nightscout.utils.NSUpload;
import info.nightscout.utils.NumberPicker; import info.nightscout.utils.NumberPicker;
@ -73,17 +74,11 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
String units; String units;
TextView eventTypeText; TextView eventTypeText;
LinearLayout layoutBg;
LinearLayout layoutBgSource;
LinearLayout layoutInsulin;
LinearLayout layoutCarbs;
LinearLayout layoutSplit;
LinearLayout layoutDuration;
LinearLayout layoutPercent; LinearLayout layoutPercent;
LinearLayout layoutAbsolute; LinearLayout layoutAbsolute;
LinearLayout layoutCarbTime; LinearLayout layoutReuse;
LinearLayout layoutProfile;
LinearLayout layoutTempTarget;
TextView dateButton; TextView dateButton;
TextView timeButton; TextView timeButton;
@ -94,6 +89,7 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
EditText notesEdit; EditText notesEdit;
Spinner profileSpinner; Spinner profileSpinner;
Spinner reasonSpinner; Spinner reasonSpinner;
Button reuseButton;
NumberPicker editBg; NumberPicker editBg;
NumberPicker editCarbs; NumberPicker editCarbs;
@ -104,13 +100,11 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
NumberPicker editAbsolute; NumberPicker editAbsolute;
NumberPicker editCarbTime; NumberPicker editCarbTime;
NumberPicker editTemptarget; NumberPicker editTemptarget;
NumberPicker editPercentage;
NumberPicker editTimeshift;
Date eventTime; Date eventTime;
private static Handler sHandler;
private static HandlerThread sHandlerThread;
public void setOptions(OptionsToShow options, int event) { public void setOptions(OptionsToShow options, int event) {
this.options = options; this.options = options;
this.event = MainApp.sResources.getString(event); this.event = MainApp.sResources.getString(event);
@ -118,11 +112,6 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
public NewNSTreatmentDialog() { public NewNSTreatmentDialog() {
super(); super();
if (sHandlerThread == null) {
sHandlerThread = new HandlerThread(NewNSTreatmentDialog.class.getSimpleName());
sHandlerThread.start();
sHandler = new Handler(sHandlerThread.getLooper());
}
} }
@Override @Override
@ -140,21 +129,15 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
@Override @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) { Bundle savedInstanceState) {
if (options == null) return null;
getDialog().setTitle(getString(options.eventName)); getDialog().setTitle(getString(options.eventName));
setStyle(DialogFragment.STYLE_NORMAL, getTheme()); setStyle(DialogFragment.STYLE_NORMAL, getTheme());
View view = inflater.inflate(R.layout.careportal_newnstreatment_dialog, container, false); View view = inflater.inflate(R.layout.careportal_newnstreatment_dialog, container, false);
layoutBg = (LinearLayout) view.findViewById(R.id.careportal_newnstreatment_bg_layout);
layoutBgSource = (LinearLayout) view.findViewById(R.id.careportal_newnstreatment_bgsource_layout);
layoutInsulin = (LinearLayout) view.findViewById(R.id.careportal_newnstreatment_insulin_layout);
layoutCarbs = (LinearLayout) view.findViewById(R.id.careportal_newnstreatment_carbs_layout);
layoutSplit = (LinearLayout) view.findViewById(R.id.careportal_newnstreatment_split_layout);
layoutDuration = (LinearLayout) view.findViewById(R.id.careportal_newnstreatment_duration_layout);
layoutPercent = (LinearLayout) view.findViewById(R.id.careportal_newnstreatment_percent_layout); layoutPercent = (LinearLayout) view.findViewById(R.id.careportal_newnstreatment_percent_layout);
layoutAbsolute = (LinearLayout) view.findViewById(R.id.careportal_newnstreatment_absolute_layout); layoutAbsolute = (LinearLayout) view.findViewById(R.id.careportal_newnstreatment_absolute_layout);
layoutCarbTime = (LinearLayout) view.findViewById(R.id.careportal_newnstreatment_carbtime_layout);
layoutProfile = (LinearLayout) view.findViewById(R.id.careportal_newnstreatment_profile_layout); layoutReuse = (LinearLayout) view.findViewById(R.id.careportal_newnstreatment_reuse_layout);
layoutTempTarget = (LinearLayout) view.findViewById(R.id.careportal_newnstreatment_temptarget_layout);
eventTypeText = (TextView) view.findViewById(R.id.careportal_newnstreatment_eventtype); eventTypeText = (TextView) view.findViewById(R.id.careportal_newnstreatment_eventtype);
eventTypeText.setText(event); eventTypeText.setText(event);
@ -164,6 +147,8 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
otherRadioButton = (RadioButton) view.findViewById(R.id.careportal_newnstreatment_other); otherRadioButton = (RadioButton) view.findViewById(R.id.careportal_newnstreatment_other);
profileSpinner = (Spinner) view.findViewById(R.id.careportal_newnstreatment_profile); profileSpinner = (Spinner) view.findViewById(R.id.careportal_newnstreatment_profile);
reuseButton = (Button) view.findViewById(R.id.careportal_newnstreatment_reusebutton);
notesEdit = (EditText) view.findViewById(R.id.careportal_newnstreatment_notes); notesEdit = (EditText) view.findViewById(R.id.careportal_newnstreatment_notes);
reasonSpinner = (Spinner) view.findViewById(R.id.careportal_newnstreatment_temptarget_reason); reasonSpinner = (Spinner) view.findViewById(R.id.careportal_newnstreatment_temptarget_reason);
@ -194,32 +179,60 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
profileSpinner.setSelection(p); profileSpinner.setSelection(p);
} }
final Double bg = Profile.fromMgdlToUnits(GlucoseStatus.getGlucoseStatusData() != null ? GlucoseStatus.getGlucoseStatusData().glucose : 0d, profile != null ? profile.getUnits() : Constants.MGDL);
// temp target // temp target
ArrayList<CharSequence> reasonList = new ArrayList<CharSequence>(); final ArrayList<CharSequence> reasonList = new ArrayList<CharSequence>();
reasonList.add(MainApp.sResources.getString(R.string.manual));
reasonList.add(MainApp.sResources.getString(R.string.eatingsoon)); reasonList.add(MainApp.sResources.getString(R.string.eatingsoon));
reasonList.add(MainApp.sResources.getString(R.string.activity)); reasonList.add(MainApp.sResources.getString(R.string.activity));
reasonList.add(MainApp.sResources.getString(R.string.manual));
ArrayAdapter<CharSequence> adapterReason = new ArrayAdapter<CharSequence>(getContext(), ArrayAdapter<CharSequence> adapterReason = new ArrayAdapter<CharSequence>(getContext(),
R.layout.spinner_centered, reasonList); R.layout.spinner_centered, reasonList);
reasonSpinner.setAdapter(adapterReason); reasonSpinner.setAdapter(adapterReason);
reasonSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
double defaultDuration = 0;
double defaultTarget = 0;
if (profile != null) {
defaultTarget = bg.doubleValue();
}
boolean erase = false;
if (MainApp.sResources.getString(R.string.eatingsoon).equals(reasonList.get(position))) {
defaultDuration = SP.getDouble(R.string.key_eatingsoon_duration, 0d);
defaultTarget = SP.getDouble(R.string.key_eatingsoon_target, 0d);
;
} else if (MainApp.sResources.getString(R.string.activity).equals(reasonList.get(position))) {
defaultDuration = SP.getDouble(R.string.key_activity_duration, 0d);
;
defaultTarget = SP.getDouble(R.string.key_activity_target, 0d);
;
} else {
defaultDuration = 0;
erase = true;
}
if (defaultTarget != 0 || erase) {
editTemptarget.setValue(defaultTarget);
}
if (defaultDuration != 0) {
editDuration.setValue(defaultDuration);
} else if (erase) {
editDuration.setValue(0d);
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
// bg // bg
bgUnitsView.setText(units); bgUnitsView.setText(units);
Double bg = Profile.fromMgdlToUnits(GlucoseStatus.getGlucoseStatusData() != null ? GlucoseStatus.getGlucoseStatusData().glucose : 0d, profile != null ? profile.getUnits() : Constants.MGDL); TextWatcher bgTextWatcher = new TextWatcher() {
editBg = (NumberPicker) view.findViewById(R.id.careportal_newnstreatment_bginput);
editTemptarget = (NumberPicker) view.findViewById(R.id.careportal_newnstreatment_temptarget);
if (profile == null) {
editBg.setParams(bg, 0d, 500d, 0.1d, new DecimalFormat("0.0"), false);
editTemptarget.setParams(bg, 0d, 500d, 0.1d, new DecimalFormat("0.0"), false);
} else if (profile.getUnits().equals(Constants.MMOL)) {
editBg.setParams(bg, 0d, 30d, 0.1d, new DecimalFormat("0.0"), false);
editTemptarget.setParams(bg, 0d, 30d, 0.1d, new DecimalFormat("0.0"), false);
} else {
editBg.setParams(bg, 0d, 500d, 1d, new DecimalFormat("0"), false);
editTemptarget.setParams(bg, 0d, 500d, 1d, new DecimalFormat("0"), false);
}
editBg.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) { public void afterTextChanged(Editable s) {
} }
@ -229,8 +242,20 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
public void onTextChanged(CharSequence s, int start, int before, int count) { public void onTextChanged(CharSequence s, int start, int before, int count) {
if (sensorRadioButton.isChecked()) meterRadioButton.setChecked(true); if (sensorRadioButton.isChecked()) meterRadioButton.setChecked(true);
} }
}); };
editBg = (NumberPicker) view.findViewById(R.id.careportal_newnstreatment_bginput);
editTemptarget = (NumberPicker) view.findViewById(R.id.careportal_newnstreatment_temptarget);
if (profile == null) {
editBg.setParams(bg, 0d, 500d, 0.1d, new DecimalFormat("0.0"), false, bgTextWatcher);
editTemptarget.setParams(bg, 0d, 500d, 0.1d, new DecimalFormat("0.0"), false);
} else if (profile.getUnits().equals(Constants.MMOL)) {
editBg.setParams(bg, 0d, 30d, 0.1d, new DecimalFormat("0.0"), false, bgTextWatcher);
editTemptarget.setParams(bg, 0d, 30d, 0.1d, new DecimalFormat("0.0"), false);
} else {
editBg.setParams(bg, 0d, 500d, 1d, new DecimalFormat("0"), false, bgTextWatcher);
editTemptarget.setParams(bg, 0d, 500d, 1d, new DecimalFormat("0"), false);
}
sensorRadioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { sensorRadioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override @Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
@ -252,10 +277,7 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
editDuration = (NumberPicker) view.findViewById(R.id.careportal_newnstreatment_durationinput); editDuration = (NumberPicker) view.findViewById(R.id.careportal_newnstreatment_durationinput);
editDuration.setParams(0d, 0d, 24 * 60d, 10d, new DecimalFormat("0"), false); editDuration.setParams(0d, 0d, 24 * 60d, 10d, new DecimalFormat("0"), false);
Integer maxPercent = MainApp.getConfigBuilder().applyBasalConstraints(Constants.basalPercentOnlyForCheckLimit); TextWatcher percentTextWatcher = new TextWatcher() {
editPercent = (NumberPicker) view.findViewById(R.id.careportal_newnstreatment_percentinput);
editPercent.setParams(0d, 0d, (double) maxPercent, 5d, new DecimalFormat("0"), true);
editPercent.addTextChangedListener(new TextWatcher() {
@Override @Override
public void afterTextChanged(Editable s) { public void afterTextChanged(Editable s) {
} }
@ -271,12 +293,13 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
layoutPercent.setVisibility(View.VISIBLE); layoutPercent.setVisibility(View.VISIBLE);
layoutAbsolute.setVisibility(View.GONE); layoutAbsolute.setVisibility(View.GONE);
} }
}); };
Double maxAbsolute = MainApp.getConfigBuilder().applyBasalConstraints(Constants.basalAbsoluteOnlyForCheckLimit); Integer maxPercent = MainApp.getConfigBuilder().applyBasalConstraints(Constants.basalPercentOnlyForCheckLimit);
editAbsolute = (NumberPicker) view.findViewById(R.id.careportal_newnstreatment_absoluteinput); editPercent = (NumberPicker) view.findViewById(R.id.careportal_newnstreatment_percentinput);
editAbsolute.setParams(0d, 0d, maxAbsolute, 0.05d, new DecimalFormat("0.00"), true); editPercent.setParams(0d, 0d, (double) maxPercent, 5d, new DecimalFormat("0"), true, percentTextWatcher);
editAbsolute.addTextChangedListener(new TextWatcher() {
TextWatcher absoluteTextWatcher = new TextWatcher() {
@Override @Override
public void afterTextChanged(Editable s) { public void afterTextChanged(Editable s) {
} }
@ -292,23 +315,50 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
layoutPercent.setVisibility(View.GONE); layoutPercent.setVisibility(View.GONE);
layoutAbsolute.setVisibility(View.VISIBLE); layoutAbsolute.setVisibility(View.VISIBLE);
} }
}); };
Double maxAbsolute = MainApp.getConfigBuilder().applyBasalConstraints(Constants.basalAbsoluteOnlyForCheckLimit);
editAbsolute = (NumberPicker) view.findViewById(R.id.careportal_newnstreatment_absoluteinput);
editAbsolute.setParams(0d, 0d, maxAbsolute, 0.05d, new DecimalFormat("0.00"), true, absoluteTextWatcher);
editCarbTime = (NumberPicker) view.findViewById(R.id.careportal_newnstreatment_carbtimeinput); editCarbTime = (NumberPicker) view.findViewById(R.id.careportal_newnstreatment_carbtimeinput);
editCarbTime.setParams(0d, -60d, 60d, 5d, new DecimalFormat("0"), false); editCarbTime.setParams(0d, -60d, 60d, 5d, new DecimalFormat("0"), false);
editPercentage = (NumberPicker) view.findViewById(R.id.careportal_newnstreatment_percentage);
editPercentage.setParams(100d, (double) Constants.CPP_MIN_PERCENTAGE, (double) Constants.CPP_MAX_PERCENTAGE, 1d, new DecimalFormat("0"), false);
showOrHide(layoutBg, options.bg); editTimeshift = (NumberPicker) view.findViewById(R.id.careportal_newnstreatment_timeshift);
showOrHide(layoutBgSource, options.bg); editTimeshift.setParams(0d, (double) Constants.CPP_MIN_TIMESHIFT, (double) Constants.CPP_MAX_TIMESHIFT, 1d, new DecimalFormat("0"), false);
showOrHide(layoutInsulin, options.insulin);
showOrHide(layoutCarbs, options.carbs); ProfileSwitch ps = MainApp.getConfigBuilder().getProfileSwitchFromHistory(System.currentTimeMillis());
showOrHide(layoutSplit, options.split); if (ps != null && ps.isCPP) {
showOrHide(layoutDuration, options.duration); final int percentage = ps.percentage;
final int timeshift = ps.timeshift;
reuseButton.setText(reuseButton.getText() + " " + percentage + "% " + timeshift + "h");
reuseButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
editPercentage.setValue((double) percentage);
editTimeshift.setValue((double) timeshift);
}
});
}
showOrHide((ViewGroup) view.findViewById(R.id.careportal_newnstreatment_eventtime_layout), options.date);
showOrHide((ViewGroup) view.findViewById(R.id.careportal_newnstreatment_bg_layout), options.bg);
showOrHide((ViewGroup) view.findViewById(R.id.careportal_newnstreatment_bgsource_layout), options.bg);
showOrHide((ViewGroup) view.findViewById(R.id.careportal_newnstreatment_insulin_layout), options.insulin);
showOrHide((ViewGroup) view.findViewById(R.id.careportal_newnstreatment_carbs_layout), options.carbs);
showOrHide((ViewGroup) view.findViewById(R.id.careportal_newnstreatment_split_layout), options.split);
showOrHide((ViewGroup) view.findViewById(R.id.careportal_newnstreatment_duration_layout), options.duration);
showOrHide(layoutPercent, options.percent); showOrHide(layoutPercent, options.percent);
showOrHide(layoutAbsolute, options.absolute); showOrHide(layoutAbsolute, options.absolute);
showOrHide(layoutCarbTime, options.prebolus); showOrHide((ViewGroup) view.findViewById(R.id.careportal_newnstreatment_carbtime_layout), options.prebolus);
showOrHide(layoutProfile, options.profile); showOrHide((ViewGroup) view.findViewById(R.id.careportal_newnstreatment_profile_layout), options.profile);
showOrHide(layoutTempTarget, options.tempTarget); showOrHide((ViewGroup) view.findViewById(R.id.careportal_newnstreatment_percentage_layout), options.profile);
showOrHide((ViewGroup) view.findViewById(R.id.careportal_newnstreatment_timeshift_layout), options.profile);
showOrHide((ViewGroup) view.findViewById(R.id.careportal_newnstreatment_reuse_layout), options.profile && ps != null && ps.isCPP);
showOrHide((ViewGroup) view.findViewById(R.id.careportal_newnstreatment_temptarget_layout), options.tempTarget);
return view; return view;
} }
@ -451,7 +501,7 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
allowZeroDuration = true; allowZeroDuration = true;
break; break;
} }
if (SafeParse.stringToDouble(editBg.getText()) != 0d) { if (options.bg && SafeParse.stringToDouble(editBg.getText()) != 0d) {
data.put("glucose", SafeParse.stringToDouble(editBg.getText())); data.put("glucose", SafeParse.stringToDouble(editBg.getText()));
if (meterRadioButton.isChecked()) data.put("glucoseType", "Finger"); if (meterRadioButton.isChecked()) data.put("glucoseType", "Finger");
if (sensorRadioButton.isChecked()) data.put("glucoseType", "Sensor"); if (sensorRadioButton.isChecked()) data.put("glucoseType", "Sensor");
@ -469,6 +519,10 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
data.put("absolute", SafeParse.stringToDouble(editAbsolute.getText())); data.put("absolute", SafeParse.stringToDouble(editAbsolute.getText()));
if (options.profile && profileSpinner.getSelectedItem() != null) if (options.profile && profileSpinner.getSelectedItem() != null)
data.put("profile", profileSpinner.getSelectedItem().toString()); data.put("profile", profileSpinner.getSelectedItem().toString());
if (options.profile)
data.put("percentage", SafeParse.stringToInt(editPercentage.getText()));
if (options.profile)
data.put("timeshift", SafeParse.stringToInt(editTimeshift.getText()));
if (SafeParse.stringToDouble(editCarbTime.getText()) != 0d) if (SafeParse.stringToDouble(editCarbTime.getText()) != 0d)
data.put("preBolus", SafeParse.stringToDouble(editCarbTime.getText())); data.put("preBolus", SafeParse.stringToDouble(editCarbTime.getText()));
if (!notesEdit.getText().toString().equals("")) if (!notesEdit.getText().toString().equals(""))
@ -482,7 +536,7 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
data.put("relative", enteredInsulin * (100 - SafeParse.stringToDouble(editSplit.getText())) / 100 / SafeParse.stringToDouble(editDuration.getText()) * 60); data.put("relative", enteredInsulin * (100 - SafeParse.stringToDouble(editSplit.getText())) / 100 / SafeParse.stringToDouble(editDuration.getText()) * 60);
} }
} catch (JSONException e) { } catch (JSONException e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
return data; return data;
} }
@ -556,6 +610,18 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
ret += data.get("profile"); ret += data.get("profile");
ret += "\n"; ret += "\n";
} }
if (data.has("percentage")) {
ret += getString(R.string.careportal_newnstreatment_percentage_label);
ret += ": ";
ret += data.get("percentage");
ret += " %\n";
}
if (data.has("timeshift")) {
ret += getString(R.string.careportal_newnstreatment_timeshift_label);
ret += ": ";
ret += data.get("timeshift");
ret += " h\n";
}
if (data.has("targetBottom") && data.has("targetTop")) { if (data.has("targetBottom") && data.has("targetTop")) {
ret += getString(R.string.target_range); ret += getString(R.string.target_range);
ret += " "; ret += " ";
@ -577,7 +643,7 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
ret += "\n"; ret += "\n";
} }
} catch (JSONException e) { } catch (JSONException e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
return ret; return ret;
@ -594,42 +660,33 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
if (options.executeProfileSwitch) { if (options.executeProfileSwitch) {
if (data.has("profile")) { if (data.has("profile")) {
try { try {
doProfileSwitch(profileStore, data.getString("profile"), data.getInt("duration")); doProfileSwitch(profileStore, data.getString("profile"), data.getInt("duration"), data.getInt("percentage"), data.getInt("timeshift"));
} catch (JSONException e) { } catch (JSONException e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
} }
} else if (options.executeTempTarget) { } else if (options.executeTempTarget) {
try { try {
if ((data.has("targetBottom") && data.has("targetTop")) || (data.has("duration") && data.getInt("duration") == 0)) { if ((data.has("targetBottom") && data.has("targetTop")) || (data.has("duration") && data.getInt("duration") == 0)) {
sHandler.post(new Runnable() { TempTarget tempTarget = new TempTarget();
@Override tempTarget.date = eventTime.getTime();
public void run() { tempTarget.durationInMinutes = data.getInt("duration");
try { tempTarget.reason = data.getString("reason");
TempTarget tempTarget = new TempTarget(); tempTarget.source = Source.USER;
tempTarget.date = eventTime.getTime(); if (tempTarget.durationInMinutes != 0) {
tempTarget.durationInMinutes = data.getInt("duration"); tempTarget.low = Profile.toMgdl(data.getDouble("targetBottom"), profile.getUnits());
tempTarget.reason = data.getString("reason"); tempTarget.high = Profile.toMgdl(data.getDouble("targetTop"), profile.getUnits());
tempTarget.source = Source.USER; } else {
if (tempTarget.durationInMinutes != 0) { tempTarget.low = 0;
tempTarget.low = Profile.toMgdl(data.getDouble("targetBottom"), profile.getUnits()); tempTarget.high = 0;
tempTarget.high = Profile.toMgdl(data.getDouble("targetTop"), profile.getUnits()); }
} else { log.debug("Creating new TempTarget db record: " + tempTarget.toString());
tempTarget.low = 0; MainApp.getDbHelper().createOrUpdate(tempTarget);
tempTarget.high = 0; NSUpload.uploadCareportalEntryToNS(data);
} Answers.getInstance().logCustom(new CustomEvent("TempTarget"));
log.debug("Creating new TempTarget db record: " + tempTarget.toString());
MainApp.getDbHelper().createOrUpdate(tempTarget);
NSUpload.uploadCareportalEntryToNS(data);
Answers.getInstance().logCustom(new CustomEvent("TempTarget"));
} catch (JSONException e) {
e.printStackTrace();
}
}
});
} }
} catch (JSONException e) { } catch (JSONException e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
} else { } else {
NSUpload.uploadCareportalEntryToNS(data); NSUpload.uploadCareportalEntryToNS(data);
@ -641,35 +698,69 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
builder.show(); builder.show();
} }
public static void doProfileSwitch(final ProfileStore profileStore, final String profileName, final int duration) { public static void doProfileSwitch(final ProfileStore profileStore, final String profileName, final int duration, final int percentage, final int timeshift) {
sHandler.post(new Runnable() { ProfileSwitch profileSwitch = new ProfileSwitch();
profileSwitch.date = System.currentTimeMillis();
profileSwitch.source = Source.USER;
profileSwitch.profileName = profileName;
profileSwitch.profileJson = profileStore.getSpecificProfile(profileName).getData().toString();
profileSwitch.profilePlugin = ConfigBuilderPlugin.getActiveProfileInterface().getClass().getName();
profileSwitch.durationInMinutes = duration;
profileSwitch.isCPP = percentage != 100 || timeshift != 0;
profileSwitch.timeshift = timeshift;
profileSwitch.percentage = percentage;
MainApp.getConfigBuilder().addToHistoryProfileSwitch(profileSwitch);
ConfigBuilderPlugin.getCommandQueue().setProfile(profileSwitch.getProfileObject(), new Callback() {
@Override @Override
public void run() { public void run() {
ProfileSwitch profileSwitch = new ProfileSwitch(); if (!result.success) {
profileSwitch.date = System.currentTimeMillis(); Intent i = new Intent(MainApp.instance(), ErrorHelperActivity.class);
profileSwitch.source = Source.USER; i.putExtra("soundid", R.raw.boluserror);
profileSwitch.profileName = profileName; i.putExtra("status", result.comment);
profileSwitch.profileJson = profileStore.getSpecificProfile(profileName).getData().toString(); i.putExtra("title", MainApp.sResources.getString(R.string.failedupdatebasalprofile));
profileSwitch.profilePlugin = ConfigBuilderPlugin.getActiveProfileInterface().getClass().getName(); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
profileSwitch.durationInMinutes = duration; MainApp.instance().startActivity(i);
if (ConfigBuilderPlugin.getActiveProfileInterface() instanceof CircadianPercentageProfilePlugin) { }
CircadianPercentageProfilePlugin cpp = (CircadianPercentageProfilePlugin) ConfigBuilderPlugin.getActiveProfileInterface(); MainApp.bus().post(new EventNewBasalProfile());
profileSwitch.isCPP = true;
profileSwitch.timeshift = cpp.timeshift;
profileSwitch.percentage = cpp.percentage;
}
MainApp.getConfigBuilder().addToHistoryProfileSwitch(profileSwitch);
PumpInterface pump = MainApp.getConfigBuilder();
if (pump != null) {
pump.setNewBasalProfile(profileStore.getSpecificProfile(profileName));
MainApp.bus().post(new EventNewBasalProfile());
} else {
log.error("No active pump selected");
}
Answers.getInstance().logCustom(new CustomEvent("ProfileSwitch"));
} }
}); });
Answers.getInstance().logCustom(new CustomEvent("ProfileSwitch"));
}
public static void doProfileSwitch(final int duration, final int percentage, final int timeshift) {
ProfileSwitch profileSwitch = MainApp.getConfigBuilder().getProfileSwitchFromHistory(System.currentTimeMillis());
if (profileSwitch != null) {
profileSwitch = new ProfileSwitch();
profileSwitch.date = System.currentTimeMillis();
profileSwitch.source = Source.USER;
profileSwitch.profileName = MainApp.getConfigBuilder().getProfileName(System.currentTimeMillis(), false);
profileSwitch.profileJson = MainApp.getConfigBuilder().getProfile().getData().toString();
profileSwitch.profilePlugin = ConfigBuilderPlugin.getActiveProfileInterface().getClass().getName();
profileSwitch.durationInMinutes = duration;
profileSwitch.isCPP = percentage != 100 || timeshift != 0;
profileSwitch.timeshift = timeshift;
profileSwitch.percentage = percentage;
MainApp.getConfigBuilder().addToHistoryProfileSwitch(profileSwitch);
ConfigBuilderPlugin.getCommandQueue().setProfile(profileSwitch.getProfileObject(), new Callback() {
@Override
public void run() {
if (!result.success) {
Intent i = new Intent(MainApp.instance(), ErrorHelperActivity.class);
i.putExtra("soundid", R.raw.boluserror);
i.putExtra("status", result.comment);
i.putExtra("title", MainApp.sResources.getString(R.string.failedupdatebasalprofile));
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
MainApp.instance().startActivity(i);
}
MainApp.bus().post(new EventNewBasalProfile());
}
});
Answers.getInstance().logCustom(new CustomEvent("ProfileSwitch"));
} else {
log.error("No profile switch existing");
}
} }
} }

View file

@ -7,6 +7,7 @@ package info.nightscout.androidaps.plugins.Careportal;
public class OptionsToShow { public class OptionsToShow {
public int eventType; public int eventType;
public int eventName; public int eventName;
public boolean date;
public boolean bg; public boolean bg;
public boolean insulin; public boolean insulin;
public boolean carbs; public boolean carbs;
@ -22,29 +23,63 @@ public class OptionsToShow {
public boolean executeProfileSwitch = false; public boolean executeProfileSwitch = false;
public boolean executeTempTarget = false; public boolean executeTempTarget = false;
public OptionsToShow(int eventType, public OptionsToShow(int eventType, int eventName) {
int eventName,
boolean bg,
boolean insulin,
boolean carbs,
boolean prebolus,
boolean duration,
boolean percent,
boolean absolute,
boolean profile,
boolean split,
boolean tempTarget) {
this.eventType = eventType; this.eventType = eventType;
this.eventName = eventName; this.eventName = eventName;
this.bg = bg; }
this.insulin = insulin;
this.carbs = carbs; public OptionsToShow date() {
this.prebolus = prebolus; date = true;
this.duration = duration; return this;
this.percent = percent; }
this.absolute = absolute;
this.profile = profile; public OptionsToShow bg() {
this.split = split; bg = true;
this.tempTarget = tempTarget; return this;
}
public OptionsToShow insulin() {
insulin = true;
return this;
}
public OptionsToShow carbs() {
carbs = true;
return this;
}
public OptionsToShow prebolus() {
prebolus = true;
return this;
}
public OptionsToShow duration() {
duration = true;
return this;
}
public OptionsToShow percent() {
percent = true;
return this;
}
public OptionsToShow absolute() {
absolute = true;
return this;
}
public OptionsToShow profile() {
profile = true;
return this;
}
public OptionsToShow split() {
split = true;
return this;
}
public OptionsToShow tempTarget() {
tempTarget = true;
return this;
} }
} }

View file

@ -2,28 +2,29 @@ package info.nightscout.androidaps.plugins.ConfigBuilder;
import android.content.Context; import android.content.Context;
import android.graphics.Color; import android.content.Intent;
import android.os.Bundle; import android.os.Bundle;
import android.support.v4.app.Fragment; import android.support.v4.app.Fragment;
import android.util.DisplayMetrics;
import android.view.LayoutInflater; import android.view.LayoutInflater;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
import android.widget.ArrayAdapter; import android.widget.ArrayAdapter;
import android.widget.Button; import android.widget.Button;
import android.widget.CheckBox; import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout; import android.widget.LinearLayout;
import android.widget.ListAdapter; import android.widget.ListAdapter;
import android.widget.ListView; import android.widget.ListView;
import android.widget.TextView; import android.widget.TextView;
import com.crashlytics.android.Crashlytics;
import com.crashlytics.android.answers.Answers; import com.crashlytics.android.answers.Answers;
import com.crashlytics.android.answers.CustomEvent; import com.crashlytics.android.answers.CustomEvent;
import java.util.ArrayList; import java.util.ArrayList;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.PreferencesActivity;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.events.EventConfigBuilderChange; import info.nightscout.androidaps.events.EventConfigBuilderChange;
import info.nightscout.androidaps.events.EventRefreshGui; import info.nightscout.androidaps.events.EventRefreshGui;
@ -35,7 +36,7 @@ import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.ProfileInterface; import info.nightscout.androidaps.interfaces.ProfileInterface;
import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.interfaces.SensitivityInterface; import info.nightscout.androidaps.interfaces.SensitivityInterface;
import info.nightscout.androidaps.plugins.InsulinFastacting.InsulinFastactingPlugin; import info.nightscout.androidaps.plugins.Insulin.InsulinFastactingPlugin;
import info.nightscout.androidaps.plugins.ProfileNS.NSProfilePlugin; import info.nightscout.androidaps.plugins.ProfileNS.NSProfilePlugin;
import info.nightscout.androidaps.plugins.PumpVirtual.VirtualPumpPlugin; import info.nightscout.androidaps.plugins.PumpVirtual.VirtualPumpPlugin;
import info.nightscout.androidaps.plugins.SensitivityOref0.SensitivityOref0Plugin; import info.nightscout.androidaps.plugins.SensitivityOref0.SensitivityOref0Plugin;
@ -76,113 +77,109 @@ public class ConfigBuilderFragment extends Fragment {
PluginCustomAdapter bgsourceDataAdapter = null; PluginCustomAdapter bgsourceDataAdapter = null;
PluginCustomAdapter pumpDataAdapter = null; PluginCustomAdapter pumpDataAdapter = null;
PluginCustomAdapter loopDataAdapter = null; PluginCustomAdapter loopDataAdapter = null;
PluginCustomAdapter treatmentsDataAdapter = null; PluginCustomAdapter treatmentDataAdapter = null;
PluginCustomAdapter profileDataAdapter = null; PluginCustomAdapter profileDataAdapter = null;
PluginCustomAdapter apsDataAdapter = null; PluginCustomAdapter apsDataAdapter = null;
PluginCustomAdapter constraintsDataAdapter = null; PluginCustomAdapter constraintsDataAdapter = null;
PluginCustomAdapter generalDataAdapter = null; PluginCustomAdapter generalDataAdapter = null;
boolean smallWidth;
// TODO: sorting
@Override @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) { Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.configbuilder_fragment, container, false); try {
View view = inflater.inflate(R.layout.configbuilder_fragment, container, false);
//check screen width insulinListView = (ListView) view.findViewById(R.id.configbuilder_insulinlistview);
final DisplayMetrics dm = new DisplayMetrics(); sensitivityListView = (ListView) view.findViewById(R.id.configbuilder_sensitivitylistview);
getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm); bgsourceListView = (ListView) view.findViewById(R.id.configbuilder_bgsourcelistview);
int screen_width = dm.widthPixels; bgsourceLabel = (TextView) view.findViewById(R.id.configbuilder_bgsourcelabel);
smallWidth = screen_width < Constants.SMALL_WIDTH; pumpListView = (ListView) view.findViewById(R.id.configbuilder_pumplistview);
pumpLabel = (TextView) view.findViewById(R.id.configbuilder_pumplabel);
loopListView = (ListView) view.findViewById(R.id.configbuilder_looplistview);
loopLabel = (TextView) view.findViewById(R.id.configbuilder_looplabel);
treatmentsListView = (ListView) view.findViewById(R.id.configbuilder_treatmentslistview);
treatmentsLabel = (TextView) view.findViewById(R.id.configbuilder_treatmentslabel);
profileListView = (ListView) view.findViewById(R.id.configbuilder_profilelistview);
profileLabel = (TextView) view.findViewById(R.id.configbuilder_profilelabel);
apsListView = (ListView) view.findViewById(R.id.configbuilder_apslistview);
apsLabel = (TextView) view.findViewById(R.id.configbuilder_apslabel);
constraintsListView = (ListView) view.findViewById(R.id.configbuilder_constraintslistview);
constraintsLabel = (TextView) view.findViewById(R.id.configbuilder_constraintslabel);
generalListView = (ListView) view.findViewById(R.id.configbuilder_generallistview);
insulinListView = (ListView) view.findViewById(R.id.configbuilder_insulinlistview); mainLayout = (LinearLayout) view.findViewById(R.id.configbuilder_mainlayout);
sensitivityListView = (ListView) view.findViewById(R.id.configbuilder_sensitivitylistview); unlock = (Button) view.findViewById(R.id.configbuilder_unlock);
bgsourceListView = (ListView) view.findViewById(R.id.configbuilder_bgsourcelistview);
bgsourceLabel = (TextView) view.findViewById(R.id.configbuilder_bgsourcelabel);
pumpListView = (ListView) view.findViewById(R.id.configbuilder_pumplistview);
pumpLabel = (TextView) view.findViewById(R.id.configbuilder_pumplabel);
loopListView = (ListView) view.findViewById(R.id.configbuilder_looplistview);
loopLabel = (TextView) view.findViewById(R.id.configbuilder_looplabel);
treatmentsListView = (ListView) view.findViewById(R.id.configbuilder_treatmentslistview);
treatmentsLabel = (TextView) view.findViewById(R.id.configbuilder_treatmentslabel);
profileListView = (ListView) view.findViewById(R.id.configbuilder_profilelistview);
profileLabel = (TextView) view.findViewById(R.id.configbuilder_profilelabel);
apsListView = (ListView) view.findViewById(R.id.configbuilder_apslistview);
apsLabel = (TextView) view.findViewById(R.id.configbuilder_apslabel);
constraintsListView = (ListView) view.findViewById(R.id.configbuilder_constraintslistview);
constraintsLabel = (TextView) view.findViewById(R.id.configbuilder_constraintslabel);
generalListView = (ListView) view.findViewById(R.id.configbuilder_generallistview);
mainLayout = (LinearLayout) view.findViewById(R.id.configbuilder_mainlayout); setViews();
unlock = (Button) view.findViewById(R.id.configbuilder_unlock);
setViews(); if (PasswordProtection.isLocked("settings_password")) {
mainLayout.setVisibility(View.GONE);
if (PasswordProtection.isLocked("settings_password")) { unlock.setOnClickListener(new View.OnClickListener() {
mainLayout.setVisibility(View.GONE); @Override
unlock.setOnClickListener(new View.OnClickListener() { public void onClick(View v) {
@Override PasswordProtection.QueryPassword(getContext(), R.string.settings_password, "settings_password", new Runnable() {
public void onClick(View v) { @Override
PasswordProtection.QueryPassword(getContext(), R.string.settings_password, "settings_password", new Runnable() { public void run() {
@Override mainLayout.setVisibility(View.VISIBLE);
public void run() { unlock.setVisibility(View.GONE);
mainLayout.setVisibility(View.VISIBLE); }
unlock.setVisibility(View.GONE); }, null);
} }
}, null); });
} } else {
}); unlock.setVisibility(View.GONE);
} else { }
unlock.setVisibility(View.GONE); return view;
} catch (Exception e) {
Crashlytics.logException(e);
} }
return view;
return null;
} }
void setViews() { void setViews() {
insulinDataAdapter = new PluginCustomAdapter(getContext(), smallWidth?R.layout.configbuilder_smallitem :R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsVisibleInListByInterface(InsulinInterface.class, PluginBase.INSULIN), PluginBase.INSULIN); insulinDataAdapter = new PluginCustomAdapter(getContext(), R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsVisibleInListByInterface(InsulinInterface.class, PluginBase.INSULIN), PluginBase.INSULIN);
insulinListView.setAdapter(insulinDataAdapter); insulinListView.setAdapter(insulinDataAdapter);
setListViewHeightBasedOnChildren(insulinListView); setListViewHeightBasedOnChildren(insulinListView);
bgsourceDataAdapter = new PluginCustomAdapter(getContext(), smallWidth?R.layout.configbuilder_smallitem :R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsVisibleInListByInterface(BgSourceInterface.class, PluginBase.BGSOURCE), PluginBase.BGSOURCE); bgsourceDataAdapter = new PluginCustomAdapter(getContext(), R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsVisibleInListByInterface(BgSourceInterface.class, PluginBase.BGSOURCE), PluginBase.BGSOURCE);
bgsourceListView.setAdapter(bgsourceDataAdapter); bgsourceListView.setAdapter(bgsourceDataAdapter);
if (MainApp.getSpecificPluginsVisibleInList(PluginBase.BGSOURCE).size() == 0) if (MainApp.getSpecificPluginsVisibleInList(PluginBase.BGSOURCE).size() == 0)
bgsourceLabel.setVisibility(View.GONE); bgsourceLabel.setVisibility(View.GONE);
setListViewHeightBasedOnChildren(bgsourceListView); setListViewHeightBasedOnChildren(bgsourceListView);
pumpDataAdapter = new PluginCustomAdapter(getContext(), smallWidth?R.layout.configbuilder_smallitem :R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsVisibleInList(PluginBase.PUMP), PluginBase.PUMP); pumpDataAdapter = new PluginCustomAdapter(getContext(), R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsVisibleInList(PluginBase.PUMP), PluginBase.PUMP);
pumpListView.setAdapter(pumpDataAdapter); pumpListView.setAdapter(pumpDataAdapter);
if (MainApp.getSpecificPluginsVisibleInList(PluginBase.PUMP).size() == 0) if (MainApp.getSpecificPluginsVisibleInList(PluginBase.PUMP).size() == 0)
pumpLabel.setVisibility(View.GONE); pumpLabel.setVisibility(View.GONE);
setListViewHeightBasedOnChildren(pumpListView); setListViewHeightBasedOnChildren(pumpListView);
loopDataAdapter = new PluginCustomAdapter(getContext(), smallWidth?R.layout.configbuilder_smallitem :R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsVisibleInList(PluginBase.LOOP), PluginBase.LOOP); loopDataAdapter = new PluginCustomAdapter(getContext(), R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsVisibleInList(PluginBase.LOOP), PluginBase.LOOP);
loopListView.setAdapter(loopDataAdapter); loopListView.setAdapter(loopDataAdapter);
setListViewHeightBasedOnChildren(loopListView); setListViewHeightBasedOnChildren(loopListView);
if (MainApp.getSpecificPluginsVisibleInList(PluginBase.LOOP).size() == 0) if (MainApp.getSpecificPluginsVisibleInList(PluginBase.LOOP).size() == 0)
loopLabel.setVisibility(View.GONE); loopLabel.setVisibility(View.GONE);
treatmentsDataAdapter = new PluginCustomAdapter(getContext(), smallWidth?R.layout.configbuilder_smallitem :R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsVisibleInList(PluginBase.TREATMENT), PluginBase.TREATMENT); treatmentDataAdapter = new PluginCustomAdapter(getContext(), R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsVisibleInList(PluginBase.TREATMENT), PluginBase.TREATMENT);
treatmentsListView.setAdapter(treatmentsDataAdapter); treatmentsListView.setAdapter(treatmentDataAdapter);
setListViewHeightBasedOnChildren(treatmentsListView);
if (MainApp.getSpecificPluginsVisibleInList(PluginBase.TREATMENT).size() == 0) if (MainApp.getSpecificPluginsVisibleInList(PluginBase.TREATMENT).size() == 0)
treatmentsLabel.setVisibility(View.GONE); treatmentsLabel.setVisibility(View.GONE);
setListViewHeightBasedOnChildren(treatmentsListView); profileDataAdapter = new PluginCustomAdapter(getContext(), R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsVisibleInListByInterface(ProfileInterface.class, PluginBase.PROFILE), PluginBase.PROFILE);
profileDataAdapter = new PluginCustomAdapter(getContext(), smallWidth?R.layout.configbuilder_smallitem :R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsVisibleInListByInterface(ProfileInterface.class, PluginBase.PROFILE), PluginBase.PROFILE);
profileListView.setAdapter(profileDataAdapter); profileListView.setAdapter(profileDataAdapter);
if (MainApp.getSpecificPluginsVisibleInList(PluginBase.PROFILE).size() == 0) if (MainApp.getSpecificPluginsVisibleInList(PluginBase.PROFILE).size() == 0)
profileLabel.setVisibility(View.GONE); profileLabel.setVisibility(View.GONE);
setListViewHeightBasedOnChildren(profileListView); setListViewHeightBasedOnChildren(profileListView);
apsDataAdapter = new PluginCustomAdapter(getContext(), smallWidth?R.layout.configbuilder_smallitem :R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsVisibleInList(PluginBase.APS), PluginBase.APS); apsDataAdapter = new PluginCustomAdapter(getContext(), R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsVisibleInList(PluginBase.APS), PluginBase.APS);
apsListView.setAdapter(apsDataAdapter); apsListView.setAdapter(apsDataAdapter);
setListViewHeightBasedOnChildren(apsListView); setListViewHeightBasedOnChildren(apsListView);
if (MainApp.getSpecificPluginsVisibleInList(PluginBase.APS).size() == 0) if (MainApp.getSpecificPluginsVisibleInList(PluginBase.APS).size() == 0)
apsLabel.setVisibility(View.GONE); apsLabel.setVisibility(View.GONE);
sensivityDataAdapter = new PluginCustomAdapter(getContext(), smallWidth?R.layout.configbuilder_smallitem :R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsVisibleInListByInterface(SensitivityInterface.class, PluginBase.SENSITIVITY), PluginBase.SENSITIVITY); sensivityDataAdapter = new PluginCustomAdapter(getContext(), R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsVisibleInListByInterface(SensitivityInterface.class, PluginBase.SENSITIVITY), PluginBase.SENSITIVITY);
sensitivityListView.setAdapter(sensivityDataAdapter); sensitivityListView.setAdapter(sensivityDataAdapter);
setListViewHeightBasedOnChildren(sensitivityListView); setListViewHeightBasedOnChildren(sensitivityListView);
constraintsDataAdapter = new PluginCustomAdapter(getContext(), smallWidth?R.layout.configbuilder_smallitem :R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsVisibleInListByInterface(ConstraintsInterface.class, PluginBase.CONSTRAINTS), PluginBase.CONSTRAINTS); constraintsDataAdapter = new PluginCustomAdapter(getContext(), R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsVisibleInListByInterface(ConstraintsInterface.class, PluginBase.CONSTRAINTS), PluginBase.CONSTRAINTS);
constraintsListView.setAdapter(constraintsDataAdapter); constraintsListView.setAdapter(constraintsDataAdapter);
setListViewHeightBasedOnChildren(constraintsListView); setListViewHeightBasedOnChildren(constraintsListView);
if (MainApp.getSpecificPluginsVisibleInList(PluginBase.CONSTRAINTS).size() == 0) if (MainApp.getSpecificPluginsVisibleInList(PluginBase.CONSTRAINTS).size() == 0)
constraintsLabel.setVisibility(View.GONE); constraintsLabel.setVisibility(View.GONE);
generalDataAdapter = new PluginCustomAdapter(getContext(), smallWidth?R.layout.configbuilder_smallitem :R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsVisibleInList(PluginBase.GENERAL), PluginBase.GENERAL); generalDataAdapter = new PluginCustomAdapter(getContext(), R.layout.configbuilder_simpleitem, MainApp.getSpecificPluginsVisibleInList(PluginBase.GENERAL), PluginBase.GENERAL);
generalListView.setAdapter(generalDataAdapter); generalListView.setAdapter(generalDataAdapter);
setListViewHeightBasedOnChildren(generalListView); setListViewHeightBasedOnChildren(generalListView);
@ -200,7 +197,7 @@ public class ConfigBuilderFragment extends Fragment {
public PluginCustomAdapter(Context context, int textViewResourceId, public PluginCustomAdapter(Context context, int textViewResourceId,
ArrayList<PluginBase> pluginList, int type) { ArrayList<PluginBase> pluginList, int type) {
super(context, textViewResourceId, pluginList); super(context, textViewResourceId, pluginList);
this.pluginList = new ArrayList<PluginBase>(); this.pluginList = new ArrayList<>();
this.pluginList.addAll(pluginList); this.pluginList.addAll(pluginList);
this.type = type; this.type = type;
} }
@ -209,20 +206,29 @@ public class ConfigBuilderFragment extends Fragment {
TextView name; TextView name;
CheckBox checkboxEnabled; CheckBox checkboxEnabled;
CheckBox checkboxVisible; CheckBox checkboxVisible;
ImageView settings;
} }
@Override @Override
public View getView(int position, View view, ViewGroup parent) { public View getView(int position, View view, ViewGroup parent) {
PluginViewHolder holder = null; PluginViewHolder holder = null;
PluginBase plugin = pluginList.get(position);
if (view == null) { if (view == null) {
view = LayoutInflater.from(parent.getContext()).inflate(smallWidth?R.layout.configbuilder_smallitem :R.layout.configbuilder_simpleitem, null); view = LayoutInflater.from(parent.getContext()).inflate(R.layout.configbuilder_simpleitem, null);
holder = new PluginViewHolder(); holder = new PluginViewHolder();
holder.name = (TextView) view.findViewById(R.id.configbuilder_simpleitem_name); holder.name = (TextView) view.findViewById(R.id.configbuilder_simpleitem_name);
holder.checkboxEnabled = (CheckBox) view.findViewById(R.id.configbuilder_simpleitem_checkboxenabled); holder.checkboxEnabled = (CheckBox) view.findViewById(R.id.configbuilder_simpleitem_checkboxenabled);
holder.checkboxVisible = (CheckBox) view.findViewById(R.id.configbuilder_simpleitem_checkboxvisible); holder.checkboxVisible = (CheckBox) view.findViewById(R.id.configbuilder_simpleitem_checkboxvisible);
holder.settings = (ImageView) view.findViewById(R.id.configbuilder_simpleitem_settings);
if (plugin.isEnabled(type) && plugin.getPreferencesId() != -1)
holder.settings.setVisibility(View.VISIBLE);
else
holder.settings.setVisibility(View.INVISIBLE);
view.setTag(holder); view.setTag(holder);
holder.checkboxEnabled.setOnClickListener(new View.OnClickListener() { holder.checkboxEnabled.setOnClickListener(new View.OnClickListener() {
@ -250,17 +256,48 @@ public class ConfigBuilderFragment extends Fragment {
getPlugin().logPluginStatus(); getPlugin().logPluginStatus();
} }
}); });
holder.settings.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
final PluginBase plugin = (PluginBase) v.getTag();
PasswordProtection.QueryPassword(getContext(), R.string.settings_password, "settings_password", new Runnable() {
@Override
public void run() {
Intent i = new Intent(getContext(), PreferencesActivity.class);
i.putExtra("id", plugin.getPreferencesId());
startActivity(i);
}
}, null);
}
});
holder.name.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
final PluginBase plugin = (PluginBase) v.getTag();
PasswordProtection.QueryPassword(getContext(), R.string.settings_password, "settings_password", new Runnable() {
@Override
public void run() {
Intent i = new Intent(getContext(), PreferencesActivity.class);
i.putExtra("id", plugin.getPreferencesId());
startActivity(i);
}
}, null);
return false;
}
});
} else { } else {
holder = (PluginViewHolder) view.getTag(); holder = (PluginViewHolder) view.getTag();
} }
PluginBase plugin = pluginList.get(position);
holder.name.setText(plugin.getName()); holder.name.setText(plugin.getName());
holder.checkboxEnabled.setChecked(plugin.isEnabled(type)); holder.checkboxEnabled.setChecked(plugin.isEnabled(type));
holder.checkboxVisible.setChecked(plugin.isVisibleInTabs(type)); holder.checkboxVisible.setChecked(plugin.isVisibleInTabs(type));
holder.name.setTag(plugin); holder.name.setTag(plugin);
holder.checkboxEnabled.setTag(plugin); holder.checkboxEnabled.setTag(plugin);
holder.checkboxVisible.setTag(plugin); holder.checkboxVisible.setTag(plugin);
holder.settings.setTag(plugin);
if (!plugin.canBeHidden(type)) { if (!plugin.canBeHidden(type)) {
holder.checkboxEnabled.setEnabled(false); holder.checkboxEnabled.setEnabled(false);
@ -307,6 +344,10 @@ public class ConfigBuilderFragment extends Fragment {
} }
} }
if (plugin.isEnabled(type)) {
view.setBackgroundColor(MainApp.sResources.getColor(R.color.configBuilderSelectedBackground));
}
return view; return view;
} }

View file

@ -1,12 +1,8 @@
package info.nightscout.androidaps.plugins.ConfigBuilder; package info.nightscout.androidaps.plugins.ConfigBuilder;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences; import android.content.SharedPreferences;
import android.os.PowerManager;
import android.preference.PreferenceManager; import android.preference.PreferenceManager;
import android.support.annotation.Nullable; import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
@ -14,7 +10,6 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Date;
import java.util.List; import java.util.List;
import info.nightscout.androidaps.Config; import info.nightscout.androidaps.Config;
@ -32,33 +27,29 @@ import info.nightscout.androidaps.db.ProfileSwitch;
import info.nightscout.androidaps.db.TempTarget; import info.nightscout.androidaps.db.TempTarget;
import info.nightscout.androidaps.db.TemporaryBasal; import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.db.Treatment; import info.nightscout.androidaps.db.Treatment;
import info.nightscout.androidaps.events.EventBolusRequested;
import info.nightscout.androidaps.interfaces.APSInterface; import info.nightscout.androidaps.interfaces.APSInterface;
import info.nightscout.androidaps.interfaces.BgSourceInterface; import info.nightscout.androidaps.interfaces.BgSourceInterface;
import info.nightscout.androidaps.interfaces.ConstraintsInterface; import info.nightscout.androidaps.interfaces.ConstraintsInterface;
import info.nightscout.androidaps.interfaces.InsulinInterface; import info.nightscout.androidaps.interfaces.InsulinInterface;
import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.ProfileInterface; import info.nightscout.androidaps.interfaces.ProfileInterface;
import info.nightscout.androidaps.interfaces.PumpDescription;
import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.interfaces.SensitivityInterface; import info.nightscout.androidaps.interfaces.SensitivityInterface;
import info.nightscout.androidaps.interfaces.TreatmentsInterface; import info.nightscout.androidaps.interfaces.TreatmentsInterface;
import info.nightscout.androidaps.plugins.Loop.APSResult; import info.nightscout.androidaps.plugins.Loop.APSResult;
import info.nightscout.androidaps.plugins.Loop.LoopPlugin; import info.nightscout.androidaps.plugins.Loop.LoopPlugin;
import info.nightscout.androidaps.plugins.Overview.Dialogs.BolusProgressDialog; import info.nightscout.androidaps.plugins.Overview.notifications.Notification;
import info.nightscout.androidaps.plugins.Overview.Dialogs.BolusProgressHelperActivity;
import info.nightscout.androidaps.plugins.Overview.Notification;
import info.nightscout.androidaps.plugins.Overview.events.EventDismissBolusprogressIfRunning;
import info.nightscout.androidaps.plugins.Overview.events.EventDismissNotification;
import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification; import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.PumpVirtual.VirtualPumpPlugin; import info.nightscout.androidaps.plugins.PumpVirtual.VirtualPumpPlugin;
import info.nightscout.androidaps.queue.Callback;
import info.nightscout.androidaps.queue.CommandQueue;
import info.nightscout.utils.NSUpload; import info.nightscout.utils.NSUpload;
import info.nightscout.utils.SP; import info.nightscout.utils.SP;
/** /**
* Created by mike on 05.08.2016. * Created by mike on 05.08.2016.
*/ */
public class ConfigBuilderPlugin implements PluginBase, PumpInterface, ConstraintsInterface, TreatmentsInterface { public class ConfigBuilderPlugin implements PluginBase, ConstraintsInterface, TreatmentsInterface {
private static Logger log = LoggerFactory.getLogger(ConfigBuilderPlugin.class); private static Logger log = LoggerFactory.getLogger(ConfigBuilderPlugin.class);
private static BgSourceInterface activeBgSource; private static BgSourceInterface activeBgSource;
@ -77,12 +68,10 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain
private static ArrayList<PluginBase> pluginList; private static ArrayList<PluginBase> pluginList;
private PowerManager.WakeLock mWakeLock; private static CommandQueue commandQueue = new CommandQueue();
public ConfigBuilderPlugin() { public ConfigBuilderPlugin() {
MainApp.bus().register(this); MainApp.bus().register(this);
PowerManager powerManager = (PowerManager) MainApp.instance().getApplicationContext().getSystemService(Context.POWER_SERVICE);
mWakeLock = powerManager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "ConfigBuilderPlugin");
} }
@Override @Override
@ -146,6 +135,11 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain
// Always visible // Always visible
} }
@Override
public int getPreferencesId() {
return -1;
}
public void initialize() { public void initialize() {
pluginList = MainApp.getPluginsList(); pluginList = MainApp.getPluginsList();
loadSettings(); loadSettings();
@ -185,13 +179,17 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain
if (SP.contains(settingVisible)) if (SP.contains(settingVisible))
p.setFragmentVisible(type, SP.getBoolean(settingVisible, true) && SP.getBoolean(settingEnabled, true)); p.setFragmentVisible(type, SP.getBoolean(settingVisible, true) && SP.getBoolean(settingEnabled, true));
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
} }
} }
verifySelectionInCategories(); verifySelectionInCategories();
} }
public static CommandQueue getCommandQueue() {
return commandQueue;
}
public static BgSourceInterface getActiveBgSource() { public static BgSourceInterface getActiveBgSource() {
return activeBgSource; return activeBgSource;
} }
@ -216,7 +214,7 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain
return activePump; return activePump;
} }
public static SensitivityInterface getActiveSensitivity() { public static SensitivityInterface getActiveSensitivity() {
return activeSensitivity; return activeSensitivity;
} }
@ -301,7 +299,7 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain
pluginsInCategory = MainApp.getSpecificPluginsList(PluginBase.PUMP); pluginsInCategory = MainApp.getSpecificPluginsList(PluginBase.PUMP);
activePump = (PumpInterface) getTheOneEnabledInArray(pluginsInCategory, PluginBase.PUMP); activePump = (PumpInterface) getTheOneEnabledInArray(pluginsInCategory, PluginBase.PUMP);
if (activePump == null) if (activePump == null)
activePump = VirtualPumpPlugin.getInstance(); // for NSClient build activePump = VirtualPumpPlugin.getPlugin(); // for NSClient build
if (Config.logConfigBuilder) if (Config.logConfigBuilder)
log.debug("Selected pump interface: " + ((PluginBase) activePump).getName()); log.debug("Selected pump interface: " + ((PluginBase) activePump).getName());
for (PluginBase p : pluginsInCategory) { for (PluginBase p : pluginsInCategory) {
@ -353,259 +351,77 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain
} }
/* /*
* Pump interface * Ex Pump interface
* *
* Config builder return itself as a pump and check constraints before it passes command to pump driver * Config builder return itself as a pump and check constraints before it passes command to pump driver
*/ */
@Override
public boolean isInitialized() {
if (activePump != null)
return activePump.isInitialized();
else return true;
}
@Override
public boolean isSuspended() {
if (activePump != null)
return activePump.isSuspended();
else return false;
}
@Override
public boolean isBusy() {
if (activePump != null)
return activePump.isBusy();
else return false;
}
@Override
public int setNewBasalProfile(Profile profile) {
// Compare with pump limits
Profile.BasalValue[] basalValues = profile.getBasalValues();
for (int index = 0; index < basalValues.length; index++) {
if (basalValues[index].value < getPumpDescription().basalMinimumRate) {
Notification notification = new Notification(Notification.BASAL_VALUE_BELOW_MINIMUM, MainApp.sResources.getString(R.string.basalvaluebelowminimum), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(notification));
return FAILED;
}
}
MainApp.bus().post(new EventDismissNotification(Notification.BASAL_VALUE_BELOW_MINIMUM));
if (isThisProfileSet(profile)) {
log.debug("Correct profile already set");
return NOT_NEEDED;
} else if (activePump != null) {
return activePump.setNewBasalProfile(profile);
} else
return SUCCESS;
}
@Override
public boolean isThisProfileSet(Profile profile) {
if (activePump != null)
return activePump.isThisProfileSet(profile);
else return true;
}
@Override
public Date lastDataTime() {
if (activePump != null)
return activePump.lastDataTime();
else return new Date();
}
@Override
public void refreshDataFromPump(String reason) {
if (activePump != null)
activePump.refreshDataFromPump(reason);
}
@Override
public double getBaseBasalRate() {
if (activePump != null)
return activePump.getBaseBasalRate();
else
return 0d;
}
@Override
public PumpEnactResult deliverTreatment(DetailedBolusInfo detailedBolusInfo) {
mWakeLock.acquire();
PumpEnactResult result;
detailedBolusInfo.insulin = applyBolusConstraints(detailedBolusInfo.insulin);
detailedBolusInfo.carbs = applyCarbsConstraints((int) detailedBolusInfo.carbs);
BolusProgressDialog bolusProgressDialog = null;
if (detailedBolusInfo.context != null) {
bolusProgressDialog = new BolusProgressDialog();
bolusProgressDialog.setInsulin(detailedBolusInfo.insulin);
bolusProgressDialog.show(((AppCompatActivity) detailedBolusInfo.context).getSupportFragmentManager(), "BolusProgress");
} else {
Intent i = new Intent();
i.putExtra("insulin", detailedBolusInfo.insulin);
i.setClass(MainApp.instance(), BolusProgressHelperActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
MainApp.instance().startActivity(i);
}
MainApp.bus().post(new EventBolusRequested(detailedBolusInfo.insulin));
result = activePump.deliverTreatment(detailedBolusInfo);
BolusProgressDialog.bolusEnded = true;
MainApp.bus().post(new EventDismissBolusprogressIfRunning(result));
mWakeLock.release();
return result;
}
@Override
public void stopBolusDelivering() {
activePump.stopBolusDelivering();
}
/**
* apply constraints, set temp based on absolute valus and expecting absolute result
*
* @param absoluteRate
* @param durationInMinutes
* @return
*/
@Override
public PumpEnactResult setTempBasalAbsolute(Double absoluteRate, Integer durationInMinutes, boolean force) {
Double rateAfterConstraints = applyBasalConstraints(absoluteRate);
PumpEnactResult result = activePump.setTempBasalAbsolute(rateAfterConstraints, durationInMinutes, force);
if (Config.logCongigBuilderActions)
log.debug("setTempBasalAbsolute rate: " + rateAfterConstraints + " durationInMinutes: " + durationInMinutes + " success: " + result.success + " enacted: " + result.enacted);
return result;
}
public PumpEnactResult setTempBasalAbsolute(Double absoluteRate, Integer durationInMinutes) {
return setTempBasalAbsolute(absoluteRate, durationInMinutes, false);
}
/**
* apply constraints, set temp based on percent and expecting result in percent
*
* @param percent 0 ... 100 ...
* @param durationInMinutes
* @return result
*/
@Override
public PumpEnactResult setTempBasalPercent(Integer percent, Integer durationInMinutes) {
Integer percentAfterConstraints = applyBasalConstraints(percent);
PumpEnactResult result = activePump.setTempBasalPercent(percentAfterConstraints, durationInMinutes);
if (Config.logCongigBuilderActions)
log.debug("setTempBasalPercent percent: " + percentAfterConstraints + " durationInMinutes: " + durationInMinutes + " success: " + result.success + " enacted: " + result.enacted);
return result;
}
@Override
public PumpEnactResult setExtendedBolus(Double insulin, Integer durationInMinutes) {
Double rateAfterConstraints = applyBolusConstraints(insulin);
PumpEnactResult result = activePump.setExtendedBolus(rateAfterConstraints, durationInMinutes);
if (Config.logCongigBuilderActions)
log.debug("setExtendedBolus rate: " + rateAfterConstraints + " durationInMinutes: " + durationInMinutes + " success: " + result.success + " enacted: " + result.enacted);
return result;
}
@Override
public PumpEnactResult cancelTempBasal(boolean force) {
PumpEnactResult result = activePump.cancelTempBasal(force);
if (Config.logCongigBuilderActions)
log.debug("cancelTempBasal success: " + result.success + " enacted: " + result.enacted);
return result;
}
@Override
public PumpEnactResult cancelExtendedBolus() {
PumpEnactResult result = activePump.cancelExtendedBolus();
if (Config.logCongigBuilderActions)
log.debug("cancelExtendedBolus success: " + result.success + " enacted: " + result.enacted);
return result;
}
/** /**
* expect absolute request and allow both absolute and percent response based on pump capabilities * expect absolute request and allow both absolute and percent response based on pump capabilities
* *
* @param request * @param request
* @return * @return
* true if command is going to be executed
* false if error
*/ */
public PumpEnactResult applyAPSRequest(APSResult request) { public boolean applyAPSRequest(APSResult request, Callback callback) {
PumpInterface pump = getActivePump();
request.rate = applyBasalConstraints(request.rate); request.rate = applyBasalConstraints(request.rate);
PumpEnactResult result; PumpEnactResult result;
if (!isInitialized()) { if (!pump.isInitialized()) {
result = new PumpEnactResult();
result.comment = MainApp.sResources.getString(R.string.pumpNotInitialized);
result.enacted = false;
result.success = false;
log.debug("applyAPSRequest: " + MainApp.sResources.getString(R.string.pumpNotInitialized)); log.debug("applyAPSRequest: " + MainApp.sResources.getString(R.string.pumpNotInitialized));
return result; if (callback != null) {
callback.result(new PumpEnactResult().comment(MainApp.sResources.getString(R.string.pumpNotInitialized)).enacted(false).success(false)).run();
}
return false;
} }
if (isSuspended()) { if (pump.isSuspended()) {
result = new PumpEnactResult();
result.comment = MainApp.sResources.getString(R.string.pumpsuspended);
result.enacted = false;
result.success = false;
log.debug("applyAPSRequest: " + MainApp.sResources.getString(R.string.pumpsuspended)); log.debug("applyAPSRequest: " + MainApp.sResources.getString(R.string.pumpsuspended));
return result; if (callback != null) {
callback.result(new PumpEnactResult().comment(MainApp.sResources.getString(R.string.pumpsuspended)).enacted(false).success(false)).run();
}
return false;
} }
if (Config.logCongigBuilderActions) if (Config.logCongigBuilderActions)
log.debug("applyAPSRequest: " + request.toString()); log.debug("applyAPSRequest: " + request.toString());
if ((request.rate == 0 && request.duration == 0) || Math.abs(request.rate - getBaseBasalRate()) < 0.05) { if ((request.rate == 0 && request.duration == 0) || Math.abs(request.rate - pump.getBaseBasalRate()) < pump.getPumpDescription().basalStep) {
if (isTempBasalInProgress()) { if (isTempBasalInProgress()) {
if (Config.logCongigBuilderActions) if (Config.logCongigBuilderActions)
log.debug("applyAPSRequest: cancelTempBasal()"); log.debug("applyAPSRequest: cancelTempBasal()");
result = cancelTempBasal(false); getCommandQueue().cancelTempBasal(false, callback);
return true;
} else { } else {
result = new PumpEnactResult();
result.absolute = request.rate;
result.duration = 0;
result.enacted = false;
result.comment = "Basal set correctly";
result.success = true;
if (Config.logCongigBuilderActions) if (Config.logCongigBuilderActions)
log.debug("applyAPSRequest: Basal set correctly"); log.debug("applyAPSRequest: Basal set correctly");
if (callback != null) {
callback.result(new PumpEnactResult().absolute(request.rate).duration(0).enacted(false).success(true).comment("Basal set correctly")).run();
}
return false;
} }
} else if (isTempBasalInProgress() && Math.abs(request.rate - getTempBasalAbsoluteRateHistory()) < 0.05) { } else if (isTempBasalInProgress()
result = new PumpEnactResult(); && getTempBasalRemainingMinutesFromHistory() > 5
result.absolute = getTempBasalAbsoluteRateHistory(); && Math.abs(request.rate - getTempBasalAbsoluteRateHistory()) < pump.getPumpDescription().basalStep) {
result.duration = getTempBasalFromHistory(System.currentTimeMillis()).getPlannedRemainingMinutes();
result.enacted = false;
result.comment = "Temp basal set correctly";
result.success = true;
if (Config.logCongigBuilderActions) if (Config.logCongigBuilderActions)
log.debug("applyAPSRequest: Temp basal set correctly"); log.debug("applyAPSRequest: Temp basal set correctly");
if (callback != null) {
callback.result(new PumpEnactResult().absolute(getTempBasalAbsoluteRateHistory()).duration(getTempBasalFromHistory(System.currentTimeMillis()).getPlannedRemainingMinutes()).enacted(false).success(true).comment("Temp basal set correctly")).run();
}
return false;
} else { } else {
if (Config.logCongigBuilderActions) if (Config.logCongigBuilderActions)
log.debug("applyAPSRequest: setTempBasalAbsolute()"); log.debug("applyAPSRequest: setTempBasalAbsolute()");
result = setTempBasalAbsolute(request.rate, request.duration); getCommandQueue().tempBasalAbsolute(request.rate, request.duration, false, callback);
return true;
} }
return result;
} }
@Nullable
@Override
public JSONObject getJSONStatus() {
if (activePump != null)
return activePump.getJSONStatus();
else return null;
}
@Override
public String deviceID() {
if (activePump != null)
return activePump.deviceID();
else return "No Pump active!";
}
/*
@Override @Override
public PumpDescription getPumpDescription() { public PumpDescription getPumpDescription() {
if (activePump != null) if (activePump != null)
@ -620,20 +436,7 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain
return emptyDescription; return emptyDescription;
} }
} }
*/
@Override
public String shortStatus(boolean veryShort) {
if (activePump != null) {
return activePump.shortStatus(veryShort);
} else {
return "No Pump active!";
}
}
@Override
public boolean isFakingTempsByExtendedBoluses() {
return activePump.isFakingTempsByExtendedBoluses();
}
/** /**
* Constraints interface * Constraints interface
@ -810,7 +613,7 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain
@Override @Override
public boolean isTempBasalInProgress() { public boolean isTempBasalInProgress() {
return activeTreatments.isTempBasalInProgress(); return activeTreatments != null && activeTreatments.isTempBasalInProgress();
} }
@Override @Override
@ -890,6 +693,12 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain
return newRecordCreated; return newRecordCreated;
} }
@Override
@Nullable
public TempTarget getTempTargetFromHistory() {
return activeTreatments.getTempTargetFromHistory(System.currentTimeMillis());
}
@Override @Override
@Nullable @Nullable
public TempTarget getTempTargetFromHistory(long time) { public TempTarget getTempTargetFromHistory(long time) {
@ -928,10 +737,14 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain
} }
public String getProfileName(long time) { public String getProfileName(long time) {
return getProfileName(time, true);
}
public String getProfileName(long time, boolean customized) {
ProfileSwitch profileSwitch = getProfileSwitchFromHistory(time); ProfileSwitch profileSwitch = getProfileSwitchFromHistory(time);
if (profileSwitch != null) { if (profileSwitch != null) {
if (profileSwitch.profileJson != null) { if (profileSwitch.profileJson != null) {
return profileSwitch.profileName; return customized ? profileSwitch.getCustomizedName() : profileSwitch.profileName;
} else { } else {
Profile profile = activeProfile.getProfile().getSpecificProfile(profileSwitch.profileName); Profile profile = activeProfile.getProfile().getSpecificProfile(profileSwitch.profileName);
if (profile != null) if (profile != null)
@ -951,7 +764,7 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain
} }
public String getProfileUnits() { public String getProfileUnits() {
return activeProfile.getUnits(); return getProfile().getUnits();
} }
public Profile getProfile(long time) { public Profile getProfile(long time) {
@ -987,9 +800,9 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain
MainApp.bus().post(new EventNewNotification(nobasal)); MainApp.bus().post(new EventNewNotification(nobasal));
Notification notarget = new Notification(Notification.TARGET_MISSING, MainApp.sResources.getString(R.string.targetmissing), Notification.URGENT); Notification notarget = new Notification(Notification.TARGET_MISSING, MainApp.sResources.getString(R.string.targetmissing), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(notarget)); MainApp.bus().post(new EventNewNotification(notarget));
return new Profile(new JSONObject("{\"dia\":\"3\",\"carbratio\":[{\"time\":\"00:00\",\"value\":\"20\"}],\"carbs_hr\":\"20\",\"delay\":\"20\",\"sens\":[{\"time\":\"00:00\",\"value\":\"20\"}],\"timezone\":\"UTC\",\"basal\":[{\"time\":\"00:00\",\"value\":\"0.1\"}],\"target_low\":[{\"time\":\"00:00\",\"value\":\"6\"}],\"target_high\":[{\"time\":\"00:00\",\"value\":\"8\"}],\"startDate\":\"1970-01-01T00:00:00.000Z\",\"units\":\"mmol\"}}")); return new Profile(new JSONObject("{\"dia\":\"3\",\"carbratio\":[{\"time\":\"00:00\",\"value\":\"20\"}],\"carbs_hr\":\"20\",\"delay\":\"20\",\"sens\":[{\"time\":\"00:00\",\"value\":\"20\"}],\"timezone\":\"UTC\",\"basal\":[{\"time\":\"00:00\",\"value\":\"0.1\"}],\"target_low\":[{\"time\":\"00:00\",\"value\":\"6\"}],\"target_high\":[{\"time\":\"00:00\",\"value\":\"8\"}],\"startDate\":\"1970-01-01T00:00:00.000Z\",\"units\":\"mmol\"}}"), 100, 0);
} catch (JSONException e) { } catch (JSONException e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
return null; return null;
} }

View file

@ -20,7 +20,7 @@ public class DetailedBolusInfoStorage {
private static List<DetailedBolusInfo> store = new ArrayList<>(); private static List<DetailedBolusInfo> store = new ArrayList<>();
public static void add(DetailedBolusInfo detailedBolusInfo) { public static void add(DetailedBolusInfo detailedBolusInfo) {
log.debug("Bolus info stored: " + new Date(detailedBolusInfo.date).toLocaleString()); log.debug("Stored bolus info: " + detailedBolusInfo);
store.add(detailedBolusInfo); store.add(detailedBolusInfo);
} }
@ -29,7 +29,7 @@ public class DetailedBolusInfoStorage {
DetailedBolusInfo found = null; DetailedBolusInfo found = null;
for (int i = 0; i < store.size(); i++) { for (int i = 0; i < store.size(); i++) {
long infoTime = store.get(i).date; long infoTime = store.get(i).date;
log.debug("Existing info: " + new Date(infoTime).toLocaleString()); log.debug("Existing bolus info: " + store.get(i));
if (bolustime > infoTime - 60 * 1000 && bolustime < infoTime + 60 * 1000) { if (bolustime > infoTime - 60 * 1000 && bolustime < infoTime + 60 * 1000) {
found = store.get(i); found = store.get(i);
break; break;
@ -42,7 +42,7 @@ public class DetailedBolusInfoStorage {
for (int i = 0; i < store.size(); i++) { for (int i = 0; i < store.size(); i++) {
long infoTime = store.get(i).date; long infoTime = store.get(i).date;
if (bolustime > infoTime - 60 * 1000 && bolustime < infoTime + 60 * 1000) { if (bolustime > infoTime - 60 * 1000 && bolustime < infoTime + 60 * 1000) {
log.debug("Removing info: " + new Date(infoTime).toLocaleString()); log.debug("Removing bolus info: " + store.get(i));
store.remove(i); store.remove(i);
break; break;
} }

View file

@ -15,6 +15,8 @@ import android.widget.CheckBox;
import android.widget.LinearLayout; import android.widget.LinearLayout;
import android.widget.TextView; import android.widget.TextView;
import com.crashlytics.android.Crashlytics;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -27,15 +29,6 @@ import info.nightscout.androidaps.R;
public class ObjectivesFragment extends Fragment { public class ObjectivesFragment extends Fragment {
private static Logger log = LoggerFactory.getLogger(ObjectivesFragment.class); private static Logger log = LoggerFactory.getLogger(ObjectivesFragment.class);
private static ObjectivesPlugin objectivesPlugin;
public static ObjectivesPlugin getPlugin() {
if (objectivesPlugin == null) {
objectivesPlugin = new ObjectivesPlugin();
}
return objectivesPlugin;
}
RecyclerView recyclerView; RecyclerView recyclerView;
LinearLayoutManager llm; LinearLayoutManager llm;
CheckBox enableFake; CheckBox enableFake;
@ -59,7 +52,7 @@ public class ObjectivesFragment extends Fragment {
@Override @Override
public void onBindViewHolder(ObjectiveViewHolder holder, int position) { public void onBindViewHolder(ObjectiveViewHolder holder, int position) {
ObjectivesPlugin.Objective o = objectives.get(position); ObjectivesPlugin.Objective o = objectives.get(position);
ObjectivesPlugin.RequirementResult requirementsMet = getPlugin().requirementsMet(position); ObjectivesPlugin.RequirementResult requirementsMet = ObjectivesPlugin.getPlugin().requirementsMet(position);
Context context = MainApp.instance().getApplicationContext(); Context context = MainApp.instance().getApplicationContext();
holder.position.setText(String.valueOf(position + 1)); holder.position.setText(String.valueOf(position + 1));
holder.objective.setText(o.objective); holder.objective.setText(o.objective);
@ -83,7 +76,7 @@ public class ObjectivesFragment extends Fragment {
holder.verifyButton.setOnClickListener(new View.OnClickListener() { holder.verifyButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) { public void onClick(View v) {
ObjectivesPlugin.Objective o = (ObjectivesPlugin.Objective) v.getTag(); ObjectivesPlugin.Objective o = (ObjectivesPlugin.Objective) v.getTag();
if (getPlugin().requirementsMet(o.num).done || enableFake.isChecked()) { if (ObjectivesPlugin.getPlugin().requirementsMet(o.num).done || enableFake.isChecked()) {
o.accomplished = new Date(); o.accomplished = new Date();
updateGUI(); updateGUI();
ObjectivesPlugin.saveProgress(); ObjectivesPlugin.saveProgress();
@ -173,45 +166,51 @@ public class ObjectivesFragment extends Fragment {
@Override @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) { Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.objectives_fragment, container, false); try {
View view = inflater.inflate(R.layout.objectives_fragment, container, false);
recyclerView = (RecyclerView) view.findViewById(R.id.objectives_recyclerview); recyclerView = (RecyclerView) view.findViewById(R.id.objectives_recyclerview);
recyclerView.setHasFixedSize(true); recyclerView.setHasFixedSize(true);
llm = new LinearLayoutManager(view.getContext()); llm = new LinearLayoutManager(view.getContext());
recyclerView.setLayoutManager(llm); recyclerView.setLayoutManager(llm);
enableFake = (CheckBox) view.findViewById(R.id.objectives_fake); enableFake = (CheckBox) view.findViewById(R.id.objectives_fake);
fake_layout = (LinearLayout) view.findViewById(R.id.objectives_fake_layout); fake_layout = (LinearLayout) view.findViewById(R.id.objectives_fake_layout);
reset = (TextView) view.findViewById(R.id.objectives_reset); reset = (TextView) view.findViewById(R.id.objectives_reset);
enableFake.setOnClickListener(new View.OnClickListener() { enableFake.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) { public void onClick(View v) {
updateGUI(); updateGUI();
} }
}); });
reset.setOnClickListener(new View.OnClickListener() { reset.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) { public void onClick(View v) {
getPlugin().initializeData(); ObjectivesPlugin.getPlugin().initializeData();
getPlugin().saveProgress(); ObjectivesPlugin.saveProgress();
updateGUI(); updateGUI();
} }
}); });
// Add correct translations to array after app is initialized // Add correct translations to array after app is initialized
getPlugin().objectives.get(0).objective = MainApp.sResources.getString(R.string.objectives_0_objective); ObjectivesPlugin.objectives.get(0).objective = MainApp.sResources.getString(R.string.objectives_0_objective);
getPlugin().objectives.get(1).objective = MainApp.sResources.getString(R.string.objectives_1_objective); ObjectivesPlugin.objectives.get(1).objective = MainApp.sResources.getString(R.string.objectives_1_objective);
getPlugin().objectives.get(2).objective = MainApp.sResources.getString(R.string.objectives_2_objective); ObjectivesPlugin.objectives.get(2).objective = MainApp.sResources.getString(R.string.objectives_2_objective);
getPlugin().objectives.get(3).objective = MainApp.sResources.getString(R.string.objectives_3_objective); ObjectivesPlugin.objectives.get(3).objective = MainApp.sResources.getString(R.string.objectives_3_objective);
getPlugin().objectives.get(4).objective = MainApp.sResources.getString(R.string.objectives_4_objective); ObjectivesPlugin.objectives.get(4).objective = MainApp.sResources.getString(R.string.objectives_4_objective);
getPlugin().objectives.get(5).objective = MainApp.sResources.getString(R.string.objectives_5_objective); ObjectivesPlugin.objectives.get(5).objective = MainApp.sResources.getString(R.string.objectives_5_objective);
getPlugin().objectives.get(6).objective = MainApp.sResources.getString(R.string.objectives_6_objective); ObjectivesPlugin.objectives.get(6).objective = MainApp.sResources.getString(R.string.objectives_6_objective);
getPlugin().objectives.get(0).gate = MainApp.sResources.getString(R.string.objectives_0_gate); ObjectivesPlugin.objectives.get(0).gate = MainApp.sResources.getString(R.string.objectives_0_gate);
getPlugin().objectives.get(1).gate = MainApp.sResources.getString(R.string.objectives_1_gate); ObjectivesPlugin.objectives.get(1).gate = MainApp.sResources.getString(R.string.objectives_1_gate);
getPlugin().objectives.get(2).gate = MainApp.sResources.getString(R.string.objectives_2_gate); ObjectivesPlugin.objectives.get(2).gate = MainApp.sResources.getString(R.string.objectives_2_gate);
getPlugin().objectives.get(3).gate = MainApp.sResources.getString(R.string.objectives_3_gate); ObjectivesPlugin.objectives.get(3).gate = MainApp.sResources.getString(R.string.objectives_3_gate);
getPlugin().objectives.get(4).gate = MainApp.sResources.getString(R.string.objectives_4_gate); ObjectivesPlugin.objectives.get(4).gate = MainApp.sResources.getString(R.string.objectives_4_gate);
getPlugin().objectives.get(5).gate = MainApp.sResources.getString(R.string.objectives_5_gate); ObjectivesPlugin.objectives.get(5).gate = MainApp.sResources.getString(R.string.objectives_5_gate);
updateGUI(); updateGUI();
return view; return view;
} catch (Exception e) {
Crashlytics.logException(e);
}
return null;
} }
void updateGUI() { void updateGUI() {

View file

@ -16,7 +16,7 @@ import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.interfaces.ConstraintsInterface; import info.nightscout.androidaps.interfaces.ConstraintsInterface;
import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.plugins.Loop.LoopPlugin; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.utils.SP; import info.nightscout.utils.SP;
/** /**
@ -25,11 +25,20 @@ import info.nightscout.utils.SP;
public class ObjectivesPlugin implements PluginBase, ConstraintsInterface { public class ObjectivesPlugin implements PluginBase, ConstraintsInterface {
private static Logger log = LoggerFactory.getLogger(ObjectivesPlugin.class); private static Logger log = LoggerFactory.getLogger(ObjectivesPlugin.class);
private static ObjectivesPlugin objectivesPlugin;
public static ObjectivesPlugin getPlugin() {
if (objectivesPlugin == null) {
objectivesPlugin = new ObjectivesPlugin();
}
return objectivesPlugin;
}
public static List<Objective> objectives; public static List<Objective> objectives;
boolean fragmentVisible = true; private boolean fragmentVisible = true;
public ObjectivesPlugin() { private ObjectivesPlugin() {
initializeData(); initializeData();
loadProgress(); loadProgress();
MainApp.bus().register(this); MainApp.bus().register(this);
@ -53,7 +62,7 @@ public class ObjectivesPlugin implements PluginBase, ConstraintsInterface {
@Override @Override
public String getNameShort() { public String getNameShort() {
String name = MainApp.sResources.getString(R.string.objectives_shortname); String name = MainApp.sResources.getString(R.string.objectives_shortname);
if (!name.trim().isEmpty()){ if (!name.trim().isEmpty()) {
//only if translation exists //only if translation exists
return name; return name;
} }
@ -63,12 +72,12 @@ public class ObjectivesPlugin implements PluginBase, ConstraintsInterface {
@Override @Override
public boolean isEnabled(int type) { public boolean isEnabled(int type) {
return type == CONSTRAINTS && MainApp.getConfigBuilder().getPumpDescription().isTempBasalCapable; return type == CONSTRAINTS && ConfigBuilderPlugin.getActivePump().getPumpDescription().isTempBasalCapable;
} }
@Override @Override
public boolean isVisibleInTabs(int type) { public boolean isVisibleInTabs(int type) {
return type == CONSTRAINTS && fragmentVisible && !BuildConfig.NSCLIENTOLNY; return type == CONSTRAINTS && fragmentVisible && !Config.NSCLIENT && !Config.G5UPLOADER;
} }
@Override @Override
@ -95,7 +104,12 @@ public class ObjectivesPlugin implements PluginBase, ConstraintsInterface {
if (type == CONSTRAINTS) this.fragmentVisible = fragmentVisible; if (type == CONSTRAINTS) this.fragmentVisible = fragmentVisible;
} }
public class Objective { @Override
public int getPreferencesId() {
return -1;
}
class Objective {
Integer num; Integer num;
String objective; String objective;
String gate; String gate;
@ -118,13 +132,13 @@ public class ObjectivesPlugin implements PluginBase, ConstraintsInterface {
public static boolean pumpStatusIsAvailableInNS = false; public static boolean pumpStatusIsAvailableInNS = false;
// Objective 1 // Objective 1
public static Integer manualEnacts = 0; public static Integer manualEnacts = 0;
public static final Integer manualEnactsNeeded = 20; private static final Integer manualEnactsNeeded = 20;
public class RequirementResult { class RequirementResult {
boolean done = false; boolean done = false;
String comment = ""; String comment = "";
public RequirementResult(boolean done, String comment) { RequirementResult(boolean done, String comment) {
this.done = done; this.done = done;
this.comment = comment; this.comment = comment;
} }
@ -135,7 +149,7 @@ public class ObjectivesPlugin implements PluginBase, ConstraintsInterface {
else return "---"; else return "---";
} }
public RequirementResult requirementsMet(Integer objNum) { RequirementResult requirementsMet(Integer objNum) {
switch (objNum) { switch (objNum) {
case 0: case 0:
return new RequirementResult(bgIsAvailableInNS && pumpStatusIsAvailableInNS, return new RequirementResult(bgIsAvailableInNS && pumpStatusIsAvailableInNS,
@ -152,7 +166,7 @@ public class ObjectivesPlugin implements PluginBase, ConstraintsInterface {
} }
public void initializeData() { void initializeData() {
bgIsAvailableInNS = false; bgIsAvailableInNS = false;
pumpStatusIsAvailableInNS = false; pumpStatusIsAvailableInNS = false;
manualEnacts = 0; manualEnacts = 0;
@ -220,14 +234,14 @@ public class ObjectivesPlugin implements PluginBase, ConstraintsInterface {
} }
} }
void loadProgress() { private void loadProgress() {
for (int num = 0; num < objectives.size(); num++) { for (int num = 0; num < objectives.size(); num++) {
Objective o = objectives.get(num); Objective o = objectives.get(num);
try { try {
o.started = new Date(SP.getLong("Objectives" + num + "started", 0L)); o.started = new Date(SP.getLong("Objectives" + num + "started", 0L));
o.accomplished = new Date(SP.getLong("Objectives" + num + "accomplished", 0L)); o.accomplished = new Date(SP.getLong("Objectives" + num + "accomplished", 0L));
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
} }
bgIsAvailableInNS = SP.getBoolean("Objectives" + "bgIsAvailableInNS", false); bgIsAvailableInNS = SP.getBoolean("Objectives" + "bgIsAvailableInNS", false);
@ -235,7 +249,7 @@ public class ObjectivesPlugin implements PluginBase, ConstraintsInterface {
try { try {
manualEnacts = SP.getInt("Objectives" + "manualEnacts", 0); manualEnacts = SP.getInt("Objectives" + "manualEnacts", 0);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
if (Config.logPrefsChange) if (Config.logPrefsChange)
log.debug("Objectives loaded"); log.debug("Objectives loaded");

View file

@ -10,9 +10,10 @@ import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.interfaces.ConstraintsInterface; import info.nightscout.androidaps.interfaces.ConstraintsInterface;
import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.utils.HardLimits; import info.nightscout.utils.HardLimits;
import info.nightscout.utils.Round; import info.nightscout.utils.Round;
import info.nightscout.utils.SP; import info.nightscout.utils.SP;
@ -86,9 +87,14 @@ public class SafetyPlugin implements PluginBase, ConstraintsInterface {
public void setFragmentVisible(int type, boolean fragmentVisible) { public void setFragmentVisible(int type, boolean fragmentVisible) {
} }
@Override
public int getPreferencesId() {
return R.xml.pref_safety;
}
@Override @Override
public boolean isLoopEnabled() { public boolean isLoopEnabled() {
return MainApp.getConfigBuilder().getPumpDescription().isTempBasalCapable; return ConfigBuilderPlugin.getActivePump().getPumpDescription().isTempBasalCapable;
} }
/** /**

View file

@ -0,0 +1,315 @@
package info.nightscout.androidaps.plugins.Food;
import android.app.Activity;
import android.content.DialogInterface;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import com.crashlytics.android.Crashlytics;
import com.squareup.otto.Subscribe;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.db.Food;
import info.nightscout.androidaps.events.EventFoodDatabaseChanged;
import info.nightscout.androidaps.plugins.Common.SubscriberFragment;
import info.nightscout.utils.NSUpload;
import info.nightscout.utils.SpinnerHelper;
/**
* Created by mike on 16.10.2017.
*/
public class FoodFragment extends SubscriberFragment {
private static Logger log = LoggerFactory.getLogger(FoodFragment.class);
EditText filter;
ImageView clearFilter;
SpinnerHelper category;
SpinnerHelper subcategory;
RecyclerView recyclerView;
List<Food> unfiltered;
List<Food> filtered;
ArrayList<CharSequence> categories;
ArrayList<CharSequence> subcategories;
final String EMPTY = MainApp.sResources.getString(R.string.none);
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
try {
View view = inflater.inflate(R.layout.food_fragment, container, false);
filter = (EditText) view.findViewById(R.id.food_filter);
clearFilter = (ImageView) view.findViewById(R.id.food_clearfilter);
category = new SpinnerHelper(view.findViewById(R.id.food_category));
subcategory = new SpinnerHelper(view.findViewById(R.id.food_subcategory));
recyclerView = (RecyclerView) view.findViewById(R.id.food_recyclerview);
recyclerView.setHasFixedSize(true);
LinearLayoutManager llm = new LinearLayoutManager(view.getContext());
recyclerView.setLayoutManager(llm);
clearFilter.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
filter.setText("");
category.setSelection(0);
subcategory.setSelection(0);
filterData();
}
});
category.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
fillSubcategories();
filterData();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
fillSubcategories();
filterData();
}
});
subcategory.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
filterData();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
filterData();
}
});
filter.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
filterData();
}
@Override
public void afterTextChanged(Editable s) {
}
});
RecyclerViewAdapter adapter = new RecyclerViewAdapter(MainApp.getDbHelper().foodHelper.getFoodData());
recyclerView.setAdapter(adapter);
loadData();
fillCategories();
fillSubcategories();
filterData();
return view;
} catch (Exception e) {
Crashlytics.logException(e);
}
return null;
}
@Subscribe
@SuppressWarnings("unused")
public void onStatusEvent(final EventFoodDatabaseChanged ev) {
loadData();
filterData();
}
void loadData() {
unfiltered = MainApp.getDbHelper().foodHelper.getFoodData();
}
void fillCategories() {
categories = new ArrayList<>();
for (Food f : unfiltered) {
if (f.category != null && !f.category.equals(""))
categories.add(f.category);
}
// make it unique
categories = new ArrayList<>(new HashSet<>(categories));
categories.add(0, MainApp.sResources.getString(R.string.none));
ArrayAdapter<CharSequence> adapterCategories = new ArrayAdapter<>(getContext(),
R.layout.spinner_centered, categories);
category.setAdapter(adapterCategories);
}
void fillSubcategories() {
String categoryFilter = category.getSelectedItem().toString();
subcategories = new ArrayList<>();
if (!categoryFilter.equals(EMPTY)) {
for (Food f : unfiltered) {
if (f.category != null && f.category.equals(categoryFilter))
if (f.subcategory != null && !f.subcategory.equals(""))
subcategories.add(f.subcategory);
}
}
// make it unique
subcategories = new ArrayList<>(new HashSet<>(subcategories));
subcategories.add(0, MainApp.sResources.getString(R.string.none));
ArrayAdapter<CharSequence> adapterSubcategories = new ArrayAdapter<>(getContext(),
R.layout.spinner_centered, subcategories);
subcategory.setAdapter(adapterSubcategories);
}
void filterData() {
String textFilter = filter.getText().toString();
String categoryFilter = category.getSelectedItem().toString();
String subcategoryFilter = subcategory.getSelectedItem().toString();
filtered = new ArrayList<>();
for (Food f : unfiltered) {
if (f.name == null || f.category == null || f.subcategory == null)
continue;
if (!subcategoryFilter.equals(EMPTY) && !f.subcategory.equals(subcategoryFilter))
continue;
if (!categoryFilter.equals(EMPTY) && !f.category.equals(categoryFilter))
continue;
if (!textFilter.equals("") && !f.name.toLowerCase().contains(textFilter.toLowerCase()))
continue;
filtered.add(f);
}
updateGUI();
}
@Override
protected void updateGUI() {
Activity activity = getActivity();
if (activity != null)
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
recyclerView.swapAdapter(new FoodFragment.RecyclerViewAdapter(filtered), true);
}
});
}
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.FoodsViewHolder> {
List<Food> foodList;
RecyclerViewAdapter(List<Food> foodList) {
this.foodList = foodList;
}
@Override
public FoodsViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.food_item, viewGroup, false);
return new FoodsViewHolder(v);
}
@Override
public void onBindViewHolder(FoodsViewHolder holder, int position) {
Food food = foodList.get(position);
holder.ns.setVisibility(food._id != null ? View.VISIBLE : View.GONE);
holder.name.setText(food.name);
holder.portion.setText(food.portion + food.units);
holder.carbs.setText(food.carbs + MainApp.sResources.getString(R.string.shortgramm));
holder.fat.setText(MainApp.sResources.getString(R.string.shortfat) + ": " + food.fat + MainApp.sResources.getString(R.string.shortgramm));
if (food.fat == 0)
holder.fat.setVisibility(View.INVISIBLE);
holder.protein.setText(MainApp.sResources.getString(R.string.shortprotein) + ": " + food.protein + MainApp.sResources.getString(R.string.shortgramm));
if (food.protein == 0)
holder.protein.setVisibility(View.INVISIBLE);
holder.energy.setText(MainApp.sResources.getString(R.string.shortenergy) + ": " + food.energy + MainApp.sResources.getString(R.string.shortkilojoul));
if (food.energy == 0)
holder.energy.setVisibility(View.INVISIBLE);
holder.remove.setTag(food);
}
@Override
public int getItemCount() {
return foodList.size();
}
class FoodsViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView name;
TextView portion;
TextView carbs;
TextView fat;
TextView protein;
TextView energy;
TextView ns;
TextView remove;
FoodsViewHolder(View itemView) {
super(itemView);
name = (TextView) itemView.findViewById(R.id.food_name);
portion = (TextView) itemView.findViewById(R.id.food_portion);
carbs = (TextView) itemView.findViewById(R.id.food_carbs);
fat = (TextView) itemView.findViewById(R.id.food_fat);
protein = (TextView) itemView.findViewById(R.id.food_protein);
energy = (TextView) itemView.findViewById(R.id.food_energy);
ns = (TextView) itemView.findViewById(R.id.ns_sign);
remove = (TextView) itemView.findViewById(R.id.food_remove);
remove.setOnClickListener(this);
remove.setPaintFlags(remove.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
}
@Override
public void onClick(View v) {
final Food food = (Food) v.getTag();
switch (v.getId()) {
case R.id.food_remove:
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle(MainApp.sResources.getString(R.string.confirmation));
builder.setMessage(MainApp.sResources.getString(R.string.removerecord) + "\n" + food.name);
builder.setPositiveButton(MainApp.sResources.getString(R.string.ok), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
final String _id = food._id;
if (_id != null && !_id.equals("")) {
NSUpload.removeFoodFromNS(_id);
}
MainApp.getDbHelper().foodHelper.delete(food);
}
});
builder.setNegativeButton(MainApp.sResources.getString(R.string.cancel), null);
builder.show();
break;
}
}
}
}
}

View file

@ -0,0 +1,85 @@
package info.nightscout.androidaps.plugins.Food;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.interfaces.PluginBase;
/**
* Created by mike on 05.08.2016.
*/
public class FoodPlugin implements PluginBase {
private boolean fragmentEnabled = true;
private boolean fragmentVisible = false;
private static FoodPlugin plugin = null;
public static FoodPlugin getPlugin() {
if (plugin == null)
plugin = new FoodPlugin();
return plugin;
}
@Override
public String getFragmentClass() {
return FoodFragment.class.getName();
}
@Override
public int getType() {
return PluginBase.GENERAL;
}
@Override
public String getName() {
return MainApp.instance().getString(R.string.food);
}
@Override
public String getNameShort() {
// use long name as fallback (not visible in tabs)
return getName();
}
@Override
public boolean isEnabled(int type) {
return type == GENERAL && fragmentEnabled;
}
@Override
public boolean isVisibleInTabs(int type) {
return type == GENERAL && fragmentVisible;
}
@Override
public boolean canBeHidden(int type) {
return true;
}
@Override
public boolean hasFragment() {
return true;
}
@Override
public boolean showInList(int type) {
return true;
}
@Override
public void setFragmentEnabled(int type, boolean fragmentEnabled) {
if (type == GENERAL) this.fragmentEnabled = fragmentEnabled;
}
@Override
public void setFragmentVisible(int type, boolean fragmentVisible) {
if (type == GENERAL) this.fragmentVisible = fragmentVisible;
}
@Override
public int getPreferencesId() {
return -1;
}
}

View file

@ -1,4 +1,4 @@
package info.nightscout.androidaps.plugins.InsulinFastacting; package info.nightscout.androidaps.plugins.Insulin;
import android.content.Context; import android.content.Context;
import android.graphics.Color; import android.graphics.Color;

View file

@ -1,4 +1,4 @@
package info.nightscout.androidaps.plugins.InsulinFastacting; package info.nightscout.androidaps.plugins.Insulin;
import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
@ -14,8 +14,16 @@ import info.nightscout.androidaps.interfaces.PluginBase;
public class InsulinFastactingPlugin implements PluginBase, InsulinInterface { public class InsulinFastactingPlugin implements PluginBase, InsulinInterface {
private static boolean fragmentEnabled = true; private boolean fragmentEnabled = true;
private static boolean fragmentVisible = false; private boolean fragmentVisible = false;
private static InsulinFastactingPlugin plugin = null;
public static InsulinFastactingPlugin getPlugin() {
if (plugin == null)
plugin = new InsulinFastactingPlugin();
return plugin;
}
@Override @Override
public int getType() { public int getType() {
@ -24,7 +32,7 @@ public class InsulinFastactingPlugin implements PluginBase, InsulinInterface {
@Override @Override
public String getFragmentClass() { public String getFragmentClass() {
return InsulinFastactingFragment.class.getName(); return InsulinFragment.class.getName();
} }
@Override @Override
@ -72,6 +80,11 @@ public class InsulinFastactingPlugin implements PluginBase, InsulinInterface {
if (type == INSULIN) this.fragmentVisible = fragmentVisible; if (type == INSULIN) this.fragmentVisible = fragmentVisible;
} }
@Override
public int getPreferencesId() {
return -1;
}
// Insulin interface // Insulin interface
@Override @Override
public int getId() { public int getId() {

View file

@ -1,4 +1,4 @@
package info.nightscout.androidaps.plugins.InsulinFastactingProlonged; package info.nightscout.androidaps.plugins.Insulin;
import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
@ -14,8 +14,16 @@ import info.nightscout.androidaps.interfaces.PluginBase;
public class InsulinFastactingProlongedPlugin implements PluginBase, InsulinInterface { public class InsulinFastactingProlongedPlugin implements PluginBase, InsulinInterface {
private static boolean fragmentEnabled = false; private boolean fragmentEnabled = false;
private static boolean fragmentVisible = false; private boolean fragmentVisible = false;
private static InsulinFastactingProlongedPlugin plugin = null;
public static InsulinFastactingProlongedPlugin getPlugin() {
if (plugin == null)
plugin = new InsulinFastactingProlongedPlugin();
return plugin;
}
@Override @Override
public int getType() { public int getType() {
@ -24,7 +32,7 @@ public class InsulinFastactingProlongedPlugin implements PluginBase, InsulinInte
@Override @Override
public String getFragmentClass() { public String getFragmentClass() {
return InsulinFastactingProlongedFragment.class.getName(); return InsulinFragment.class.getName();
} }
@Override @Override
@ -72,6 +80,11 @@ public class InsulinFastactingProlongedPlugin implements PluginBase, InsulinInte
if (type == INSULIN) this.fragmentVisible = fragmentVisible; if (type == INSULIN) this.fragmentVisible = fragmentVisible;
} }
@Override
public int getPreferencesId() {
return -1;
}
// Insulin interface // Insulin interface
@Override @Override
public int getId() { public int getId() {

View file

@ -0,0 +1,59 @@
package info.nightscout.androidaps.plugins.Insulin;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.crashlytics.android.Crashlytics;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
/**
* Created by mike on 17.04.2017.
*/
public class InsulinFragment extends Fragment {
TextView insulinName;
TextView insulinComment;
TextView insulinDia;
ActivityGraph insulinGraph;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
try {
View view = inflater.inflate(R.layout.insulin_fragment, container, false);
insulinName = (TextView) view.findViewById(R.id.insulin_name);
insulinComment = (TextView) view.findViewById(R.id.insulin_comment);
insulinDia = (TextView) view.findViewById(R.id.insulin_dia);
insulinGraph = (ActivityGraph) view.findViewById(R.id.insuling_graph);
updateGUI();
return view;
} catch (Exception e) {
Crashlytics.logException(e);
}
return null;
}
@Override
public void onResume() {
super.onResume();
updateGUI();
}
private void updateGUI() {
insulinName.setText(ConfigBuilderPlugin.getActiveInsulin().getFriendlyName());
insulinComment.setText(ConfigBuilderPlugin.getActiveInsulin().getComment());
insulinDia.setText(MainApp.sResources.getText(R.string.dia) + " " + Double.toString(ConfigBuilderPlugin.getActiveInsulin().getDia()) + "h");
insulinGraph.show(ConfigBuilderPlugin.getActiveInsulin());
}
}

View file

@ -1,13 +1,12 @@
package info.nightscout.androidaps.plugins.InsulinOrefCurves; package info.nightscout.androidaps.plugins.Insulin;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.Iob; import info.nightscout.androidaps.data.Iob;
import info.nightscout.androidaps.db.Treatment; import info.nightscout.androidaps.db.Treatment;
import info.nightscout.androidaps.interfaces.InsulinInterface; import info.nightscout.androidaps.interfaces.InsulinInterface;
import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.plugins.Overview.Notification; import info.nightscout.androidaps.plugins.Overview.notifications.Notification;
import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification; import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification;
/** /**
@ -61,7 +60,7 @@ public abstract class InsulinOrefBasePlugin implements PluginBase, InsulinInterf
} }
public double getUserDefinedDia() { public double getUserDefinedDia() {
return MainApp.getConfigBuilder().getProfile() != null ? MainApp.getConfigBuilder().getProfile().getDia() : Constants.defaultDIA; return MainApp.getConfigBuilder().getProfile() != null ? MainApp.getConfigBuilder().getProfile().getDia() : MIN_DIA;
} }
@Override @Override

View file

@ -1,4 +1,4 @@
package info.nightscout.androidaps.plugins.InsulinOrefCurves; package info.nightscout.androidaps.plugins.Insulin;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
@ -10,8 +10,16 @@ import info.nightscout.utils.SP;
public class InsulinOrefFreePeakPlugin extends InsulinOrefBasePlugin { public class InsulinOrefFreePeakPlugin extends InsulinOrefBasePlugin {
private static boolean fragmentEnabled = false; private boolean fragmentEnabled = false;
private static boolean fragmentVisible = false; private boolean fragmentVisible = false;
private static InsulinOrefFreePeakPlugin plugin = null;
public static InsulinOrefFreePeakPlugin getPlugin() {
if (plugin == null)
plugin = new InsulinOrefFreePeakPlugin();
return plugin;
}
public static final int DEFAULT_PEAK = 75; public static final int DEFAULT_PEAK = 75;
@ -27,7 +35,7 @@ public class InsulinOrefFreePeakPlugin extends InsulinOrefBasePlugin {
@Override @Override
public String getFragmentClass() { public String getFragmentClass() {
return InsulinOrefFreePeakFragment.class.getName(); return InsulinFragment.class.getName();
} }
@Override @Override
@ -60,6 +68,11 @@ public class InsulinOrefFreePeakPlugin extends InsulinOrefBasePlugin {
if (type == INSULIN) this.fragmentVisible = fragmentVisible; if (type == INSULIN) this.fragmentVisible = fragmentVisible;
} }
@Override
public int getPreferencesId() {
return R.xml.pref_insulinoreffreepeak;
}
@Override @Override
int getPeak() { int getPeak() {
return SP.getInt(R.string.key_insulin_oref_peak, DEFAULT_PEAK); return SP.getInt(R.string.key_insulin_oref_peak, DEFAULT_PEAK);

View file

@ -1,4 +1,4 @@
package info.nightscout.androidaps.plugins.InsulinOrefCurves; package info.nightscout.androidaps.plugins.Insulin;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
@ -9,8 +9,16 @@ import info.nightscout.androidaps.R;
public class InsulinOrefRapidActingPlugin extends InsulinOrefBasePlugin { public class InsulinOrefRapidActingPlugin extends InsulinOrefBasePlugin {
private static boolean fragmentEnabled = false; private boolean fragmentEnabled = false;
private static boolean fragmentVisible = false; private boolean fragmentVisible = false;
private static InsulinOrefRapidActingPlugin plugin = null;
public static InsulinOrefRapidActingPlugin getPlugin() {
if (plugin == null)
plugin = new InsulinOrefRapidActingPlugin();
return plugin;
}
public static final int PEAK = 75; public static final int PEAK = 75;
@ -26,7 +34,7 @@ public class InsulinOrefRapidActingPlugin extends InsulinOrefBasePlugin {
@Override @Override
public String getFragmentClass() { public String getFragmentClass() {
return InsulinOrefRapidActingFragment.class.getName(); return InsulinFragment.class.getName();
} }
@Override @Override
@ -59,6 +67,11 @@ public class InsulinOrefRapidActingPlugin extends InsulinOrefBasePlugin {
if (type == INSULIN) this.fragmentVisible = fragmentVisible; if (type == INSULIN) this.fragmentVisible = fragmentVisible;
} }
@Override
public int getPreferencesId() {
return -1;
}
@Override @Override
int getPeak() { int getPeak() {
return PEAK; return PEAK;

View file

@ -1,4 +1,4 @@
package info.nightscout.androidaps.plugins.InsulinOrefCurves; package info.nightscout.androidaps.plugins.Insulin;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
@ -9,8 +9,16 @@ import info.nightscout.androidaps.R;
public class InsulinOrefUltraRapidActingPlugin extends InsulinOrefBasePlugin { public class InsulinOrefUltraRapidActingPlugin extends InsulinOrefBasePlugin {
private static boolean fragmentEnabled = false; private boolean fragmentEnabled = false;
private static boolean fragmentVisible = false; private boolean fragmentVisible = false;
private static InsulinOrefUltraRapidActingPlugin plugin = null;
public static InsulinOrefUltraRapidActingPlugin getPlugin() {
if (plugin == null)
plugin = new InsulinOrefUltraRapidActingPlugin();
return plugin;
}
public static final int PEAK = 55; public static final int PEAK = 55;
@ -26,7 +34,7 @@ public class InsulinOrefUltraRapidActingPlugin extends InsulinOrefBasePlugin {
@Override @Override
public String getFragmentClass() { public String getFragmentClass() {
return InsulinOrefUltraRapidActingFragment.class.getName(); return InsulinFragment.class.getName();
} }
@Override @Override
@ -59,6 +67,11 @@ public class InsulinOrefUltraRapidActingPlugin extends InsulinOrefBasePlugin {
if (type == INSULIN) this.fragmentVisible = fragmentVisible; if (type == INSULIN) this.fragmentVisible = fragmentVisible;
} }
@Override
public int getPreferencesId() {
return -1;
}
@Override @Override
int getPeak() { int getPeak() {
return PEAK; return PEAK;

View file

@ -1,56 +0,0 @@
package info.nightscout.androidaps.plugins.InsulinFastacting;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
/**
* Created by mike on 17.04.2017.
*/
public class InsulinFastactingFragment extends Fragment {
static InsulinFastactingPlugin insulinFastactingPlugin = new InsulinFastactingPlugin();
static public InsulinFastactingPlugin getPlugin() {
return insulinFastactingPlugin;
}
TextView insulinName;
TextView insulinComment;
TextView insulinDia;
ActivityGraph insulinGraph;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.insulin_fragment, container, false);
insulinName = (TextView) view.findViewById(R.id.insulin_name);
insulinComment = (TextView) view.findViewById(R.id.insulin_comment);
insulinDia = (TextView) view.findViewById(R.id.insulin_dia);
insulinGraph = (ActivityGraph) view.findViewById(R.id.insuling_graph);
updateGUI();
return view;
}
@Override
public void onResume() {
super.onResume();
updateGUI();
}
private void updateGUI() {
insulinName.setText(insulinFastactingPlugin.getFriendlyName());
insulinComment.setText(insulinFastactingPlugin.getComment());
insulinDia.setText(MainApp.sResources.getText(R.string.dia) + " " + Double.toString(insulinFastactingPlugin.getDia()) + "h");
insulinGraph.show(insulinFastactingPlugin);
}
}

View file

@ -1,57 +0,0 @@
package info.nightscout.androidaps.plugins.InsulinFastactingProlonged;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.plugins.InsulinFastacting.ActivityGraph;
/**
* Created by mike on 17.04.2017.
*/
public class InsulinFastactingProlongedFragment extends Fragment {
static InsulinFastactingProlongedPlugin insulinFastactingProlongedPlugin = new InsulinFastactingProlongedPlugin();
static public InsulinFastactingProlongedPlugin getPlugin() {
return insulinFastactingProlongedPlugin;
}
TextView insulinName;
TextView insulinComment;
TextView insulinDia;
ActivityGraph insulinGraph;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.insulin_fragment, container, false);
insulinName = (TextView) view.findViewById(R.id.insulin_name);
insulinComment = (TextView) view.findViewById(R.id.insulin_comment);
insulinDia = (TextView) view.findViewById(R.id.insulin_dia);
insulinGraph = (ActivityGraph) view.findViewById(R.id.insuling_graph);
updateGUI();
return view;
}
@Override
public void onResume() {
super.onResume();
updateGUI();
}
private void updateGUI() {
insulinName.setText(insulinFastactingProlongedPlugin.getFriendlyName());
insulinComment.setText(insulinFastactingProlongedPlugin.getComment());
insulinDia.setText(MainApp.sResources.getText(R.string.dia) + " " + Double.toString(insulinFastactingProlongedPlugin.getDia()) + "h");
insulinGraph.show(insulinFastactingProlongedPlugin);
}
}

View file

@ -1,58 +0,0 @@
package info.nightscout.androidaps.plugins.InsulinOrefCurves;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.plugins.InsulinFastacting.ActivityGraph;
/**
* Created by adrian on 14/08/17.
*/
public class InsulinOrefFreePeakFragment extends Fragment {
static InsulinOrefFreePeakPlugin insulinPlugin = new InsulinOrefFreePeakPlugin();
static public InsulinOrefFreePeakPlugin getPlugin() {
return insulinPlugin;
}
TextView insulinName;
TextView insulinComment;
TextView insulinDia;
ActivityGraph insulinGraph;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.insulin_fragment, container, false);
insulinName = (TextView) view.findViewById(R.id.insulin_name);
insulinComment = (TextView) view.findViewById(R.id.insulin_comment);
insulinDia = (TextView) view.findViewById(R.id.insulin_dia);
insulinGraph = (ActivityGraph) view.findViewById(R.id.insuling_graph);
updateGUI();
return view;
}
@Override
public void onResume() {
super.onResume();
updateGUI();
}
private void updateGUI() {
insulinName.setText(insulinPlugin.getFriendlyName());
insulinComment.setText(insulinPlugin.getComment());
insulinDia.setText(MainApp.sResources.getText(R.string.dia) + " " + Double.toString(insulinPlugin.getDia()) + "h");
insulinGraph.show(insulinPlugin);
}
}

View file

@ -1,57 +0,0 @@
package info.nightscout.androidaps.plugins.InsulinOrefCurves;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.plugins.InsulinFastacting.ActivityGraph;
/**
* Created by adrian on 14/08/17.
*/
public class InsulinOrefRapidActingFragment extends Fragment {
static InsulinOrefRapidActingPlugin insulinPlugin = new InsulinOrefRapidActingPlugin();
static public InsulinOrefRapidActingPlugin getPlugin() {
return insulinPlugin;
}
TextView insulinName;
TextView insulinComment;
TextView insulinDia;
ActivityGraph insulinGraph;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.insulin_fragment, container, false);
insulinName = (TextView) view.findViewById(R.id.insulin_name);
insulinComment = (TextView) view.findViewById(R.id.insulin_comment);
insulinDia = (TextView) view.findViewById(R.id.insulin_dia);
insulinGraph = (ActivityGraph) view.findViewById(R.id.insuling_graph);
updateGUI();
return view;
}
@Override
public void onResume() {
super.onResume();
updateGUI();
}
private void updateGUI() {
insulinName.setText(insulinPlugin.getFriendlyName());
insulinComment.setText(insulinPlugin.getComment());
insulinDia.setText(MainApp.sResources.getText(R.string.dia) + " " + Double.toString(insulinPlugin.getDia()) + "h");
insulinGraph.show(insulinPlugin);
}
}

View file

@ -1,58 +0,0 @@
package info.nightscout.androidaps.plugins.InsulinOrefCurves;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.plugins.InsulinFastacting.ActivityGraph;
/**
* Created by adrian on 14/08/17.
*/
public class InsulinOrefUltraRapidActingFragment extends Fragment {
static InsulinOrefUltraRapidActingPlugin insulinPlugin = new InsulinOrefUltraRapidActingPlugin();
static public InsulinOrefUltraRapidActingPlugin getPlugin() {
return insulinPlugin;
}
TextView insulinName;
TextView insulinComment;
TextView insulinDia;
ActivityGraph insulinGraph;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.insulin_fragment, container, false);
insulinName = (TextView) view.findViewById(R.id.insulin_name);
insulinComment = (TextView) view.findViewById(R.id.insulin_comment);
insulinDia = (TextView) view.findViewById(R.id.insulin_dia);
insulinGraph = (ActivityGraph) view.findViewById(R.id.insuling_graph);
updateGUI();
return view;
}
@Override
public void onResume() {
super.onResume();
updateGUI();
}
private void updateGUI() {
insulinName.setText(insulinPlugin.getFriendlyName());
insulinComment.setText(insulinPlugin.getComment());
insulinDia.setText(MainApp.sResources.getText(R.string.dia) + " " + Double.toString(insulinPlugin.getDia()) + "h");
insulinGraph.show(insulinPlugin);
}
}

View file

@ -13,6 +13,7 @@ import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.db.Treatment; import info.nightscout.androidaps.db.Treatment;
import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.plugins.SensitivityAAPS.SensitivityAAPSPlugin; import info.nightscout.androidaps.plugins.SensitivityAAPS.SensitivityAAPSPlugin;
import info.nightscout.androidaps.plugins.SensitivityWeightedAverage.SensitivityWeightedAveragePlugin;
import info.nightscout.utils.SP; import info.nightscout.utils.SP;
/** /**
@ -32,7 +33,7 @@ public class AutosensData {
time = t.date; time = t.date;
carbs = t.carbs; carbs = t.carbs;
remaining = t.carbs; remaining = t.carbs;
if (MainApp.getSpecificPlugin(SensitivityAAPSPlugin.class) != null && MainApp.getSpecificPlugin(SensitivityAAPSPlugin.class).isEnabled(PluginBase.SENSITIVITY)) { if (SensitivityAAPSPlugin.getPlugin().isEnabled(PluginBase.SENSITIVITY) || SensitivityWeightedAveragePlugin.getPlugin().isEnabled(PluginBase.SENSITIVITY)) {
double maxAbsorptionHours = SP.getDouble(R.string.key_absorption_maxtime, 4d); double maxAbsorptionHours = SP.getDouble(R.string.key_absorption_maxtime, 4d);
Profile profile = MainApp.getConfigBuilder().getProfile(t.date); Profile profile = MainApp.getConfigBuilder().getProfile(t.date);
double sens = Profile.toMgdl(profile.getIsf(t.date), profile.getUnits()); double sens = Profile.toMgdl(profile.getIsf(t.date), profile.getUnits());

View file

@ -2,11 +2,14 @@ package info.nightscout.androidaps.plugins.IobCobCalculator;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** /**
* Created by mike on 06.01.2017. * Created by mike on 06.01.2017.
*/ */
public class AutosensResult { public class AutosensResult {
private static Logger log = LoggerFactory.getLogger(AutosensResult.class);
//default values to show when autosens algorithm is not called //default values to show when autosens algorithm is not called
public double ratio = 1d; public double ratio = 1d;
@ -24,7 +27,7 @@ public class AutosensResult {
ret.put("sensResult", sensResult); ret.put("sensResult", sensResult);
ret.put("ratio", ratio); ret.put("ratio", ratio);
} catch (JSONException e) { } catch (JSONException e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
return ret; return ret;
} }

View file

@ -2,6 +2,7 @@ package info.nightscout.androidaps.plugins.IobCobCalculator;
import android.os.Handler; import android.os.Handler;
import android.os.HandlerThread; import android.os.HandlerThread;
import android.os.Process;
import android.support.annotation.Nullable; import android.support.annotation.Nullable;
import android.support.v4.util.LongSparseArray; import android.support.v4.util.LongSparseArray;
@ -126,10 +127,15 @@ public class IobCobCalculatorPlugin implements PluginBase {
} }
@Override
public int getPreferencesId() {
return -1;
}
IobCobCalculatorPlugin() { IobCobCalculatorPlugin() {
MainApp.bus().register(this); MainApp.bus().register(this);
if (sHandlerThread == null) { if (sHandlerThread == null) {
sHandlerThread = new HandlerThread(IobCobCalculatorPlugin.class.getSimpleName()); sHandlerThread = new HandlerThread(IobCobCalculatorPlugin.class.getSimpleName(), Process.THREAD_PRIORITY_LOWEST);
sHandlerThread.start(); sHandlerThread.start();
sHandler = new Handler(sHandlerThread.getLooper()); sHandler = new Handler(sHandlerThread.getLooper());
} }
@ -227,7 +233,7 @@ public class IobCobCalculatorPlugin implements PluginBase {
private BgReading findOlder(long time) { private BgReading findOlder(long time) {
BgReading lastFound = bgReadings.get(bgReadings.size() - 1); BgReading lastFound = bgReadings.get(bgReadings.size() - 1);
if (lastFound.date > time) return null; if (lastFound.date > time) return null;
for (int i = bgReadings.size() - 2; i >=0 ; --i) { for (int i = bgReadings.size() - 2; i >= 0; --i) {
if (bgReadings.get(i).date < time) continue; if (bgReadings.get(i).date < time) continue;
lastFound = bgReadings.get(i); lastFound = bgReadings.get(i);
if (bgReadings.get(i).date > time) break; if (bgReadings.get(i).date > time) break;
@ -246,7 +252,7 @@ public class IobCobCalculatorPlugin implements PluginBase {
long currentTime = bgReadings.get(0).date + 5 * 60 * 1000 - bgReadings.get(0).date % (5 * 60 * 1000) - 5 * 60 * 1000L; long currentTime = bgReadings.get(0).date + 5 * 60 * 1000 - bgReadings.get(0).date % (5 * 60 * 1000) - 5 * 60 * 1000L;
//log.debug("First reading: " + new Date(currentTime).toLocaleString()); //log.debug("First reading: " + new Date(currentTime).toLocaleString());
while (true) { while (true) {
// test if current value is older than current time // test if current value is older than current time
BgReading newer = findNewer(currentTime); BgReading newer = findNewer(currentTime);
BgReading older = findOlder(currentTime); BgReading older = findOlder(currentTime);
@ -366,6 +372,9 @@ public class IobCobCalculatorPlugin implements PluginBase {
continue; continue;
} }
if (profile.getIsf(bgTime) == null)
return; // profile not set yet
double sens = Profile.toMgdl(profile.getIsf(bgTime), profile.getUnits()); double sens = Profile.toMgdl(profile.getIsf(bgTime), profile.getUnits());
AutosensData autosensData = new AutosensData(); AutosensData autosensData = new AutosensData();
@ -669,8 +678,8 @@ public class IobCobCalculatorPlugin implements PluginBase {
for (int index = iobTable.size() - 1; index >= 0; index--) { for (int index = iobTable.size() - 1; index >= 0; index--) {
if (iobTable.keyAt(index) > time) { if (iobTable.keyAt(index) > time) {
if (Config.logAutosensData) if (Config.logAutosensData)
if (Config.logAutosensData) if (Config.logAutosensData)
log.debug("Removing from iobTable: " + new Date(iobTable.keyAt(index)).toLocaleString()); log.debug("Removing from iobTable: " + new Date(iobTable.keyAt(index)).toLocaleString());
iobTable.removeAt(index); iobTable.removeAt(index);
} else { } else {
break; break;

View file

@ -1,8 +1,10 @@
package info.nightscout.androidaps.plugins.IobCobCalculator.events; package info.nightscout.androidaps.plugins.IobCobCalculator.events;
import info.nightscout.androidaps.events.EventLoop;
/** /**
* Created by mike on 30.04.2017. * Created by mike on 30.04.2017.
*/ */
public class EventAutosensCalculationFinished { public class EventAutosensCalculationFinished extends EventLoop {
} }

View file

@ -1,10 +1,12 @@
package info.nightscout.androidaps.plugins.IobCobCalculator.events; package info.nightscout.androidaps.plugins.IobCobCalculator.events;
import info.nightscout.androidaps.events.Event;
/** /**
* Created by mike on 26.04.2017. * Created by mike on 26.04.2017.
*/ */
public class EventNewHistoryData { public class EventNewHistoryData extends Event {
public long time = 0; public long time = 0;
public EventNewHistoryData(long time) { public EventNewHistoryData(long time) {

View file

@ -7,9 +7,12 @@ import android.text.Spanned;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.utils.DecimalFormatter; import info.nightscout.utils.DecimalFormatter;
@ -17,19 +20,22 @@ import info.nightscout.utils.DecimalFormatter;
* Created by mike on 09.06.2016. * Created by mike on 09.06.2016.
*/ */
public class APSResult { public class APSResult {
private static Logger log = LoggerFactory.getLogger(APSResult.class);
public String reason; public String reason;
public double rate; public double rate;
public int duration; public int duration;
public boolean changeRequested = false; public boolean changeRequested = false;
@Override @Override
public String toString() { public String toString() {
final ConfigBuilderPlugin configBuilder = MainApp.getConfigBuilder(); final PumpInterface pump = ConfigBuilderPlugin.getActivePump();
if (changeRequested) { if (changeRequested) {
if (rate == 0 && duration == 0) if (rate == 0 && duration == 0)
return MainApp.sResources.getString(R.string.canceltemp); return MainApp.sResources.getString(R.string.canceltemp);
else else
return MainApp.sResources.getString(R.string.rate) + ": " + DecimalFormatter.to2Decimal(rate) + " U/h " + return MainApp.sResources.getString(R.string.rate) + ": " + DecimalFormatter.to2Decimal(rate) + " U/h " +
"(" + DecimalFormatter.to2Decimal(rate/configBuilder.getBaseBasalRate() *100) + "%)\n" + "(" + DecimalFormatter.to2Decimal(rate / pump.getBaseBasalRate() * 100) + "%)\n" +
MainApp.sResources.getString(R.string.duration) + ": " + DecimalFormatter.to0Decimal(duration) + " min\n" + MainApp.sResources.getString(R.string.duration) + ": " + DecimalFormatter.to0Decimal(duration) + " min\n" +
MainApp.sResources.getString(R.string.reason) + ": " + reason; MainApp.sResources.getString(R.string.reason) + ": " + reason;
} else } else
@ -37,13 +43,13 @@ public class APSResult {
} }
public Spanned toSpanned() { public Spanned toSpanned() {
final ConfigBuilderPlugin configBuilder = MainApp.getConfigBuilder(); final PumpInterface pump = ConfigBuilderPlugin.getActivePump();
if (changeRequested) { if (changeRequested) {
String ret = ""; String ret = "";
if (rate == 0 && duration == 0) ret = MainApp.sResources.getString(R.string.canceltemp); if (rate == 0 && duration == 0) ret = MainApp.sResources.getString(R.string.canceltemp);
else else
ret = "<b>" + MainApp.sResources.getString(R.string.rate) + "</b>: " + DecimalFormatter.to2Decimal(rate) + " U/h " + ret = "<b>" + MainApp.sResources.getString(R.string.rate) + "</b>: " + DecimalFormatter.to2Decimal(rate) + " U/h " +
"(" + DecimalFormatter.to2Decimal(rate/configBuilder.getBaseBasalRate() *100) + "%) <br>" + "(" + DecimalFormatter.to2Decimal(rate / pump.getBaseBasalRate() * 100) + "%) <br>" +
"<b>" + MainApp.sResources.getString(R.string.duration) + "</b>: " + DecimalFormatter.to2Decimal(duration) + " min<br>" + "<b>" + MainApp.sResources.getString(R.string.duration) + "</b>: " + DecimalFormatter.to2Decimal(duration) + " min<br>" +
"<b>" + MainApp.sResources.getString(R.string.reason) + "</b>: " + reason.replace("<", "&lt;").replace(">", "&gt;"); "<b>" + MainApp.sResources.getString(R.string.reason) + "</b>: " + reason.replace("<", "&lt;").replace(">", "&gt;");
return Html.fromHtml(ret); return Html.fromHtml(ret);
@ -72,7 +78,7 @@ public class APSResult {
json.put("reason", reason); json.put("reason", reason);
} }
} catch (JSONException e) { } catch (JSONException e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
return json; return json;
} }

View file

@ -397,7 +397,7 @@ public class DeviceStatus {
if (uploaderBattery != 0) record.put("uploaderBattery", uploaderBattery); if (uploaderBattery != 0) record.put("uploaderBattery", uploaderBattery);
if (created_at != null) record.put("created_at" , created_at); if (created_at != null) record.put("created_at" , created_at);
} catch (JSONException e) { } catch (JSONException e) {
e.printStackTrace(); log.error("Unhandled exception", e);
} }
return record; return record;
} }

View file

@ -9,6 +9,7 @@ import android.view.ViewGroup;
import android.widget.Button; import android.widget.Button;
import android.widget.TextView; import android.widget.TextView;
import com.crashlytics.android.Crashlytics;
import com.crashlytics.android.answers.Answers; import com.crashlytics.android.answers.Answers;
import com.crashlytics.android.answers.CustomEvent; import com.crashlytics.android.answers.CustomEvent;
import com.squareup.otto.Subscribe; import com.squareup.otto.Subscribe;
@ -25,15 +26,6 @@ import info.nightscout.androidaps.plugins.Loop.events.EventLoopUpdateGui;
public class LoopFragment extends SubscriberFragment implements View.OnClickListener { public class LoopFragment extends SubscriberFragment implements View.OnClickListener {
private static Logger log = LoggerFactory.getLogger(LoopFragment.class); private static Logger log = LoggerFactory.getLogger(LoopFragment.class);
private static LoopPlugin loopPlugin;
public static LoopPlugin getPlugin() {
if (loopPlugin == null){
loopPlugin = new LoopPlugin();
}
return loopPlugin;
}
Button runNowButton; Button runNowButton;
TextView lastRunView; TextView lastRunView;
TextView lastEnactView; TextView lastEnactView;
@ -46,19 +38,25 @@ public class LoopFragment extends SubscriberFragment implements View.OnClickList
@Override @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) { Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.loop_fragment, container, false); try {
View view = inflater.inflate(R.layout.loop_fragment, container, false);
lastRunView = (TextView) view.findViewById(R.id.loop_lastrun); lastRunView = (TextView) view.findViewById(R.id.loop_lastrun);
lastEnactView = (TextView) view.findViewById(R.id.loop_lastenact); lastEnactView = (TextView) view.findViewById(R.id.loop_lastenact);
sourceView = (TextView) view.findViewById(R.id.loop_source); sourceView = (TextView) view.findViewById(R.id.loop_source);
requestView = (TextView) view.findViewById(R.id.loop_request); requestView = (TextView) view.findViewById(R.id.loop_request);
constraintsProcessedView = (TextView) view.findViewById(R.id.loop_constraintsprocessed); constraintsProcessedView = (TextView) view.findViewById(R.id.loop_constraintsprocessed);
setByPumpView = (TextView) view.findViewById(R.id.loop_setbypump); setByPumpView = (TextView) view.findViewById(R.id.loop_setbypump);
runNowButton = (Button) view.findViewById(R.id.loop_run); runNowButton = (Button) view.findViewById(R.id.loop_run);
runNowButton.setOnClickListener(this); runNowButton.setOnClickListener(this);
updateGUI(); updateGUI();
return view; return view;
} catch (Exception e) {
Crashlytics.logException(e);
}
return null;
} }
@Override @Override
@ -69,7 +67,7 @@ public class LoopFragment extends SubscriberFragment implements View.OnClickList
Thread thread = new Thread(new Runnable() { Thread thread = new Thread(new Runnable() {
@Override @Override
public void run() { public void run() {
getPlugin().invoke("Loop button", true); LoopPlugin.getPlugin().invoke("Loop button", true);
} }
}); });
thread.start(); thread.start();
@ -105,13 +103,13 @@ public class LoopFragment extends SubscriberFragment implements View.OnClickList
activity.runOnUiThread(new Runnable() { activity.runOnUiThread(new Runnable() {
@Override @Override
public void run() { public void run() {
if (getPlugin().lastRun != null) { if (LoopPlugin.lastRun != null) {
requestView.setText(getPlugin().lastRun.request != null ? getPlugin().lastRun.request.toSpanned() : ""); requestView.setText(LoopPlugin.lastRun.request != null ? LoopPlugin.lastRun.request.toSpanned() : "");
constraintsProcessedView.setText(getPlugin().lastRun.constraintsProcessed != null ? getPlugin().lastRun.constraintsProcessed.toSpanned() : ""); constraintsProcessedView.setText(LoopPlugin.lastRun.constraintsProcessed != null ? LoopPlugin.lastRun.constraintsProcessed.toSpanned() : "");
setByPumpView.setText(getPlugin().lastRun.setByPump != null ? getPlugin().lastRun.setByPump.toSpanned() : ""); setByPumpView.setText(LoopPlugin.lastRun.setByPump != null ? LoopPlugin.lastRun.setByPump.toSpanned() : "");
sourceView.setText(getPlugin().lastRun.source != null ? getPlugin().lastRun.source : ""); sourceView.setText(LoopPlugin.lastRun.source != null ? LoopPlugin.lastRun.source : "");
lastRunView.setText(getPlugin().lastRun.lastAPSRun != null && getPlugin().lastRun.lastAPSRun.getTime() != 0 ? getPlugin().lastRun.lastAPSRun.toLocaleString() : ""); lastRunView.setText(LoopPlugin.lastRun.lastAPSRun != null && LoopPlugin.lastRun.lastAPSRun.getTime() != 0 ? LoopPlugin.lastRun.lastAPSRun.toLocaleString() : "");
lastEnactView.setText(getPlugin().lastRun.lastEnact != null && getPlugin().lastRun.lastEnact.getTime() != 0 ? getPlugin().lastRun.lastEnact.toLocaleString() : ""); lastEnactView.setText(LoopPlugin.lastRun.lastEnact != null && LoopPlugin.lastRun.lastEnact.getTime() != 0 ? LoopPlugin.lastRun.lastEnact.toLocaleString() : "");
} }
} }
}); });

View file

@ -6,15 +6,12 @@ import android.app.PendingIntent;
import android.app.TaskStackBuilder; import android.app.TaskStackBuilder;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.os.Handler;
import android.os.HandlerThread;
import android.support.v7.app.NotificationCompat; import android.support.v7.app.NotificationCompat;
import com.crashlytics.android.answers.Answers; import com.crashlytics.android.answers.Answers;
import com.crashlytics.android.answers.CustomEvent; import com.crashlytics.android.answers.CustomEvent;
import com.squareup.otto.Subscribe; import com.squareup.otto.Subscribe;
import org.json.JSONException;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -31,14 +28,14 @@ import info.nightscout.androidaps.events.EventTreatmentChange;
import info.nightscout.androidaps.interfaces.APSInterface; import info.nightscout.androidaps.interfaces.APSInterface;
import info.nightscout.androidaps.interfaces.ConstraintsInterface; import info.nightscout.androidaps.interfaces.ConstraintsInterface;
import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.Loop.events.EventLoopSetLastRunGui; import info.nightscout.androidaps.plugins.Loop.events.EventLoopSetLastRunGui;
import info.nightscout.androidaps.plugins.Loop.events.EventLoopUpdateGui; import info.nightscout.androidaps.plugins.Loop.events.EventLoopUpdateGui;
import info.nightscout.androidaps.plugins.Loop.events.EventNewOpenLoopNotification; import info.nightscout.androidaps.plugins.Loop.events.EventNewOpenLoopNotification;
import info.nightscout.androidaps.plugins.OpenAPSAMA.OpenAPSAMAPlugin; import info.nightscout.androidaps.queue.Callback;
import info.nightscout.utils.NSUpload; import info.nightscout.utils.NSUpload;
import info.nightscout.utils.SP; import info.nightscout.utils.SP;
import info.nightscout.utils.SafeParse;
/** /**
* Created by mike on 05.08.2016. * Created by mike on 05.08.2016.
@ -46,14 +43,21 @@ import info.nightscout.utils.SafeParse;
public class LoopPlugin implements PluginBase { public class LoopPlugin implements PluginBase {
private static Logger log = LoggerFactory.getLogger(LoopPlugin.class); private static Logger log = LoggerFactory.getLogger(LoopPlugin.class);
private static Handler sHandler; private static LoopPlugin loopPlugin;
private static HandlerThread sHandlerThread;
public static LoopPlugin getPlugin() {
if (loopPlugin == null) {
loopPlugin = new LoopPlugin();
}
return loopPlugin;
}
private boolean fragmentEnabled = false; private boolean fragmentEnabled = false;
private boolean fragmentVisible = false; private boolean fragmentVisible = false;
private long loopSuspendedTill = 0L; // end of manual loop suspend private long loopSuspendedTill = 0L; // end of manual loop suspend
private boolean isSuperBolus = false; private boolean isSuperBolus = false;
private boolean isDisconnected = false;
public class LastRun { public class LastRun {
public APSResult request = null; public APSResult request = null;
@ -68,14 +72,10 @@ public class LoopPlugin implements PluginBase {
static public LastRun lastRun = null; static public LastRun lastRun = null;
public LoopPlugin() { public LoopPlugin() {
if (sHandlerThread == null) {
sHandlerThread = new HandlerThread(LoopPlugin.class.getSimpleName());
sHandlerThread.start();
sHandler = new Handler(sHandlerThread.getLooper());
}
MainApp.bus().register(this); MainApp.bus().register(this);
loopSuspendedTill = SP.getLong("loopSuspendedTill", 0L); loopSuspendedTill = SP.getLong("loopSuspendedTill", 0L);
isSuperBolus = SP.getBoolean("isSuperBolus", false); isSuperBolus = SP.getBoolean("isSuperBolus", false);
isDisconnected = SP.getBoolean("isDisconnected", false);
} }
@Override @Override
@ -96,7 +96,7 @@ public class LoopPlugin implements PluginBase {
@Override @Override
public String getNameShort() { public String getNameShort() {
String name = MainApp.sResources.getString(R.string.loop_shortname); String name = MainApp.sResources.getString(R.string.loop_shortname);
if (!name.trim().isEmpty()){ if (!name.trim().isEmpty()) {
//only if translation exists //only if translation exists
return name; return name;
} }
@ -106,12 +106,14 @@ public class LoopPlugin implements PluginBase {
@Override @Override
public boolean isEnabled(int type) { public boolean isEnabled(int type) {
return type == LOOP && fragmentEnabled && MainApp.getConfigBuilder().getPumpDescription().isTempBasalCapable; boolean pumpCapable = ConfigBuilderPlugin.getActivePump() == null || ConfigBuilderPlugin.getActivePump().getPumpDescription().isTempBasalCapable;
return type == LOOP && fragmentEnabled && pumpCapable;
} }
@Override @Override
public boolean isVisibleInTabs(int type) { public boolean isVisibleInTabs(int type) {
return type == LOOP && fragmentVisible && MainApp.getConfigBuilder().getPumpDescription().isTempBasalCapable; boolean pumpCapable = ConfigBuilderPlugin.getActivePump() == null || ConfigBuilderPlugin.getActivePump().getPumpDescription().isTempBasalCapable;
return type == LOOP && fragmentVisible && pumpCapable;
} }
@Override @Override
@ -139,6 +141,11 @@ public class LoopPlugin implements PluginBase {
if (type == LOOP) this.fragmentVisible = fragmentVisible; if (type == LOOP) this.fragmentVisible = fragmentVisible;
} }
@Override
public int getPreferencesId() {
return R.xml.pref_closedmode;
}
@Subscribe @Subscribe
public void onStatusEvent(final EventTreatmentChange ev) { public void onStatusEvent(final EventTreatmentChange ev) {
invoke("EventTreatmentChange", true); invoke("EventTreatmentChange", true);
@ -156,13 +163,28 @@ public class LoopPlugin implements PluginBase {
public void suspendTo(long endTime) { public void suspendTo(long endTime) {
loopSuspendedTill = endTime; loopSuspendedTill = endTime;
isSuperBolus = false; isSuperBolus = false;
isDisconnected = false;
SP.putLong("loopSuspendedTill", loopSuspendedTill); SP.putLong("loopSuspendedTill", loopSuspendedTill);
SP.putBoolean("isSuperBolus", isSuperBolus);
SP.putBoolean("isDisconnected", isDisconnected);
} }
public void superBolusTo(long endTime) { public void superBolusTo(long endTime) {
loopSuspendedTill = endTime; loopSuspendedTill = endTime;
isSuperBolus = true; isSuperBolus = true;
isDisconnected = false;
SP.putLong("loopSuspendedTill", loopSuspendedTill); SP.putLong("loopSuspendedTill", loopSuspendedTill);
SP.putBoolean("isSuperBolus", isSuperBolus);
SP.putBoolean("isDisconnected", isDisconnected);
}
public void disconnectTo(long endTime) {
loopSuspendedTill = endTime;
isSuperBolus = false;
isDisconnected = true;
SP.putLong("loopSuspendedTill", loopSuspendedTill);
SP.putBoolean("isSuperBolus", isSuperBolus);
SP.putBoolean("isDisconnected", isDisconnected);
} }
public int minutesToEndOfSuspend() { public int minutesToEndOfSuspend() {
@ -194,7 +216,7 @@ public class LoopPlugin implements PluginBase {
return true; return true;
} }
public boolean isSuperBolus() { public boolean isSuperBolus() {
if (loopSuspendedTill == 0) if (loopSuspendedTill == 0)
return false; return false;
@ -208,6 +230,19 @@ public class LoopPlugin implements PluginBase {
return isSuperBolus; return isSuperBolus;
} }
public boolean isDisconnected() {
if (loopSuspendedTill == 0)
return false;
long now = System.currentTimeMillis();
if (loopSuspendedTill <= now) { // time exceeded
suspendTo(0L);
return false;
}
return isDisconnected;
}
public void invoke(String initiator, boolean allowNotification) { public void invoke(String initiator, boolean allowNotification) {
try { try {
if (Config.logFunctionCalls) if (Config.logFunctionCalls)
@ -218,10 +253,10 @@ public class LoopPlugin implements PluginBase {
MainApp.bus().post(new EventLoopSetLastRunGui(MainApp.sResources.getString(R.string.loopdisabled))); MainApp.bus().post(new EventLoopSetLastRunGui(MainApp.sResources.getString(R.string.loopdisabled)));
return; return;
} }
final ConfigBuilderPlugin configBuilder = MainApp.getConfigBuilder(); final PumpInterface pump = ConfigBuilderPlugin.getActivePump();
APSResult result = null; APSResult result = null;
if (configBuilder == null || !isEnabled(PluginBase.LOOP)) if (!isEnabled(PluginBase.LOOP))
return; return;
if (isSuspended()) { if (isSuspended()) {
@ -230,22 +265,22 @@ public class LoopPlugin implements PluginBase {
return; return;
} }
if (configBuilder.isSuspended()) { if (pump.isSuspended()) {
log.debug(MainApp.sResources.getString(R.string.pumpsuspended)); log.debug(MainApp.sResources.getString(R.string.pumpsuspended));
MainApp.bus().post(new EventLoopSetLastRunGui(MainApp.sResources.getString(R.string.pumpsuspended))); MainApp.bus().post(new EventLoopSetLastRunGui(MainApp.sResources.getString(R.string.pumpsuspended)));
return; return;
} }
if (configBuilder.getProfile() == null) { if (MainApp.getConfigBuilder().getProfile() == null) {
log.debug(MainApp.sResources.getString(R.string.noprofileselected)); log.debug(MainApp.sResources.getString(R.string.noprofileselected));
MainApp.bus().post(new EventLoopSetLastRunGui(MainApp.sResources.getString(R.string.noprofileselected))); MainApp.bus().post(new EventLoopSetLastRunGui(MainApp.sResources.getString(R.string.noprofileselected)));
return; return;
} }
// Check if pump info is loaded // Check if pump info is loaded
if (configBuilder.getBaseBasalRate() < 0.01d) return; if (pump.getBaseBasalRate() < 0.01d) return;
APSInterface usedAPS = configBuilder.getActiveAPS(); APSInterface usedAPS = MainApp.getConfigBuilder().getActiveAPS();
if (usedAPS != null && ((PluginBase) usedAPS).isEnabled(PluginBase.APS)) { if (usedAPS != null && ((PluginBase) usedAPS).isEnabled(PluginBase.APS)) {
usedAPS.invoke(initiator); usedAPS.invoke(initiator);
result = usedAPS.getLastAPSResult(); result = usedAPS.getLastAPSResult();
@ -268,20 +303,19 @@ public class LoopPlugin implements PluginBase {
lastRun.source = ((PluginBase) usedAPS).getName(); lastRun.source = ((PluginBase) usedAPS).getName();
lastRun.setByPump = null; lastRun.setByPump = null;
if (constraintsInterface.isClosedModeEnabled()) { if (constraintsInterface.isClosedModeEnabled()) {
if (result.changeRequested) { if (result.changeRequested) {
final PumpEnactResult waiting = new PumpEnactResult(); final PumpEnactResult waiting = new PumpEnactResult();
final PumpEnactResult previousResult = lastRun.setByPump; final PumpEnactResult previousResult = lastRun.setByPump;
waiting.queued = true; waiting.queued = true;
lastRun.setByPump = waiting; lastRun.setByPump = waiting;
MainApp.bus().post(new EventLoopUpdateGui()); MainApp.bus().post(new EventLoopUpdateGui());
sHandler.post(new Runnable() { MainApp.getConfigBuilder().applyAPSRequest(resultAfterConstraints, new Callback() {
@Override @Override
public void run() { public void run() {
final PumpEnactResult applyResult = configBuilder.applyAPSRequest(resultAfterConstraints);
Answers.getInstance().logCustom(new CustomEvent("APSRequest")); Answers.getInstance().logCustom(new CustomEvent("APSRequest"));
if (applyResult.enacted || applyResult.success) { if (result.enacted || result.success) {
lastRun.setByPump = applyResult; lastRun.setByPump = result;
lastRun.lastEnact = lastRun.lastAPSRun; lastRun.lastEnact = lastRun.lastAPSRun;
} else { } else {
lastRun.setByPump = previousResult; lastRun.setByPump = previousResult;

View file

@ -1,9 +1,11 @@
package info.nightscout.androidaps.plugins.Loop.events; package info.nightscout.androidaps.plugins.Loop.events;
import info.nightscout.androidaps.events.EventUpdateGui;
/** /**
* Created by mike on 05.08.2016. * Created by mike on 05.08.2016.
*/ */
public class EventLoopSetLastRunGui { public class EventLoopSetLastRunGui extends EventUpdateGui {
public String text = null; public String text = null;
public EventLoopSetLastRunGui(String text) { public EventLoopSetLastRunGui(String text) {

View file

@ -1,7 +1,9 @@
package info.nightscout.androidaps.plugins.Loop.events; package info.nightscout.androidaps.plugins.Loop.events;
import info.nightscout.androidaps.events.EventUpdateGui;
/** /**
* Created by mike on 05.08.2016. * Created by mike on 05.08.2016.
*/ */
public class EventLoopUpdateGui { public class EventLoopUpdateGui extends EventUpdateGui {
} }

View file

@ -1,7 +1,9 @@
package info.nightscout.androidaps.plugins.Loop.events; package info.nightscout.androidaps.plugins.Loop.events;
import info.nightscout.androidaps.events.Event;
/** /**
* Created by mike on 07.08.2016. * Created by mike on 07.08.2016.
*/ */
public class EventNewOpenLoopNotification { public class EventNewOpenLoopNotification extends Event {
} }

Some files were not shown because too many files have changed in this diff Show more