示例#1
0
 public MiniMedContext(IDevice device) : base(device)
 {
     using (Data.Repository.CgmUnitOfWork uow = new CgmUnitOfWork())
     {
         _setting = uow.Setting.GetSettings();
     }
 }
示例#2
0
 private void SaveSetting()
 {
     using (CgmUnitOfWork uow = new CgmUnitOfWork())
     {
         uow.Setting.Update(_setting);
     }
 }
示例#3
0
        //public async Task Upload_old(CancellationToken cancelToken)
        //{
        //    //save to sqlite
        //    //using (Data.Repository.CgmUnitOfWork uow=new Repository.CgmUnitOfWork())
        //    //{
        //    //    uow.CommunicationMessage.SaveSession(Session);
        //    //}

        //    //testing events
        //    await SyncWithEvents(cancelToken);

        //    await CreateUploads(cancelToken);

        //    await UploadElements(cancelToken);
        //}

        //private async Task CreateUploads(CancellationToken cancelToken)
        //{
        //    if (LastStatusMessage != null)
        //    {

        //        if (LastStatusMessage.SgvDateTime.DateTime.HasValue)
        //        {
        //            //but during testing and harding of the event/history usage, I will do this also
        //            if (this.Entries.Count==0)
        //            {
        //                await CreateEntrySgv(this.LastStatusMessage.Sgv, this.LastStatusMessage.SgvDateTime.DateTimeString, (long)this.LastStatusMessage.SgvDateTime.DateTimeEpoch, this.LastStatusMessage.CgmTrendName.ToString(), true);
        //                //if (LastStatusMessage.BolusWizardRecent == 1)
        //                //{
        //                //    CreateEntryMbg();
        //                //}
        //                //getting it from history....
        //                //carbs is not in the statusmessage.
        //                CreateCorrectionBolus(this.LastStatusMessage.BolusEstimate, 0, this.LastStatusMessage.SgvDateTime.Rtc.ToString(), this.LastStatusMessage.LastBolusDateTime.ToString(Constants.Dateformat));
        //            }

        //            CreateDeviceStatus();
        //        }

        //        if (this.LastStatusMessage.Alert != 0 && _session.PumpTime.PumpDateTime.HasValue)
        //        {
        //            CreateAnnouncement($"{this.LastStatusMessage.AlertName.ToString()} - ({this.LastStatusMessage.AlertDateTime})", this.LastStatusMessage.AlertDateTime.DateTime.Value, "Alert");
        //        }
        //    }
        //    else
        //    {
        //        this.DeviceStatus = null;
        //    }

        //}
        private async Task RemoveAlreadyUploaded(CancellationToken cancelToken)
        {
            List <HistoryStatus> status = new List <HistoryStatus>();

            using (CgmUnitOfWork uow = new CgmUnitOfWork())
            {
                status = uow.HistoryStatus.ToList();
            }
            if (Entries.Count > 0)
            {
                var query =
                    from comp in this.Entries
                    join entry in status on comp.Key equals entry.Key
                    select comp;
                query.ToList().ForEach(e => this.Entries.Remove(e));
            }
            if (Treatments.Count > 0)
            {
                var query =
                    from comp in this.Treatments
                    join entry in status on comp.Key equals entry.Key
                    select comp;

                query.ToList().ForEach(e => this.Treatments.Remove(e));
            }
        }
 private async void DeleteDevice()
 {
     await _dialogService.ShowMessage($"Are you sure you want to delete device: {this.ToString()}?",
                                      "Confirmation",
                                      buttonConfirmText : "Ok", buttonCancelText : "Cancel",
                                      afterHideCallback : (confirmed) =>
     {
         if (confirmed)
         {
             using (CgmUnitOfWork uow = new CgmUnitOfWork())
             {
                 uow.Device.Remove(_device);
             }
             if (Removed != null)
             {
                 Removed(this, null);
             }
         }
         else
         {
             // User has pressed the "cancel" button
             // (or has discared the dialog box).
             // ...
         }
     });
 }
示例#5
0
        private void GetDevices()
        {
            this.Devices.Clear();
            List <Device> devices = new List <Device>();

            using (CgmUnitOfWork uow = new CgmUnitOfWork())
            {
                devices = uow.Device.GetAllDevices();
            }

            foreach (var item in devices)
            {
                var device = new DeviceItemViewModel(item, _dialogService);
                device.Removed += Device_Removed;
                this.Devices.Add(device);
            }
            if (this.Devices.Count > 0)
            {
                this.SelectedDevice = this.Devices[0];
            }
            else
            {
                this.SelectedDevice = null;
            }
        }
示例#6
0
 private void ClearHistory()
 {
     using (CgmUnitOfWork uow = new CgmUnitOfWork())
     {
         uow.History.ResetHistory();
     }
     _dialogService.ShowMessage("History has been cleared.", "Clear history");
 }
示例#7
0
 protected virtual void SetConfiguration()
 {
     using (CgmUnitOfWork uow = new CgmUnitOfWork())
     {
         _setting        = uow.Setting.GetSettings();
         Intervalseconds = _setting.IntervalSeconds;
     }
 }
示例#8
0
        private async Task StartCollectPumpSettingsAsync(CancellationToken cancelToken)
        {
            //test this....
            if (this.Session.LinkMac == null && this.Session.PumpMac == null)
            {
                Logger.LogInformation($"Getting linkmac/Pumpmac");
                await StartCommunication(Session.GetReadInfoRequest(),
                                         new ReadInfoResponsePattern(),
                                         cancelToken);

                Logger.LogInformation($"Got LinkMac: {BitConverter.ToString(this.Session.LinkMac)} AND PumpMac: {BitConverter.ToString(this.Session.PumpMac)}");


                if (this.Session.LinkMac == null && this.Session.PumpMac == null)
                {
                    throw new Exception("Error getting Linkmac/Pumpmac");
                }
                else
                {
                    //save macs
                    using (CgmUnitOfWork uow = new CgmUnitOfWork())
                    {
                        uow.Device.AddUpdateSessionToDevice(Session);
                    }
                }
            }



            if (this.Session.LinkKey == null)
            {
                Logger.LogInformation($"Getting linkkey");
                await StartCommunication(Session.GetLinkKeyRequest(),
                                         new LinkKeyResponsePattern(),
                                         cancelToken);


                if (this.Session.LinkKey == null)
                {
                    throw new Exception("Error getting linkkey");
                }
                else
                {
                    Logger.LogInformation($"Got LinkKey: {BitConverter.ToString(this.Session.LinkKey)}");
                    //save LinkKey
                    using (CgmUnitOfWork uow = new CgmUnitOfWork())
                    {
                        uow.Device.AddUpdateSessionToDevice(Session);
                    }
                }
            }


            if (this.Session.LinkMac == null || this.Session.PumpMac == null)
            {
                throw new Exception($"Could not get linkmac/pumpmac: {this.Session.LinkMac}/{this.Session.PumpMac}");
            }
        }
示例#9
0
        public async Task Upload(CancellationToken cancelToken)
        {
            List <int> eventFilter = new List <int>();

            eventFilter.Add((int)EventTypeEnum.SENSOR_GLUCOSE_READINGS_EXTENDED);
            eventFilter.Add((int)EventTypeEnum.BOLUS_WIZARD_ESTIMATE);
            eventFilter.Add((int)EventTypeEnum.ALARM_NOTIFICATION);
            eventFilter.Add((int)EventTypeEnum.GLUCOSE_SENSOR_CHANGE);
            eventFilter.Add((int)EventTypeEnum.CANNULA_FILL_DELIVERED);
            eventFilter.Add((int)EventTypeEnum.BG_READING);
            eventFilter.Add((int)EventTypeEnum.AIRPLANE_MODE);

            List <PumpEvent> eventsToHandle = new List <PumpEvent>();

            using (CgmUnitOfWork uow = new CgmUnitOfWork())
            {
                var NewEvents = uow.History.GetHistoryWithNoStatus(eventFilter, HistoryStatusTypeEnum.NightScout);


                if (NewEvents.Count > 0)
                {
                    Serializer serializer = new Serializer(Session);

                    foreach (var item in NewEvents)
                    {
                        var pumpevent = serializer.Deserialize <PumpEvent>(item.HistoryBytes.GetBytes());
                        pumpevent.HistoryDataType = item.HistoryDataType;
                        eventsToHandle.Add(pumpevent);
                    }
                }
            }

            CreateDeviceStatus();

            if (eventsToHandle.Count > 0)
            {
                //Logger.LogInformation($"Found {eventsToHandle.Count} new pump-events.");

                MissingReadings(eventsToHandle);
                MissingWizard(eventsToHandle);
                MissingAlerts(eventsToHandle);
                SensorChange(eventsToHandle);
                CannulaChanged(eventsToHandle);
                BgReadings(eventsToHandle);
                OtherReadings(eventsToHandle);
                // await RemoveAlreadyUploaded(cancelToken);
                await UploadElements(cancelToken);
            }
            else
            {
                Logger.LogInformation($"No new pump-events.");
            }
        }
示例#10
0
        public void Start(IDevice device)
        {
            _device      = device;
            Delay        = TimeSpan.FromSeconds(_delayInSeconds);
            _tokenSource = new CancellationTokenSource();
            _token       = _tokenSource.Token;
            using (Data.Repository.CgmUnitOfWork uow = new CgmUnitOfWork())
            {
                _setting        = uow.Setting.GetSettings();
                Intervalseconds = _setting.OtherSettings.IntervalSeconds;
            }

            SetUpTimer(DateTime.Now.AddSeconds(2));
        }
示例#11
0
        public SettingsViewModel(IDialogService dialogService)
        {
            _dialogService         = dialogService;
            SwitchThemeCommand     = new RelayCommand(async() => { await ThemeSelectorService.SwitchThemeAsync(); });
            this.GetDevicesCommand = new RelayCommand(() => this.GetDevices());

            this.ClearHistoryCommand = new RelayCommand(() => this.ClearHistory());
            using (CgmUnitOfWork uow = new CgmUnitOfWork())
            {
                _setting = uow.Setting.GetSettings();
            }
            GetDevices();
            this.LocalPath = Windows.Storage.ApplicationData.Current.LocalFolder.Path;
        }
示例#12
0
        /// <summary>
        /// Invoked when the application is launched normally by the end user.  Other entry points
        /// will be used such as when the application is launched to open a specific file.
        /// </summary>
        /// <param name="e">Details about the launch request and process.</param>
        protected override async void OnLaunched(LaunchActivatedEventArgs e)
        {
            if (!e.PrelaunchActivated)
            {
                await ActivationService.ActivateAsync(e);
            }
            string DataPath = Windows.Storage.ApplicationData.Current.LocalFolder.Path;

            ApplicationLogging.LoggerFactory.AddCgmLog(DataPath);

            ApplicationLogging.LoggerFactory.AddEventAggregatorLog();

            using (CgmUnitOfWork uow = new CgmUnitOfWork())
            {
                uow.CheckDatabaseVersion(DataPath);
                uow.Setting.CheckSettings();
            }
            //check for nightscout settings
        }
        protected async override void AddTreatments(CancellationToken cancelToken)
        {
            if (this.Treatments.Count > 0)
            {
                try
                {
                    await _client.AddTreatmentsAsync(this.Treatments, cancelToken);

                    Logger.LogInformation($"Treatments uploaded to Nightscout. ({Treatments.Count})");
                    using (CgmUnitOfWork uow = new CgmUnitOfWork())
                    {
                        uow.HistoryStatus.AddKeys(Treatments.Select(e => e.Key).ToList(), 0);
                    }
                }
                catch (Exception)
                {
                    throw;
                }
            }
        }
示例#14
0
 public async void StatusChanged(BayerUsbDevice device)
 {
     await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                                                                   () =>
     {
         this.IsConnected = device.IsConnected;
         Configuration settings;
         using (CgmUnitOfWork uow = new CgmUnitOfWork())
         {
             settings = uow.Setting.GetSettings();
             if (this.IsConnected && settings.AutoStartTask)
             {
                 this.On = true;
             }
             else
             {
                 this.On = false;
             }
         }
     });
 }
        protected async override void AddEntries(CancellationToken cancelToken)
        {
            if (Entries.Count > 0)
            {
                try
                {
                    await _client.AddEntriesAsync(Entries, cancelToken);

                    Logger.LogInformation($"Entries uploaded to Nightscout. ({Entries.Count})");
                    //log uploads
                    using (CgmUnitOfWork uow = new CgmUnitOfWork())
                    {
                        uow.HistoryStatus.AddKeys(Entries.Select(e => e.Key).ToList(), 0);
                    }
                }
                catch (Exception)
                {
                    throw;
                }
            }
        }
示例#16
0
        private async Task GetSession()
        {
            //with this, the log is coming in the output window when we debug.
            Log.ApplicationLogging.LoggerFactory.AddOutputLogger();

            //find the device
            var device = BayerUsbDevice.FindMeter();

            //getting a cancellation token for the tasks
            var _tokenSource = new CancellationTokenSource();
            var _token       = _tokenSource.Token;

            //unit of work to get information
            using (CgmUnitOfWork uow = new CgmUnitOfWork())
            {
                //Check sqlite database version, should be done at the begin of every run to make sure database is aval and correct version.
                uow.CheckDatabaseVersion(AppContext.BaseDirectory);

                //Getting info from pump. The session class contain all info necessary for communicating with the pump and all the results.
                Common.Serialize.SerializerSession session = await uow.Pump.GetPumpSessionAsync(device, _token);
            }
        }
        protected override List <PumpEvent> GetHistoryWithNoStatus(List <int> eventFilter)
        {
            List <PumpEvent> eventsToHandle = new List <PumpEvent>();

            using (CgmUnitOfWork uow = new CgmUnitOfWork())
            {
                var NewEvents = uow.History.GetHistoryWithNoStatus(eventFilter);


                if (NewEvents.Count > 0)
                {
                    Serializer serializer = new Serializer(Session);

                    foreach (var item in NewEvents)
                    {
                        var pumpevent = serializer.Deserialize <PumpEvent>(item.HistoryBytes.GetBytes());
                        pumpevent.HistoryDataType = item.HistoryDataType;
                        eventsToHandle.Add(pumpevent);
                    }
                }
            }
            return(eventsToHandle);
        }
示例#18
0
        //public async void StatusChanged(BayerUsbDevice device)
        //{

        //    await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
        //            () =>
        //            {
        //                this.Device = device;

        //            });
        //}

        private async Task GetSession()
        {
            SerializerSession session = null;

            try
            {
                var _tokenSource = new CancellationTokenSource();
                var _token       = _tokenSource.Token;
                using (CgmUnitOfWork uow = new CgmUnitOfWork())
                {
                    session = await uow.Pump.GetPumpSessionAsync(this.Device, _token);

                    if (session != null)
                    {
                        UpdateSession(session);
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
示例#19
0
        private async Task StartCollectDeviceInfoAsync(CancellationToken cancelToken)
        {
            //if in bad state.....
            //await CloseAsync(cancelToken);


            Logger.LogInformation("Getting CNL deviceInformation");
            CommunicationBlock block = new CommunicationBlock();

            block.TimeoutSeconds = _setting.OtherSettings.TimeoutSeconds;
            block.Request        = new AstmStart("X");
            //block.Request = new AstmStart("W");
            //expected responses for the request
            block.ExpectedResponses.Add(new ReportPattern(new byte[] { 0x00, 0x41, 0x42, 0x43 }, 0));
            block.ExpectedResponses.Add(new EnqOREotkPattern());
            //Start Communication
            await this.StartCommunication(block, cancelToken);

            if (!cancelToken.IsCancellationRequested)
            {
                if (string.IsNullOrEmpty(this.Session.Device.SerialNumber))
                {
                    //if in bad state.....
                    //await CloseAsync(cancelToken);
                    this.Session.NeedResetCommunication = true;
                    throw new Exception("Could not communicate with CNL. Please unplug CNL and plug it in again to reset CNL-communication. ");
                }
                else
                {
                    //Get previous saved parameters Or set this session if device do not exsist
                    using (CgmUnitOfWork uow = new CgmUnitOfWork())
                    {
                        uow.Device.GetOrSetSessionAndSettings(Session);
                    }
                }
            }
        }
示例#20
0
        private async Task StartChannelNegoationAsync(CancellationToken cancelToken)
        {
            //IEEE 802.15.4 Channel ID
            //0x0e - Channel 14 - 2420MHz
            //0x11 - Channel 17 - 2435MHz
            //0x14 - Channel 20 - 2450MHz
            //0x17 - Channel 23 - 2465MHz
            //0x1a - Channel 26 - 2480MHz
            List <byte> channels = new List <byte>()
            {
                0x1a, 0x17, 0x14, 0x0e, 0x11
            };
            //short list of channels.
            //channel 23: observed loosing connection between sensor and¨pump when on channel 23. NOT GOOD.
            //channel 26: never seen a connection on this channel. remove to save loop-time.
            //the above channels removed from list to save loop-time and increase stability.

            //if (this.Session.RadioChannel==0x17)
            //{
            //    this.Session.RadioChannel = 0x00;
            //}
            //List<byte> channels = new List<byte>() { 0x1a,  0x14, 0x0e, 0x11 };

            //and then NOT.... because of no connections....
            byte lastChannel = this.Session.RadioChannel;


            if (this.Session.RadioChannelConfirmed && this.Session.RadioChannel == 0x00)
            {
                this.Session.RadioChannelConfirmed = false;
            }


            if (this.Session.RadioChannel != 0x00)
            {
                byte trie = this.Session.RadioChannel;
                this.Session.RadioChannel = 0x00;
                Logger.LogInformation($"Looking for pump. Channel: {trie} (Last used)");
                await StartCommunicationStandardResponse(Session.GetChannelRequest(trie), cancelToken);

                if (this.Session.RadioChannel == 0x00)
                {
                    Logger.LogInformation($"No connection on Channel {trie}");
                }
            }


            if (this.Session.RadioChannel == 0x00)
            {
                if (lastChannel != 0x00)
                {
                    channels.Remove(lastChannel);
                }

                foreach (var item in channels)
                {
                    cancelToken.ThrowIfCancellationRequested();
                    Logger.LogInformation($"Looking for pump. Channel: {item}");
                    await StartCommunicationStandardResponse(Session.GetChannelRequest(item), cancelToken);

                    if (this.Session.RadioChannel != 0x00)
                    {
                        break;
                    }
                    else
                    {
                        Logger.LogInformation($"No connection on Channel {item}");
                    }
                }
            }

            if (this.Session.RadioRSSI == 0 && this.Session.RadioChannel != 0x00)
            {
                Logger.LogInformation($"Signal on Radiochannel {this.Session.RadioChannel.ToString()} is too weak ({this.Session.RadioRSSI}%)");
                this.Session.RadioChannel = 0x00;
            }

            if (this.Session.RadioChannel == 0x00)
            {
                this.Session.RadioChannelConfirmed = false;
                throw new Exception("Could not find RadioChannel/Pump.");
            }
            else
            {
                this.Session.RadioChannelConfirmed = true;
                Logger.LogInformation($"Connected on radiochannel {this.Session.RadioChannel.ToString()}. ({this.Session.RadioRSSI}%)");
                //save LinkKey
                using (CgmUnitOfWork uow = new CgmUnitOfWork())
                {
                    uow.Device.AddUpdateSessionToDevice(Session);
                }
            }


            Logger.LogTrace(this.Session.GetParametersAsString());
        }
示例#21
0
        private async Task GetData()
        {
            if (!CheckNet())
            {
                Stop();
                return;
            }
            SerializerSession session = null;

            try
            {
                using (CgmUnitOfWork uow = new CgmUnitOfWork())
                {
                    if (_setting.OtherSettings.UploadToNightscout)
                    {
                        session = await uow.Pump.GetPumpDataAndUploadAsync(_device, GetBattery(), _token);
                    }
                    else
                    {
                        session = await uow.Pump.GetPumpSessionAsync(_device, _token);
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                if (!_token.IsCancellationRequested)
                {
                    if (session != null)
                    {
                        if (session.OptimalNextRead.HasValue)
                        {
                            session.NextRun = session.OptimalNextRead.Value;
                            Logger.LogInformation($"Next session: {session.OptimalNextRead.Value} (PumpTime: {session.OptimalNextReadInPumpTime.Value})");
                        }
                        else
                        {
                            var time = DateTime.Now.AddMinutes(5);
                            session.NextRun = time;
                            Logger.LogInformation($"Next session: {time} (From local datetime. No sgv-time)");
                        }
                        if (session != null)
                        {
                            GotSession(session);
                        }
                        if (this.timer != null)
                        {
                            timer.Dispose();
                        }
                        SetUpTimer(session.NextRun.Value);
                        if (session.NeedResetCommunication)
                        {
                            ResetCommunication(session);
                        }
                        session.NewSession();
                    }
                }
            }
        }
示例#22
0
        private async Task UploadElements(CancellationToken cancelToken)
        {
            if (Entries.Count > 0)
            {
                try
                {
                    await _client.AddEntriesAsync(Entries, cancelToken);

                    Logger.LogInformation($"Entries uploaded to Nightscout. ({Entries.Count})");
                    //log uploads
                    using (CgmUnitOfWork uow = new CgmUnitOfWork())
                    {
                        uow.HistoryStatus.AddKeys(Entries.Select(e => e.Key).ToList(), HistoryStatusTypeEnum.NightScout, 0);
                    }
                }
                catch (Exception)
                {
                    throw;
                }
            }



            if (this.Treatments.Count > 0)
            {
                try
                {
                    await _client.AddTreatmentsAsync(this.Treatments, cancelToken);

                    Logger.LogInformation($"Treatments uploaded to Nightscout. ({Treatments.Count})");
                    using (CgmUnitOfWork uow = new CgmUnitOfWork())
                    {
                        uow.HistoryStatus.AddKeys(Treatments.Select(e => e.Key).ToList(), HistoryStatusTypeEnum.NightScout, 0);
                    }
                }
                catch (Exception)
                {
                    throw;
                }



                if (!string.IsNullOrEmpty(Session.Settings.NotificationUrl) && Session.Settings.OtherSettings.SendEventsToNotificationUrl)
                {
                    var notif = this.Treatments.Where(e => !string.IsNullOrEmpty(e.Notification.Type)).Select(e => e.Notification);
                    if (notif.Count() > 0)
                    {
                        NotificationClient client = new NotificationClient(Session.Settings.NotificationUrl);
                        foreach (var item in notif)
                        {
                            await client.AddNotificationAsync(item, cancelToken);
                        }
                        Logger.LogInformation($"Notifications sent. ({notif.Count()})");
                    }
                }
            }


            if (this.DeviceStatus != null && !string.IsNullOrEmpty(this.DeviceStatus.Device))
            {
                await _client.AddDeviceStatusAsync(new List <Nightscout.DeviceStatus>() { this.DeviceStatus }, cancelToken);

                Logger.LogInformation("DeviceStatus uploaded to Nightscout.");
            }

            //only upload new treatments

            //List<Treatment> treatments = new List<Treatment>();


            //get trible ..... maybe this could be done better
            //    var getCount = this.Treatments.Count * 3;
            //var all = await _client.TreatmentsAsync(null, getCount);
            //remove treatments that are uploaded.

            //var query =
            //  from comp in this.Treatments
            //  join entry in all on comp.EnteredBy equals entry.EnteredBy
            //  select comp;
            //query.ToList().ForEach(e => this.Treatments.Remove(e));

            //if (this.Treatments.Count > 0)
            //{
            //    await _client.AddTreatmentsAsync(this.Treatments, cancelToken);
            //    Logger.LogInformation($"Treatments uploaded to Nightscout. ({Treatments.Count})");

            //    if (!string.IsNullOrEmpty(Session.Settings.NotificationUrl) && Session.Settings.OtherSettings.SendEventsToNotificationUrl)
            //    {
            //        var notif = this.Treatments.Where(e => !string.IsNullOrEmpty(e.Notification.Type)).Select(e => e.Notification);
            //        if (notif.Count() > 0)
            //        {
            //            NotificationClient client = new NotificationClient(Session.Settings.NotificationUrl);
            //            foreach (var item in notif)
            //            {
            //                await client.AddNotificationAsync(item, cancelToken);
            //            }
            //            Logger.LogInformation($"Notifications sent. ({notif.Count()})");
            //        }

            //    }


            //}
        }