/// <summary> /// Serializes the TempHumidityEvent to JSON and sends it to the Event Hub's REST API /// </summary> /// <param name="tempHumidityEvent"></param> /// <returns></returns> private async Task SendEventAsync(TempHumidityEvent tempHumidityEvent) { // Convert TempHumidityEvent to JSON var json = JsonConvert.SerializeObject(tempHumidityEvent); var content = new StringContent(json); // Send event var response = await httpClient.PostAsync(baseAddress + "/dachautemp/messages", content); if (response.StatusCode == HttpStatusCode.Unauthorized) { // Maybe token expired available. Renew and try again RefreshAccessToken(); // Try again content = new StringContent(json); response = await httpClient.PostAsync(baseAddress + "/dachautemp/messages", content); } // Check if everything went fine if (!response.IsSuccessStatusCode) { throw new UnauthorizedAccessException("Could not connect to Azure Event Hub. Access denied."); } }
/// <summary> /// Sends a new combination of temperature, humidity and a time stamp to the Event Hub /// </summary> /// <param name="temperature">Current temperature</param> /// <param name="humidity">Current humidity</param> /// <returns></returns> public async Task SendTempAndHumidityAsync(double temperature, double humidity) { // Round to full seconds and milliseconds var now = DateTime.Now.ToUniversalTime(); now = now.AddSeconds(now.Second * -1).AddMilliseconds(now.Millisecond * -1); var tempHumidityEvent = new TempHumidityEvent { DateTime = now, Temperature = temperature, Humidity = humidity }; await SendEventAsync(tempHumidityEvent); }