private async Task Run(string deviceId) { var connectionString = ConfigurationManager.ConnectionStrings["TemperatureDb"].ConnectionString; while (true) { using (TemperatureReadingContext context = new TemperatureReadingContext(connectionString)) { try { var reading = context.Readings.Where(t => t.DeviceId == deviceId) .OrderByDescending(t => t.EndTime).First(); _hubContext.Clients.Group(deviceId).pump(reading); } catch (Exception ex) { System.Diagnostics.Trace.TraceError(ex.Message); if (ex.InnerException != null) { System.Diagnostics.Trace.TraceError(ex.InnerException.Message); } } } await Task.Delay(1000); } }
private async Task RunAsync(CancellationToken cancellationToken) { var temperatureDbConnectionString = CloudConfigurationManager.GetSetting("TemperatureDbConnectionString"); var notificationEndpoint = CloudConfigurationManager.GetSetting("NotificationUri"); var heater = new HeaterCommunication(); var temperatureSensor = new DeviceReliabilityServiceClient(DeviceReliabilityServiceClient.FailAction.Reliable); while (true) { var correlationId = Guid.NewGuid().ToString("n"); var heaterStatus = heater.Query(correlationId); if (heaterStatus == HeaterStatus.UNKNOWN) { Trace.TraceInformation("The Heater is in an unknown state. Looping to retry acquisition of device status"); continue; } using (TemperatureReadingContext temperatureDb = new TemperatureReadingContext(temperatureDbConnectionString)) { //get the most recent entry var tempReading = temperatureDb.Readings.OrderByDescending(t => t.StartTime).First(); // Call AzureML to determine whether the temperature reading is in an acceptable range var reliable = await temperatureSensor.IsDeviceReliable(correlationId, tempReading.Temperature); if (!reliable) { Trace.TraceInformation("The Temperature reading of {0} is outside the ML calculated cluster of accuracy. Looping to await a different reading.", tempReading.Temperature); continue; } if (tempReading.Temperature >= 22) { if (heaterStatus == HeaterStatus.ON) { heater.TurnOff(correlationId); NotifyWebUi(notificationEndpoint, false); } } else if (tempReading.Temperature <= 20) { if (heaterStatus == HeaterStatus.OFF) { heater.TurnOn(correlationId); NotifyWebUi(notificationEndpoint, true); } } } await Task.Delay(5000);//temperature is recorded at a freshness hertz of 60 seconds, check twice as frequently } }
public TemperatureReadingController(TemperatureReadingContext context) { _context = context; }