Advertisement
Guest User

Untitled

a guest
Apr 19th, 2019
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 36.00 KB | None | 0 0
  1. package info.nightscout.androidaps.plugins.pump.medtronic.data;
  2.  
  3. import com.google.common.base.Splitter;
  4. import com.google.gson.Gson;
  5.  
  6. import org.joda.time.LocalDateTime;
  7. import org.joda.time.Minutes;
  8. import org.slf4j.Logger;
  9. import org.slf4j.LoggerFactory;
  10.  
  11. import java.util.ArrayList;
  12. import java.util.Collections;
  13. import java.util.Date;
  14. import java.util.GregorianCalendar;
  15. import java.util.HashMap;
  16. import java.util.List;
  17. import java.util.Map;
  18.  
  19. import info.nightscout.androidaps.MainApp;
  20. import info.nightscout.androidaps.data.DetailedBolusInfo;
  21. import info.nightscout.androidaps.db.DatabaseHelper;
  22. import info.nightscout.androidaps.db.ExtendedBolus;
  23. import info.nightscout.androidaps.db.Source;
  24. import info.nightscout.androidaps.db.TDD;
  25. import info.nightscout.androidaps.events.EventTreatmentChange;
  26. import info.nightscout.androidaps.logging.L;
  27. import info.nightscout.androidaps.plugins.configBuilder.DetailedBolusInfoStorage;
  28. import info.nightscout.androidaps.plugins.pump.common.utils.DateTimeUtil;
  29. import info.nightscout.androidaps.plugins.pump.medtronic.MedtronicPumpPlugin;
  30. import info.nightscout.androidaps.plugins.pump.medtronic.comm.history.pump.MedtronicPumpHistoryDecoder;
  31. import info.nightscout.androidaps.plugins.pump.medtronic.comm.history.pump.PumpHistoryEntry;
  32. import info.nightscout.androidaps.plugins.pump.medtronic.comm.history.pump.PumpHistoryEntryType;
  33. import info.nightscout.androidaps.plugins.pump.medtronic.comm.history.pump.PumpHistoryResult;
  34. import info.nightscout.androidaps.plugins.pump.medtronic.data.dto.BasalProfile;
  35. import info.nightscout.androidaps.plugins.pump.medtronic.data.dto.BolusDTO;
  36. import info.nightscout.androidaps.plugins.pump.medtronic.data.dto.ClockDTO;
  37. import info.nightscout.androidaps.plugins.pump.medtronic.data.dto.DailyTotalsDTO;
  38. import info.nightscout.androidaps.plugins.pump.medtronic.driver.MedtronicPumpStatus;
  39. import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil;
  40. import info.nightscout.androidaps.plugins.treatments.Treatment;
  41. import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
  42.  
  43. //import info.nightscout.androidaps.plugins.pump.medtronic.MedtronicPumpPlugin;
  44.  
  45. /**
  46. * Created by andy on 10/12/18.
  47. */
  48.  
  49. public class MedtronicHistoryData {
  50.  
  51. private static final Logger LOG = LoggerFactory.getLogger(MedtronicHistoryData.class);
  52.  
  53. private List<PumpHistoryEntry> allHistory = null;
  54. private List<PumpHistoryEntry> newHistory = null;
  55.  
  56. // private LocalDateTime previousLastHistoryRecordTime;
  57. private Long lastHistoryRecordTime;
  58. private boolean isInit = false;
  59.  
  60. private Gson gsonPretty;
  61. private List<PumpHistoryEntry> fakeTBRs;
  62.  
  63. DatabaseHelper databaseHelper = MainApp.getDbHelper();
  64.  
  65.  
  66. public MedtronicHistoryData() {
  67. this.allHistory = new ArrayList<>();
  68. this.gsonPretty = MedtronicPumpPlugin.gsonInstancePretty;
  69. }
  70.  
  71.  
  72. /**
  73. * Add New History entries
  74. *
  75. * @param result PumpHistoryResult instance
  76. */
  77. public void addNewHistory(PumpHistoryResult result) {
  78.  
  79. List<PumpHistoryEntry> validEntries = result.getValidEntries();
  80.  
  81. List<PumpHistoryEntry> newEntries = new ArrayList<>();
  82.  
  83. for (PumpHistoryEntry validEntry : validEntries) {
  84.  
  85. if (!this.allHistory.contains(validEntry)) {
  86. newEntries.add(validEntry);
  87. }
  88. }
  89.  
  90. this.newHistory = newEntries;
  91.  
  92. showLogs("List of history (before filtering): ", MedtronicPumpPlugin.gsonInstance.toJson(this.newHistory));
  93. }
  94.  
  95.  
  96. public static void showLogs(String header, String data) {
  97.  
  98. if (header != null) {
  99. LOG.debug(header);
  100. }
  101.  
  102. for (final String token : Splitter.fixedLength(3500).split(data)) {
  103. LOG.debug("{}", token);
  104. }
  105. }
  106.  
  107.  
  108. public List<PumpHistoryEntry> getAllHistory() {
  109. return this.allHistory;
  110. }
  111.  
  112.  
  113. public void filterNewEntries() {
  114.  
  115. List<PumpHistoryEntry> newHistory2 = new ArrayList<>();
  116. List<PumpHistoryEntry> TBRs = new ArrayList<>();
  117. long atechDate = DateTimeUtil.toATechDate(new GregorianCalendar());
  118.  
  119. for (PumpHistoryEntry pumpHistoryEntry : newHistory) {
  120.  
  121. if (!this.allHistory.contains(pumpHistoryEntry)) {
  122.  
  123. PumpHistoryEntryType type = pumpHistoryEntry.getEntryType();
  124.  
  125. if (type == PumpHistoryEntryType.TempBasalRate || type == PumpHistoryEntryType.TempBasalDuration) {
  126. TBRs.add(pumpHistoryEntry);
  127. } else {
  128.  
  129. if (type == PumpHistoryEntryType.EndResultTotals) {
  130. if (!DateTimeUtil.isSameDay(atechDate, pumpHistoryEntry.atechDateTime)) {
  131. newHistory2.add(pumpHistoryEntry);
  132. }
  133. } else {
  134. newHistory2.add(pumpHistoryEntry);
  135. }
  136.  
  137. }
  138. // }
  139. }
  140.  
  141. }
  142.  
  143. TBRs = preProcessTBRs(TBRs);
  144.  
  145. newHistory2.addAll(TBRs);
  146.  
  147. this.newHistory = newHistory2;
  148.  
  149. sort(this.newHistory);
  150.  
  151. LOG.debug("New History entries found: {}", this.newHistory.size());
  152. showLogs("List of history (after filtering): ", MedtronicPumpPlugin.gsonInstance.toJson(this.newHistory));
  153.  
  154. }
  155.  
  156.  
  157. public void finalizeNewHistoryRecords() {
  158.  
  159. if ((newHistory == null) || (newHistory.size() == 0))
  160. return;
  161.  
  162. PumpHistoryEntry pheLast = newHistory.get(0);
  163.  
  164. for (PumpHistoryEntry pumpHistoryEntry : newHistory) {
  165.  
  166. if (!this.allHistory.contains(pumpHistoryEntry)) {
  167. this.allHistory.add(pumpHistoryEntry);
  168. }
  169.  
  170. if (pumpHistoryEntry.isAfter(pheLast.atechDateTime)) {
  171. pheLast = pumpHistoryEntry;
  172. }
  173.  
  174. }
  175.  
  176. this.setLastHistoryRecordTime(pheLast.atechDateTime);
  177.  
  178. LocalDateTime dt = DateTimeUtil.toLocalDateTime(pheLast.atechDateTime);
  179. dt = dt.minusDays(1); // we keep 24 hours
  180.  
  181. long dtRemove = DateTimeUtil.toATechDate(dt);
  182.  
  183. List<PumpHistoryEntry> removeList = new ArrayList<>();
  184.  
  185. for (PumpHistoryEntry pumpHistoryEntry : allHistory) {
  186.  
  187. if (!pumpHistoryEntry.isAfter(dtRemove)) {
  188. removeList.add(pumpHistoryEntry);
  189. }
  190. }
  191.  
  192. this.allHistory.removeAll(removeList);
  193.  
  194. this.sort(this.allHistory);
  195.  
  196. LOG.debug("All History records [afterFilterCount={}, removedItemsCount={}, newItemsCount={}]",
  197. allHistory.size(), removeList.size(), newHistory.size());
  198.  
  199. this.newHistory.clear();
  200.  
  201. }
  202.  
  203.  
  204. public boolean hasRelevantConfigurationChanged() {
  205.  
  206. return getStateFromFilteredList( //
  207. PumpHistoryEntryType.ChangeBasalPattern, //
  208. PumpHistoryEntryType.ClearSettings, //
  209. PumpHistoryEntryType.SaveSettings, //
  210. PumpHistoryEntryType.ChangeMaxBolus, //
  211. PumpHistoryEntryType.ChangeMaxBasal, //
  212. PumpHistoryEntryType.ChangeTempBasalType);
  213.  
  214. }
  215.  
  216.  
  217. private boolean isCollectionEmpty(List col) {
  218. return (col == null || col.isEmpty());
  219. }
  220.  
  221.  
  222. public boolean isPumpSuspended() {
  223.  
  224. List<PumpHistoryEntry> items = getDataForSuspends(false);
  225.  
  226. showLogs("isPumpSuspended: ", MedtronicPumpPlugin.gsonInstancePretty.toJson(items));
  227.  
  228. if (!items.isEmpty()) {
  229.  
  230. PumpHistoryEntryType pumpHistoryEntryType = items.get(0).getEntryType();
  231.  
  232. boolean isSuspended = !(pumpHistoryEntryType == PumpHistoryEntryType.TempBasalCombined || //
  233. pumpHistoryEntryType == PumpHistoryEntryType.BasalProfileStart || //
  234. pumpHistoryEntryType == PumpHistoryEntryType.Bolus || //
  235. pumpHistoryEntryType == PumpHistoryEntryType.PumpResume || //
  236. pumpHistoryEntryType == PumpHistoryEntryType.Prime);
  237.  
  238. LOG.debug("isPumpSuspended. Last entry type={}, isSuspended={}", pumpHistoryEntryType, isSuspended);
  239.  
  240. return isSuspended;
  241. } else
  242. return false;
  243.  
  244. }
  245.  
  246.  
  247. private List<PumpHistoryEntry> getDataForSuspends(boolean forHistory) {
  248.  
  249. List<PumpHistoryEntry> newAndAll = new ArrayList<>();
  250.  
  251. if (!isCollectionEmpty(this.allHistory)) {
  252.  
  253. if (forHistory) {
  254. // TODO we filter all history ang get last 2
  255. } else {
  256. newAndAll.addAll(this.allHistory);
  257. }
  258. }
  259.  
  260. if (!isCollectionEmpty(this.newHistory)) {
  261.  
  262. for (PumpHistoryEntry pumpHistoryEntry : newHistory) {
  263. if (!newAndAll.contains(pumpHistoryEntry)) {
  264. newAndAll.add(pumpHistoryEntry);
  265. }
  266. }
  267. }
  268.  
  269. if (newAndAll.isEmpty())
  270. return newAndAll;
  271.  
  272. this.sort(newAndAll);
  273.  
  274. List<PumpHistoryEntry> newAndAll2 = getFilteredItems(newAndAll, //
  275. PumpHistoryEntryType.Bolus, //
  276. PumpHistoryEntryType.TempBasalCombined, //
  277. PumpHistoryEntryType.Prime, //
  278. PumpHistoryEntryType.PumpSuspend, //
  279. PumpHistoryEntryType.PumpResume, //
  280. PumpHistoryEntryType.Rewind, //
  281. PumpHistoryEntryType.NoDeliveryAlarm, //
  282. PumpHistoryEntryType.BasalProfileStart);
  283.  
  284. if (!forHistory) {
  285. newAndAll2 = filterPumpSuspend(newAndAll2, 10); // just last 10 (of relevant), for history we already
  286. // filtered
  287. }
  288.  
  289. return newAndAll2;
  290.  
  291. }
  292.  
  293.  
  294. private List<PumpHistoryEntry> filterPumpSuspend(List<PumpHistoryEntry> newAndAll, int filterCount) {
  295.  
  296. if (newAndAll.size() <= filterCount) {
  297. return newAndAll;
  298. }
  299.  
  300. List<PumpHistoryEntry> newAndAllOut = new ArrayList<>();
  301.  
  302. for (int i = 0; i < filterCount; i++) {
  303. newAndAllOut.add(newAndAll.get(i));
  304. }
  305.  
  306. return newAndAllOut;
  307. }
  308.  
  309.  
  310. /**
  311. * Process History Data: Boluses(Treatments), TDD, TBRs, Suspend-Resume (or other pump stops: battery, prime)
  312. */
  313. public void processNewHistoryData() {
  314.  
  315. // TDD
  316. List<PumpHistoryEntry> tdds = getFilteredItems(PumpHistoryEntryType.EndResultTotals, getTDDType());
  317.  
  318. LOG.debug("ProcessHistoryData: TDD [count={}, items={}]", tdds.size(), gsonPretty.toJson(tdds));
  319.  
  320. if (!isCollectionEmpty(tdds)) {
  321. processTDDs(tdds);
  322. }
  323.  
  324. pumpTime = MedtronicUtil.getPumpTime();
  325.  
  326. // Bolus
  327. List<PumpHistoryEntry> treatments = getFilteredItems(PumpHistoryEntryType.Bolus);
  328.  
  329. LOG.debug("ProcessHistoryData: Bolus [count={}, items={}]", treatments.size(), gsonPretty.toJson(treatments));
  330.  
  331. if (treatments.size() > 0) {
  332. processBoluses(treatments);
  333. }
  334.  
  335. // TBR
  336. List<PumpHistoryEntry> tbrs = getFilteredItems(PumpHistoryEntryType.TempBasalCombined);
  337.  
  338. LOG.debug("ProcessHistoryData: TBRs [count={}, items={}]", tbrs.size(), gsonPretty.toJson(tbrs));
  339.  
  340. if (tbrs.size() > 0) {
  341. // processTBRs(tbrs);
  342. }
  343.  
  344. // Suspends (for suspends/resume, fakeTBR)
  345. List<PumpHistoryEntry> suspends = getSuspends();
  346.  
  347. LOG.debug("ProcessHistoryData: FakeTBRs (suspend/resume) [count={}, items={}]", suspends.size(),
  348. gsonPretty.toJson(suspends));
  349.  
  350. if (suspends.size() > 0) {
  351. // processSuspends(treatments);
  352. }
  353. }
  354.  
  355. ClockDTO pumpTime;
  356.  
  357.  
  358. public void processTDDs(List<PumpHistoryEntry> tddsIn) {
  359.  
  360. List<PumpHistoryEntry> tdds = filterTDDs(tddsIn);
  361.  
  362. // /pumpTime = MedtronicUtil.getPumpTime();
  363.  
  364. LOG.error(getLogPrefix() + "TDDs found: {}. Not processed.\n{}", tdds.size(), gsonPretty.toJson(tdds));
  365.  
  366. // FIXME tdd
  367. List<TDD> tddsDb = MainApp.getDbHelper().getTDDs(); // .getTDDsForLastXDays(3);
  368.  
  369. for (PumpHistoryEntry tdd : tdds) {
  370.  
  371. TDD tddDbEntry = findTDD(tdd.atechDateTime, tddsDb);
  372.  
  373. DailyTotalsDTO totalsDTO = (DailyTotalsDTO) tdd.getDecodedData().get("Object");
  374.  
  375. LOG.debug("DailtyTotals: {}", totalsDTO);
  376.  
  377. if (tddDbEntry == null) {
  378. TDD tddNew = new TDD();
  379. totalsDTO.setTDD(tddNew);
  380.  
  381. LOG.debug("TDD-Add: {}", tddNew);
  382.  
  383. MainApp.getDbHelper().createOrUpdateTDD(tddNew);
  384.  
  385. } else {
  386.  
  387. if (!totalsDTO.doesEqual(tddDbEntry)) {
  388. totalsDTO.setTDD(tddDbEntry);
  389.  
  390. LOG.debug("TDD-Edit: {}", tddDbEntry);
  391.  
  392. MainApp.getDbHelper().createOrUpdateTDD(tddDbEntry);
  393. }
  394. }
  395. }
  396.  
  397. }
  398.  
  399.  
  400. // TODO needs to be implemented
  401. public void processBoluses(List<PumpHistoryEntry> boluses) {
  402.  
  403. int dateDifference = getOldestDateDifference(boluses);
  404.  
  405. List<Treatment> treatmentsFromHistory = TreatmentsPlugin.getPlugin().getTreatmentsFromHistoryXMinutesAgo(
  406. dateDifference);
  407.  
  408. LOG.debug("Boluses (before filter): {}, FromDb={}", gsonPretty.toJson(boluses),
  409. gsonPretty.toJson(treatmentsFromHistory));
  410.  
  411. filterOutAlreadyAddedEntries(boluses, treatmentsFromHistory);
  412.  
  413. if (boluses.isEmpty())
  414. return;
  415.  
  416. LOG.debug("Boluses (after filter): {}, FromDb={}", gsonPretty.toJson(boluses),
  417. gsonPretty.toJson(treatmentsFromHistory));
  418.  
  419. if (treatmentsFromHistory.isEmpty()) {
  420. for (PumpHistoryEntry treatment : boluses) {
  421. LOG.debug("Add Bolus (no treatments): " + treatment);
  422. addBolus(treatment, null);
  423. }
  424. } else {
  425. for (PumpHistoryEntry treatment : boluses) {
  426. tryToGetByLocalTime(treatment.atechDateTime);
  427. Treatment treatmentDb = findTreatment(treatment, treatmentsFromHistory, dateDifference);
  428. LOG.debug("Add Bolus {} - (treatmentFromDb={}) ", treatment, treatmentDb);
  429.  
  430. addBolus(treatment, treatmentDb);
  431. }
  432. }
  433. }
  434.  
  435.  
  436. private void filterOutAlreadyAddedEntries(List<PumpHistoryEntry> boluses, List<Treatment> treatmentsFromHistory) {
  437.  
  438. List<Treatment> removeTreatmentsFromHistory = new ArrayList<>();
  439.  
  440. for (Treatment treatment : treatmentsFromHistory) {
  441.  
  442. if (treatment.pumpId != 0) {
  443.  
  444. PumpHistoryEntry selectedBolus = null;
  445.  
  446. for (PumpHistoryEntry bolus : boluses) {
  447. if (bolus.getPumpId() == treatment.pumpId) {
  448. selectedBolus = bolus;
  449. break;
  450. }
  451. }
  452.  
  453. if (selectedBolus != null)
  454. boluses.remove(selectedBolus);
  455.  
  456. removeTreatmentsFromHistory.add(treatment);
  457. }
  458. }
  459.  
  460. treatmentsFromHistory.removeAll(removeTreatmentsFromHistory);
  461.  
  462. }
  463.  
  464.  
  465. private Treatment findTreatmentOld(PumpHistoryEntry treatment, List<Treatment> treatmentsFromHistory) {
  466.  
  467. long proposedTime = DateTimeUtil.toMillisFromATD(treatment.atechDateTime);
  468.  
  469. proposedTime += (this.pumpTime.timeDifference * 1000);
  470.  
  471. treatment.phoneDateTime = proposedTime;
  472.  
  473. List<Treatment> outList = new ArrayList<>();
  474.  
  475. for (Treatment treatment1 : treatmentsFromHistory) {
  476. if ((treatment1.date > proposedTime - (5 * 60 * 1000))
  477. && (treatment1.date < proposedTime + (5 * 60 * 1000))) {
  478. outList.add(treatment1);
  479. }
  480. }
  481.  
  482. if (outList.size() == 0) {
  483. return null;
  484. } else if (outList.size() == 1) {
  485. return outList.get(0);
  486. } else {
  487. LOG.error("TODO. Multiple options: {}", outList);
  488.  
  489. Map<Treatment, Integer> data = new HashMap<>();
  490.  
  491. for (Treatment treatment1 : outList) {
  492. int diff = Math.abs((int) (treatment1.date - proposedTime));
  493. data.put(treatment1, diff);
  494. }
  495.  
  496. for (int i = 1; i < 5; i++) {
  497.  
  498. List<Treatment> outList2 = new ArrayList<>();
  499.  
  500. for (Treatment treatment1 : treatmentsFromHistory) {
  501. if ((treatment1.date > proposedTime - (i * 60 * 1000))
  502. && (treatment1.date < proposedTime + (i * 60 * 1000))) {
  503. outList2.add(treatment1);
  504. }
  505. }
  506.  
  507. LOG.error("Treatment List: (timeDiff={},count={},list={})", (i * 60 * 1000), outList2.size(),
  508. gsonPretty.toJson(outList2));
  509.  
  510. if (outList2.size() == 1) {
  511. return outList2.get(0);
  512. } else if (outList2.size() > 1) {
  513.  
  514. for (int j = 1; j < 6; j++) {
  515.  
  516. List<Treatment> outList3 = new ArrayList<>();
  517.  
  518. int ttt = (i * 60 * 1000) - (10 * j * 1000);
  519.  
  520. for (Treatment treatment1 : treatmentsFromHistory) {
  521.  
  522. if ((treatment1.date > proposedTime - ttt) && (treatment1.date < proposedTime + ttt)) {
  523. outList3.add(treatment1);
  524. }
  525. }
  526.  
  527. LOG.error("Treatment List: (timeDiff={},count={},list={})", ttt, outList3.size(),
  528. gsonPretty.toJson(outList3));
  529.  
  530. if (outList3.size() == 1) {
  531. return outList3.get(0);
  532. }
  533. } // for
  534.  
  535. } // outList2
  536. }
  537.  
  538. // TODO
  539. } // outList
  540.  
  541. // TODO
  542. return null;
  543. }
  544.  
  545.  
  546. private Treatment findTreatment(PumpHistoryEntry treatment, List<Treatment> treatmentsFromHistory,
  547. int dateDifference) {
  548.  
  549. long proposedTime = DateTimeUtil.toMillisFromATD(treatment.atechDateTime);
  550.  
  551. proposedTime += (this.pumpTime.timeDifference * 1000);
  552.  
  553. // treatment.phoneDateTime = proposedTime;
  554. Date proposedTimeDD = new Date(proposedTime);
  555.  
  556. if (treatmentsFromHistory.size() == 0) {
  557. return null;
  558. } else if (treatmentsFromHistory.size() == 1) {
  559. Treatment treatment1 = treatmentsFromHistory.get(0);
  560. LocalDateTime ldt = new LocalDateTime(treatment1.date);
  561. return treatmentsFromHistory.get(0);
  562. }
  563.  
  564. for (int min = 0; min < 5; min++) {
  565. for (int sec = 0; sec < 60; sec += 10) {
  566.  
  567. int diff = (min * 60 * 1000) + (sec * 1000);
  568.  
  569. List<Treatment> outList = new ArrayList<>();
  570.  
  571. for (Treatment treatment1 : treatmentsFromHistory) {
  572.  
  573. if ((treatment1.date > proposedTime - diff) && (treatment1.date < proposedTime + diff)) {
  574. outList.add(treatment1);
  575. }
  576. }
  577.  
  578. LOG.error("Treatments: (timeDiff=[min={},sec={}],count={},list={})", min, sec, outList.size(),
  579. gsonPretty.toJson(outList));
  580.  
  581. if (outList.size() == 1) {
  582. return outList.get(0);
  583. }
  584.  
  585. if (min == 0 && sec == 10 && outList.size() > 1) {
  586. LOG.error("Too many treatments (with too small diff): (timeDiff=[min={},sec={}],count={},list={})",
  587. min, sec, outList.size(), gsonPretty.toJson(outList));
  588.  
  589. }
  590. }
  591. }
  592.  
  593. return null;
  594.  
  595. }
  596.  
  597.  
  598. private void addBolus(PumpHistoryEntry bolus, Treatment treatment) {
  599.  
  600. BolusDTO bolusDTO = (BolusDTO) bolus.getDecodedData().get("Object");
  601.  
  602. if (treatment == null) {
  603.  
  604. // treatment.carbs = detailedBolusInfo.carbs; // TODO later support BolusWizard ??
  605.  
  606. switch (bolusDTO.getBolusType()) {
  607. case Normal: {
  608. // DetailedBolusInfo normalBolus = new DetailedBolusInfo();
  609.  
  610. DetailedBolusInfo detailedBolusInfo = DetailedBolusInfoStorage
  611. .findDetailedBolusInfo(tryToGetByLocalTime(bolus.atechDateTime));
  612. if (detailedBolusInfo == null) {
  613. detailedBolusInfo = new DetailedBolusInfo();
  614. }
  615.  
  616. detailedBolusInfo.date = tryToGetByLocalTime(bolus.atechDateTime);
  617. detailedBolusInfo.source = Source.PUMP;
  618. detailedBolusInfo.pumpId = bolus.getPumpId();
  619. detailedBolusInfo.insulin = bolusDTO.getDeliveredAmount();
  620.  
  621. boolean newRecord = TreatmentsPlugin.getPlugin().addToHistoryTreatment(detailedBolusInfo, false);
  622.  
  623. bolus.setLinkedObject(detailedBolusInfo);
  624.  
  625. // bolus.setLinkedObject(normalBolus);
  626.  
  627. // TreatmentsPlugin.getPlugin().addToHistoryTreatment(normalBolus, false);
  628.  
  629. if (L.isEnabled(L.PUMPCOMM))
  630. LOG.debug("addBolus - [date={},pumpId={}, insulin={}, newRecord={}]", detailedBolusInfo.date,
  631. detailedBolusInfo.pumpId, detailedBolusInfo.insulin, newRecord);
  632. }
  633. break;
  634.  
  635. case Audio:
  636. case Extended: {
  637. ExtendedBolus extendedBolus = new ExtendedBolus();
  638. extendedBolus.date = tryToGetByLocalTime(bolus.atechDateTime);
  639. extendedBolus.source = Source.PUMP;
  640. extendedBolus.insulin = bolusDTO.getDeliveredAmount();
  641. extendedBolus.pumpId = bolus.getPumpId();
  642. extendedBolus.isValid = true;
  643. extendedBolus.durationInMinutes = bolusDTO.getDuration();
  644.  
  645. bolus.setLinkedObject(extendedBolus);
  646.  
  647. TreatmentsPlugin.getPlugin().addToHistoryExtendedBolus(extendedBolus);
  648.  
  649. LOG.debug("addBolus - Extended [date={},pumpId={}, insulin={}, duration={}]", extendedBolus.date,
  650. extendedBolus.pumpId, extendedBolus.insulin, extendedBolus.durationInMinutes);
  651.  
  652. }
  653. break;
  654.  
  655. }
  656.  
  657. } else {
  658.  
  659. boolean old = false;
  660.  
  661. if (old) {
  662. treatment.insulin = bolusDTO.getDeliveredAmount();
  663. treatment.pumpId = bolus.getPumpId();
  664. treatment.source = Source.PUMP;
  665.  
  666. bolus.setLinkedObject(treatment);
  667.  
  668. TreatmentsPlugin.getPlugin().getService().createOrUpdate(treatment);
  669.  
  670. LOG.debug("editBolus - [date={},pumpId={}, insulin={}]", treatment.date, treatment.pumpId,
  671. treatment.insulin);
  672.  
  673. MainApp.bus().post(new EventTreatmentChange(treatment));
  674. } else {
  675.  
  676. DetailedBolusInfo detailedBolusInfo = DetailedBolusInfoStorage.findDetailedBolusInfo(treatment.date);
  677. if (detailedBolusInfo == null) {
  678. detailedBolusInfo = new DetailedBolusInfo();
  679. }
  680.  
  681. detailedBolusInfo.date = treatment.date;
  682. detailedBolusInfo.source = Source.PUMP;
  683. detailedBolusInfo.pumpId = bolus.getPumpId();
  684. detailedBolusInfo.insulin = bolusDTO.getDeliveredAmount();
  685.  
  686. boolean newRecord = TreatmentsPlugin.getPlugin().addToHistoryTreatment(detailedBolusInfo, false);
  687.  
  688. bolus.setLinkedObject(detailedBolusInfo);
  689.  
  690. if (L.isEnabled(L.PUMPCOMM))
  691. LOG.debug("editBolus - [date={},pumpId={}, insulin={}, newRecord={}]", detailedBolusInfo.date,
  692. detailedBolusInfo.pumpId, detailedBolusInfo.insulin, newRecord);
  693. }
  694. }
  695.  
  696. }
  697.  
  698.  
  699. private DetailedBolusInfo createTreatment(long date, double amount, long pumpId, Boolean isSmb, Treatment treatment) {
  700. DetailedBolusInfo normalBolus = new DetailedBolusInfo();
  701. normalBolus.date = date;
  702.  
  703. if (treatment != null) {
  704. normalBolus.carbs = treatment.carbs;
  705. normalBolus.date = treatment.date;
  706. }
  707.  
  708. normalBolus.source = Source.PUMP;
  709. normalBolus.insulin = amount;
  710. normalBolus.pumpId = pumpId;
  711. normalBolus.isValid = true;
  712. normalBolus.isSMB = isSmb == null ? false : isSmb;
  713.  
  714. return normalBolus;
  715. }
  716.  
  717.  
  718. // TODO needs to be implemented
  719. public void processTBRs(List<PumpHistoryEntry> treatments) {
  720.  
  721. int dateDifference = getOldestDateDifference(treatments);
  722.  
  723. // List<Treatment> treatmentsFromHistory = TreatmentsPlugin.getPlugin().getTreatmentsFromHistoryXMinutesAgo(
  724. // dateDifference);
  725.  
  726. for (PumpHistoryEntry treatment : treatments) {
  727.  
  728. LOG.debug("TOE. Treatment: " + treatment);
  729. long inLocalTime = tryToGetByLocalTime(treatment.atechDateTime);
  730.  
  731. }
  732.  
  733. }
  734.  
  735.  
  736. // TODO needs to be implemented
  737. public void processSuspends(List<PumpHistoryEntry> treatments) {
  738.  
  739. }
  740.  
  741.  
  742. // TODO needs to be implemented
  743. public List<PumpHistoryEntry> getSuspends() {
  744. return new ArrayList<PumpHistoryEntry>();
  745. }
  746.  
  747.  
  748. private List<PumpHistoryEntry> filterTDDs(List<PumpHistoryEntry> tdds) {
  749. List<PumpHistoryEntry> tddsOut = new ArrayList<>();
  750.  
  751. for (PumpHistoryEntry tdd : tdds) {
  752. if (tdd.getEntryType() != PumpHistoryEntryType.EndResultTotals) {
  753. tddsOut.add(tdd);
  754. }
  755. }
  756.  
  757. return tddsOut.size() == 0 ? tdds : tddsOut;
  758. }
  759.  
  760.  
  761. private TDD findTDD(long atechDateTime, List<TDD> tddsDb) {
  762.  
  763. for (TDD tdd : tddsDb) {
  764.  
  765. if (DateTimeUtil.isSameDayATDAndMillis(atechDateTime, tdd.date)) {
  766. return tdd;
  767. }
  768. }
  769.  
  770. return null;
  771. }
  772.  
  773.  
  774. private long tryToGetByLocalTime(long atechDateTime) {
  775.  
  776. LocalDateTime ldt = DateTimeUtil.toLocalDateTime(atechDateTime);
  777.  
  778. // LOG.debug("TOE. Time of Entry: " + atechDateTime);
  779. // LOG.debug("TOE. Clock Pump: " + pumpTime.pumpTime.toString("HH:mm:ss"));
  780. // LOG.debug("TOE. LocalTime: " + pumpTime.localDeviceTime.toString("HH:mm:ss"));
  781. // LOG.debug("TOE. Difference(s): " + pumpTime.timeDifference);
  782.  
  783. ldt = ldt.plusSeconds(pumpTime.timeDifference);
  784. ldt = ldt.millisOfSecond().setCopy(000);
  785.  
  786. // LOG.debug("TOE. New Time Of Entry: " + ldt.toString("HH:mm:ss"));
  787.  
  788. LOG.debug("tryToGetByLocalTime: [TimeOfEntry={}, ClockPump={}, LocalTime={}, DifferenceSec={}, " +
  789. "NewTimeOfEntry={}, time={}",
  790. atechDateTime,
  791. pumpTime.pumpTime.toString("HH:mm:ss"),
  792. pumpTime.localDeviceTime.toString("HH:mm:ss"),
  793. pumpTime.timeDifference,
  794. ldt.toString("HH:mm:ss"),
  795. ldt.toDate().getTime());
  796.  
  797. return ldt.toDate().getTime();
  798. }
  799.  
  800.  
  801. private int getOldestDateDifference(List<PumpHistoryEntry> treatments) {
  802.  
  803. long dt = Long.MAX_VALUE;
  804.  
  805. for (PumpHistoryEntry treatment : treatments) {
  806.  
  807. if (treatment.atechDateTime < dt) {
  808. dt = treatment.atechDateTime;
  809. }
  810. }
  811.  
  812. //LOG.debug("Oldest entry: {}, pumpTimeDifference={}", dt, this.pumpTime.timeDifference);
  813.  
  814. LocalDateTime oldestEntryTime = DateTimeUtil.toLocalDateTime(dt);
  815. oldestEntryTime = oldestEntryTime.minusMinutes(5);
  816.  
  817. if (this.pumpTime.timeDifference < 0) {
  818. oldestEntryTime = oldestEntryTime.plusSeconds(this.pumpTime.timeDifference);
  819. }
  820. // } else {
  821. // d.minusSeconds(this.pumpTime.timeDifference);
  822. // }
  823.  
  824. LocalDateTime now = new LocalDateTime();
  825.  
  826. Minutes minutes = Minutes.minutesBetween(oldestEntryTime, now);
  827.  
  828. // returns oldest time in history, with calculated time difference between pump and phone, minus 5 minutes
  829. LOG.debug("Oldest entry: {}, pumpTimeDifference={}, newDt={}, currentTime={}, differenceMin={}",
  830. dt,
  831. this.pumpTime.timeDifference,
  832. oldestEntryTime,
  833. now,
  834. minutes.getMinutes());
  835.  
  836. return minutes.getMinutes();
  837.  
  838. }
  839.  
  840.  
  841. // private void processTreatments(List<PumpHistoryEntry> treatments) {
  842. //
  843. // // FIXME bolus and tbr
  844. //
  845. // LOG.error(getLogPrefix() + "Treatments found: {}. Not processed.\n", treatments.size());
  846. //
  847. // //MainApp.getDbHelper().getTDDsForLastXDays()
  848. //
  849. // MedtronicHistoryData.showLogs(null, gsonInstancePretty.toJson(treatments));
  850. //
  851. // }
  852.  
  853. private PumpHistoryEntryType getTDDType() {
  854.  
  855. if (MedtronicUtil.getMedtronicPumpModel() == null) {
  856. return PumpHistoryEntryType.EndResultTotals;
  857. }
  858.  
  859. switch (MedtronicUtil.getMedtronicPumpModel()) {
  860.  
  861. case Medtronic_515:
  862. case Medtronic_715:
  863. return PumpHistoryEntryType.DailyTotals515;
  864.  
  865. case Medtronic_522:
  866. case Medtronic_722:
  867. return PumpHistoryEntryType.DailyTotals522;
  868.  
  869. case Medtronic_523_Revel:
  870. case Medtronic_723_Revel:
  871. case Medtronic_554_Veo:
  872. case Medtronic_754_Veo:
  873. return PumpHistoryEntryType.DailyTotals523;
  874.  
  875. default: {
  876. return PumpHistoryEntryType.EndResultTotals;
  877. }
  878. }
  879.  
  880. }
  881.  
  882.  
  883. /*
  884. * entryType == PumpHistoryEntryType.Bolus || // Treatments
  885. * entryType == PumpHistoryEntryType.TempBasalRate || //
  886. * entryType == PumpHistoryEntryType.TempBasalDuration || //
  887. *
  888. * entryType == PumpHistoryEntryType.Prime || // Pump Status Change
  889. * entryType == PumpHistoryEntryType.PumpSuspend || //
  890. * entryType == PumpHistoryEntryType.PumpResume || //
  891. * entryType == PumpHistoryEntryType.Rewind || //
  892. * entryType == PumpHistoryEntryType.NoDeliveryAlarm || // no delivery
  893. * entryType == PumpHistoryEntryType.BasalProfileStart || //
  894. *
  895. * entryType == PumpHistoryEntryType.ChangeTime || // Time Change
  896. * entryType == PumpHistoryEntryType.NewTimeSet || //
  897. *
  898. * entryType == PumpHistoryEntryType.SelectBasalProfile || // Configuration
  899. * entryType == PumpHistoryEntryType.ClearSettings || //
  900. * entryType == PumpHistoryEntryType.SaveSettings || //
  901. * entryType == PumpHistoryEntryType.ChangeMaxBolus || //
  902. * entryType == PumpHistoryEntryType.ChangeMaxBasal || //
  903. * entryType == PumpHistoryEntryType.ChangeTempBasalType || //
  904. *
  905. * entryType == PumpHistoryEntryType.ChangeBasalProfile_NewProfile || // Basal profile
  906. *
  907. * entryType == PumpHistoryEntryType.DailyTotals512 || // Daily Totals
  908. * entryType == PumpHistoryEntryType.DailyTotals522 || //
  909. * entryType == PumpHistoryEntryType.DailyTotals523 || //
  910. * entryType == PumpHistoryEntryType.EndResultTotals
  911. */
  912.  
  913. public boolean hasBasalProfileChanged() {
  914.  
  915. List<PumpHistoryEntry> filteredItems = getFilteredItems(PumpHistoryEntryType.ChangeBasalProfile_NewProfile);
  916.  
  917. LOG.debug("hasBasalProfileChanged. Items: " + filteredItems);
  918.  
  919. return (filteredItems.size() > 0);
  920.  
  921. }
  922.  
  923.  
  924. public void processLastBasalProfileChange(MedtronicPumpStatus mdtPumpStatus) {
  925.  
  926. // FIXME
  927.  
  928. List<PumpHistoryEntry> filteredItems = getFilteredItems(PumpHistoryEntryType.ChangeBasalProfile_NewProfile);
  929.  
  930. LOG.debug("processLastBasalProfileChange. Items: " + filteredItems);
  931.  
  932. PumpHistoryEntry newProfile = null;
  933. Long lastDate = null;
  934.  
  935. if (filteredItems.size() == 1) {
  936. newProfile = filteredItems.get(0);
  937. } else if (filteredItems.size() > 1) {
  938.  
  939. for (PumpHistoryEntry filteredItem : filteredItems) {
  940.  
  941. if (lastDate == null || lastDate < filteredItem.atechDateTime) {
  942. newProfile = filteredItem;
  943. lastDate = newProfile.atechDateTime;
  944. }
  945. }
  946. }
  947.  
  948. if (newProfile != null) {
  949. LOG.debug("processLastBasalProfileChange. item found, setting new basalProfileLocally: " + newProfile);
  950. BasalProfile basalProfile = (BasalProfile) newProfile.getDecodedData().get("Object");
  951. mdtPumpStatus.basalsByHour = basalProfile.getProfilesByHour();
  952. }
  953.  
  954. // boolean profileChanged = ((filteredItems.size() - basalProfileChangedInternally) > 0);
  955.  
  956. // LOG.error("Profile changed:" + profileChanged);
  957.  
  958. // this.basalProfileChangedInternally = 0;
  959.  
  960. // return profileChanged;
  961.  
  962. }
  963.  
  964.  
  965. public boolean hasPumpTimeChanged() {
  966.  
  967. return getStateFromFilteredList(PumpHistoryEntryType.NewTimeSet, //
  968. PumpHistoryEntryType.ChangeTime);
  969.  
  970. }
  971.  
  972.  
  973. public void setLastHistoryRecordTime(Long lastHistoryRecordTime) {
  974.  
  975. // this.previousLastHistoryRecordTime = this.lastHistoryRecordTime;
  976. this.lastHistoryRecordTime = lastHistoryRecordTime;
  977. }
  978.  
  979.  
  980. public void setIsInInit(boolean init) {
  981. this.isInit = init;
  982. }
  983.  
  984.  
  985. // HELPER METHODS
  986.  
  987. private void sort(List<PumpHistoryEntry> list) {
  988. Collections.sort(list, new PumpHistoryEntry.Comparator());
  989. }
  990.  
  991.  
  992. private List<PumpHistoryEntry> preProcessTBRs(List<PumpHistoryEntry> TBRs_Input) {
  993. List<PumpHistoryEntry> TBRs = new ArrayList<>();
  994.  
  995. Map<String, PumpHistoryEntry> map = new HashMap<>();
  996.  
  997. for (PumpHistoryEntry pumpHistoryEntry : TBRs_Input) {
  998. if (map.containsKey(pumpHistoryEntry.DT)) {
  999. MedtronicPumpHistoryDecoder.decodeTempBasal(map.get(pumpHistoryEntry.DT), pumpHistoryEntry);
  1000. pumpHistoryEntry.setEntryType(PumpHistoryEntryType.TempBasalCombined);
  1001. TBRs.add(pumpHistoryEntry);
  1002. map.remove(pumpHistoryEntry.DT);
  1003. } else {
  1004. map.put(pumpHistoryEntry.DT, pumpHistoryEntry);
  1005. }
  1006. }
  1007.  
  1008. return TBRs;
  1009. }
  1010.  
  1011.  
  1012. private List<PumpHistoryEntry> getFilteredItems(PumpHistoryEntryType... entryTypes) {
  1013.  
  1014. return getFilteredItems(this.newHistory, entryTypes);
  1015.  
  1016. }
  1017.  
  1018.  
  1019. // private List<PumpHistoryEntry> getFilteredListByPreviousLastRecord(PumpHistoryEntryType... entryTypes) {
  1020. // return getFilteredListByTime(this.previousLastHistoryRecordTime, entryTypes);
  1021. // }
  1022.  
  1023. private List<PumpHistoryEntry> getFilteredListByLastRecord(PumpHistoryEntryType... entryTypes) {
  1024. return getFilteredListByTime(this.lastHistoryRecordTime, entryTypes);
  1025. }
  1026.  
  1027.  
  1028. private List<PumpHistoryEntry> getFilteredListByTime(Long lastRecordTime, PumpHistoryEntryType... entryTypes) {
  1029. if (lastRecordTime == null) {
  1030. return getFilteredItems(entryTypes);
  1031. } else {
  1032. return getFilteredItems(lastRecordTime, entryTypes);
  1033. }
  1034. }
  1035.  
  1036.  
  1037. private boolean getStateFromFilteredList(PumpHistoryEntryType... entryTypes) {
  1038. if (isInit) {
  1039. return false;
  1040. } else {
  1041. List<PumpHistoryEntry> filteredItems = getFilteredItems(entryTypes);
  1042.  
  1043. LOG.debug("Items: " + filteredItems);
  1044.  
  1045. return filteredItems.size() > 0;
  1046. }
  1047. }
  1048.  
  1049.  
  1050. private List<PumpHistoryEntry> getFilteredItems(Long dateTime, PumpHistoryEntryType... entryTypes) {
  1051.  
  1052. PumpHistoryResult phr = new PumpHistoryResult(null, dateTime);
  1053. return getFilteredItems(phr.getValidEntries(), entryTypes);
  1054.  
  1055. }
  1056.  
  1057.  
  1058. private List<PumpHistoryEntry> getFilteredItems(List<PumpHistoryEntry> inList, PumpHistoryEntryType... entryTypes) {
  1059.  
  1060. // LOG.debug("InList: " + inList.size());
  1061. List<PumpHistoryEntry> outList = new ArrayList<>();
  1062.  
  1063. if (inList != null && inList.size() > 0) {
  1064. for (PumpHistoryEntry pumpHistoryEntry : inList) {
  1065.  
  1066. if (!isEmpty(entryTypes)) {
  1067. for (PumpHistoryEntryType pumpHistoryEntryType : entryTypes) {
  1068.  
  1069. if (pumpHistoryEntry.getEntryType() == pumpHistoryEntryType) {
  1070. outList.add(pumpHistoryEntry);
  1071. break;
  1072. }
  1073. }
  1074. } else {
  1075. outList.add(pumpHistoryEntry);
  1076. }
  1077. }
  1078. }
  1079.  
  1080. // LOG.debug("OutList: " + outList.size());
  1081.  
  1082. return outList;
  1083.  
  1084. }
  1085.  
  1086.  
  1087. private boolean isEmpty(PumpHistoryEntryType... entryTypes) {
  1088. return (entryTypes == null || (entryTypes.length == 1 && entryTypes[0] == null));
  1089. }
  1090.  
  1091.  
  1092. // public List<PumpHistoryEntry> getNewHistoryEntries() {
  1093. // return this.newHistory;
  1094. // }
  1095.  
  1096. // public void setBasalProfileChanged() {
  1097. // this.basalProfileChangedInternally++;
  1098. // }
  1099.  
  1100. private String getLogPrefix() {
  1101. return "MedtronicHistoryData::";
  1102. }
  1103.  
  1104. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement