public GlucoseFetchResult GetLatestReading() { var fetchResult = new GlucoseFetchResult(); try { if (_config.FetchMethod == FetchMethod.DexcomShare) { GetFetchResultFromDexcom(fetchResult); } else if (_config.FetchMethod == FetchMethod.NightscoutApi) { GetFetchResultFromNightscout(fetchResult); } else { _logger.LogError("Invalid fetch method specified."); throw new InvalidOperationException("Fetch Method either not specified or invalid specification."); } } catch (Exception ex) { _logger.LogError("Failed to get data. {0}", ex); fetchResult = GetDefaultFetchResult(); } return(fetchResult); }
private GlucoseFetchResult GetFetchResultFromNightscout(GlucoseFetchResult fetchResult) { var request = new HttpRequestMessage { RequestUri = new Uri($"{_config.NightscoutUrl}/api/v1/entries/sgv?count=1" + (!string.IsNullOrWhiteSpace(_config.NightscoutAccessToken) ? $"&token={_config.NightscoutAccessToken}" : "")), Method = HttpMethod.Get, }; try { var response = new HttpClient().SendAsync(request).Result; var content = response.Content.ReadAsStringAsync().Result.Split('\t'); Regex rgx = new Regex("[^a-zA-Z]"); var time = content[0].ParseNightscoutDate(); var trendString = rgx.Replace(content[3], ""); var val = int.Parse(content[2]); fetchResult.Value = val; fetchResult.Time = time; fetchResult.TrendIcon = trendString.GetTrendArrowFromNightscout(); } catch (Exception ex) { _logger.LogError("Nightscout fetching failed or received incorrect format. {0}", ex); fetchResult = GetDefaultFetchResult(); } return(fetchResult); }
public async Task <GlucoseFetchResult> GetLatestReading() { var fetchResult = new GlucoseFetchResult(); try { if (_config.FetchMethod == FetchMethod.DexcomShare) { await GetFetchResultFromDexcom(fetchResult).ConfigureAwait(false); } else if (_config.FetchMethod == FetchMethod.NightscoutApi) { await GetFetchResultFromNightscout(fetchResult).ConfigureAwait(false); } else { _logger.LogError("Invalid fetch method specified."); throw new InvalidOperationException("Fetch Method either not specified or invalid specification."); } } catch (Exception ex) { _logger.LogError("Failed to get data. {0}", ex); fetchResult = GetDefaultFetchResult(); } fetchResult.UnitDisplayType = _config.UnitDisplayType; if (fetchResult.UnitDisplayType == GlucoseUnitType.MMOL && !fetchResult.Value.ToString().Contains(".")) // If decimal value, then it is already MMOL { fetchResult.Value /= 18; } return(fetchResult); }
private void ConvertMGtoMMOL(GlucoseFetchResult fetchResult) { if (!fetchResult.Value.ToString().Contains(".")) // If decimal value, then it is already MMOL { fetchResult.Value /= 18; } }
private void CreateIcon() { IsCriticalLow = false; var service = new GlucoseFetchService(new GlucoseFetchConfiguration { DexcomUsername = Constants.DexcomUsername, DexcomPassword = Constants.DexcomPassword, FetchMethod = Constants.FetchMethod, NightscoutUrl = Constants.NightscoutUrl, NightscoutAccessToken = Constants.AccessToken, UnitDisplayType = Constants.GlucoseUnitType }, _logger); FetchResult = service.GetLatestReading(); var value = FetchResult.Value.ToString(); if (value.Contains(".")) { value = FetchResult.Value.ToString("0.0"); } trayIcon.Text = $"{value} {FetchResult.Time.ToLongTimeString()} {FetchResult.TrendIcon}"; if (FetchResult.Value <= Constants.CriticalLowBg) { IsCriticalLow = true; } _iconService.CreateTextIcon(FetchResult.Value, IsCriticalLow, trayIcon); }
public static string GetFormattedStringValue(this GlucoseFetchResult fetchResult) { var value = fetchResult.Value.ToString(); if (value.Contains(".")) { value = fetchResult.Value.ToString("0.0"); } return(value); }
private GlucoseFetchResult GetFetchResultFromDexcom(GlucoseFetchResult fetchResult) { // Get Session Id var request = new HttpRequestMessage { RequestUri = new Uri("https://share1.dexcom.com/ShareWebServices/Services/General/LoginPublisherAccountByName"), Method = HttpMethod.Post, Content = new StringContent("{\"accountName\":\"" + _config.DexcomUsername + "\"," + "\"applicationId\":\"d8665ade-9673-4e27-9ff6-92db4ce13d13\"," + "\"password\":\"" + _config.DexcomPassword + "\"}", Encoding.UTF8, "application/json") }; try { var client = new HttpClient(); var response = client.SendAsync(request).Result; var sessionId = response.Content.ReadAsStringAsync().Result.Replace("\"", ""); request = new HttpRequestMessage { RequestUri = new Uri($"https://share1.dexcom.com/ShareWebServices/Services/Publisher/ReadPublisherLatestGlucoseValues?sessionId={sessionId}&minutes=1440&maxCount=1"), Method = HttpMethod.Post }; var result = client.SendAsync(request).Result.Content.ReadAsStringAsync().Result.RemoveUnnecessaryCharacters().Split(','); // Get raw data seperated var unixTime = result[1].Split('e')[1]; var trend = result[2].Split(':')[1]; var stringVal = result[3].Split(':')[1]; // Convert raw to correct data DateTime localTime = DateTime.MinValue; if (!string.IsNullOrWhiteSpace(unixTime)) { localTime = DateTimeOffset.FromUnixTimeMilliseconds(long.Parse(unixTime)).LocalDateTime; } int.TryParse(stringVal, out int val); var trendIcon = trend.GetTrendArrowFromDexcom(); fetchResult.Value = val; fetchResult.Time = localTime; fetchResult.TrendIcon = trendIcon; } catch (Exception ex) { _logger.LogError("Dexcom fetching failed or received incorrect format. {0}", ex); fetchResult = GetDefaultFetchResult(); } return(fetchResult); }
private async Task CreateIcon() { IsCriticalLow = false; var service = new GlucoseFetchService(new GlucoseFetchConfiguration { DexcomUsername = Constants.DexcomUsername, DexcomPassword = Constants.DexcomPassword, FetchMethod = Constants.FetchMethod, NightscoutUrl = Constants.NightscoutUrl, NightscoutAccessToken = Constants.AccessToken, UnitDisplayType = Constants.GlucoseUnitType }, _logger); PreviousFetchResult = FetchResult; FetchResult = await service.GetLatestReading().ConfigureAwait(false); trayIcon.Text = GetGlucoseMessage(); if (FetchResult.Value <= Constants.CriticalLowBg) { IsCriticalLow = true; } _iconService.CreateTextIcon(FetchResult, IsCriticalLow, trayIcon); if (PreviousFetchResult != null && PreviousFetchResult.TrendIcon != "⮅" && PreviousFetchResult.TrendIcon != "⮇" && (FetchResult.TrendIcon == "⮅" || FetchResult.TrendIcon == "⮇")) { // Show balloon when the trend changes to double arrow trayIcon.ShowBalloonTip(3000, "Glucose", $"{FetchResult.TrendIcon} {FetchResult.Value}", ToolTipIcon.Warning); } if (PreviousFetchResult != null && PreviousFetchResult.Value < Constants.HighBg && FetchResult.Value >= Constants.HighBg) { // Show balloon when it crosses the HighBG threshold trayIcon.ShowBalloonTip(3000, "Glucose", $"{FetchResult.TrendIcon} {FetchResult.Value}", ToolTipIcon.Warning); } if (PreviousFetchResult != null && PreviousFetchResult.Value > Constants.LowBg && FetchResult.Value <= Constants.LowBg) { // Show balloon when it crosses the LowBG threshold trayIcon.ShowBalloonTip(3000, "Glucose", $"{FetchResult.TrendIcon} {FetchResult.Value}", ToolTipIcon.Warning); } }
private async Task <GlucoseFetchResult> GetFetchResultFromDexcom(GlucoseFetchResult fetchResult) { // Get Session Id var request = new HttpRequestMessage(HttpMethod.Post, new Uri($"https://{_dexcomShareHost}/ShareWebServices/Services/General/LoginPublisherAccountByName")) { Content = new StringContent("{\"accountName\":\"" + _config.DexcomUsername + "\"," + "\"applicationId\":\"d8665ade-9673-4e27-9ff6-92db4ce13d13\"," + "\"password\":\"" + _config.DexcomPassword + "\"}", Encoding.UTF8, "application/json") }; var client = new HttpClient(); try { var response = await client.SendAsync(request).ConfigureAwait(false); var sessionId = (await response.Content.ReadAsStringAsync().ConfigureAwait(false)).Replace("\"", ""); request = new HttpRequestMessage(HttpMethod.Post, new Uri($"https://{_dexcomShareHost}/ShareWebServices/Services/Publisher/ReadPublisherLatestGlucoseValues?sessionId={sessionId}&minutes=1440&maxCount=1")); var result = JsonConvert.DeserializeObject <List <DexcomResult> >(await(await client.SendAsync(request).ConfigureAwait(false)).Content.ReadAsStringAsync().ConfigureAwait(false)).First(); var unixTime = string.Join("", result.ST.Where(char.IsDigit)); var trend = result.Trend; fetchResult.Value = result.Value; fetchResult.Time = !string.IsNullOrWhiteSpace(unixTime) ? DateTimeOffset.FromUnixTimeMilliseconds(long.Parse(unixTime)).LocalDateTime : DateTime.MinValue; fetchResult.TrendIcon = trend.GetTrendArrow(); response.Dispose(); } catch (Exception ex) { _logger.LogError("Dexcom fetching failed or received incorrect format. {0}", ex); fetchResult = GetDefaultFetchResult(); } finally { client.Dispose(); request.Dispose(); } return(fetchResult); }
private async Task CreateIcon() { IsCriticalLow = false; var service = new GlucoseFetchService(new GlucoseFetchConfiguration { DexcomUsername = Constants.DexcomUsername, DexcomPassword = Constants.DexcomPassword, FetchMethod = Constants.FetchMethod, NightscoutUrl = Constants.NightscoutUrl, NightscoutAccessToken = Constants.AccessToken, UnitDisplayType = Constants.GlucoseUnitType }, _logger); FetchResult = await service.GetLatestReading().ConfigureAwait(false); trayIcon.Text = GetGlucoseMessage(); if (FetchResult.Value <= Constants.CriticalLowBg) { IsCriticalLow = true; } _iconService.CreateTextIcon(FetchResult, IsCriticalLow, trayIcon); }
private async Task <GlucoseFetchResult> GetFetchResultFromNightscout(GlucoseFetchResult fetchResult) { var request = new HttpRequestMessage(HttpMethod.Get, new Uri($"{_config.NightscoutUrl}/api/v1/entries/sgv?count=1" + (!string.IsNullOrWhiteSpace(_config.NightscoutAccessToken) ? $"&token={_config.NightscoutAccessToken}" : ""))); request.Headers.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); var client = new HttpClient(); try { var response = await client.SendAsync(request).ConfigureAwait(false); var result = await response.Content.ReadAsStringAsync().ConfigureAwait(false); var content = JsonConvert.DeserializeObject <List <NightScoutResult> >(result).FirstOrDefault(); fetchResult.Value = content.sgv; fetchResult.Time = DateTime.Parse(content.dateString); fetchResult.TrendIcon = content.direction.GetTrendArrow(); if (fetchResult.TrendIcon.Length > 1) { _logger.LogWarning($"Un-expected value for direction/Trend {content.direction}"); } response.Dispose(); } catch (Exception ex) { _logger.LogError("Nightscout fetching failed or received incorrect format. {0}", ex); fetchResult = GetDefaultFetchResult(); } finally { client.Dispose(); request.Dispose(); } return(fetchResult); }
public static string StaleMessage(this GlucoseFetchResult fetchResult, int minutes) { var ts = System.DateTime.Now - fetchResult.Time; return(ts.TotalMinutes > minutes ? $"\r\n{ts.TotalMinutes:#} minutes ago" : ""); }
public static bool IsStale(this GlucoseFetchResult fetchResult, int minutes) { var ts = System.DateTime.Now - fetchResult.Time; return(ts.TotalMinutes > minutes); }
private void ConvertMGtoMMOL(GlucoseFetchResult fetchResult) => fetchResult.Value /= 18;