public async Task RunAsync(CancellationToken cancellationToken) { var readInterval = _cpuTemperatureMonitorConfiguration.Value.ReadInterval; _logger.LogInformation($"Starting to monitor CPU temperature. Will read every {readInterval}."); while (!cancellationToken.IsCancellationRequested) { try { var reading = _temperatureReader.Read(); var test = new TemperatureReading(true, 12.34d); var message = new Message( Encoding.ASCII.GetBytes( JsonConvert.SerializeObject( reading, new JsonSerializerSettings() { ContractResolver = new CamelCasePropertyNamesContractResolver() }))); message.Properties.Add("couldRead", reading.CouldRead ? "true" : "false"); _logger.LogInformation($"Sending reading [{reading.Celcius.ToString("F")}°C] to Azure IoT Hub."); await _deviceClient.SendEventAsync(message, cancellationToken); } catch (Exception exception) { _logger.LogError(exception, "Unable to send CPU temperature to Azure IoT Hub."); } await Task.Delay(readInterval); } }
public void FailingTemp_Under() { ContainerType Pilsner = new ContainerType(1, 4, 6, "Pilsner"); IThermometer thermometer = new StubThermometer("therm1", 3.99); Monitor monitor = new Monitor(thermometer, Pilsner); TemperatureReading reading = monitor.Check(); Assert.Equal(TemperatureStatus.Under, reading.Status); }
static void MonitorSchedule__MonitorReadEvent(object sender, EventArgs e) { TemperatureReadingEventArgs args = (TemperatureReadingEventArgs)e; TemperatureReading reading = args.Reading; Console.WriteLine(reading.Description()); if (reading.Status != TemperatureStatus.Good) { Console.WriteLine("******WARNING******"); } }
public Task SetTemperature(TemperatureReading reading) { if (this.temperatures.Keys.Contains(reading.DeviceId)) { this.temperatures[reading.DeviceId] = reading.Value; } else { this.temperatures.Add(reading.DeviceId, reading.Value); } return(TaskDone.Done); }
public async Task <bool> ConvertAndAdd(IBrowserFile browserFile) // Skapar tempfil av filen man skickat in, för att läsa in och sedan ta bort då den inte längre behövs. // Kopierar tempfilen till en riktig fil. Ökade värdet på OpenReadStream(20000000) då filen är större än värdet som tillåts. { var dataList = new List <TemperatureReading>(); var filePath = Path.GetTempFileName(); using (var stream = File.Create(filePath)) { await browserFile.OpenReadStream(20000000).CopyToAsync(stream); /**/ } var data = await File.ReadAllLinesAsync(filePath); File.Delete(filePath); for (int i = 0; i < data.Length; i++) // Inläsning av alla rader från filen. Sparar som entiteter i en lista som vi sedan skickar till databasen och sparar. { var item = data[i]; if (item != null) { var splittedData = item.Split(","); if (splittedData.Length == 4) { try { TemperatureReading temperatureReading = new TemperatureReading() { Date = DateTime.Parse(splittedData[0].Replace(" ", "T")), Location = splittedData[1], Temperature = double.Parse(splittedData[2], NumberFormatInfo.InvariantInfo), Humidity = int.Parse(splittedData[3]) }; dataList.Add(temperatureReading); } catch (Exception e) { System.Diagnostics.Debug.WriteLine(e.Message); System.Diagnostics.Debug.WriteLine(i + 1); throw; } } } } await _efContext.TemperatureReadings.AddRangeAsync(dataList); await _efContext.SaveChangesAsync(); return(true); }
protected void buttonRequest_ServerClick(object sender, EventArgs e) { try { string nric = ViewState["GridViewPatientSelectedNRIC"].ToString(); short permission = 0; if (CheckBoxTypeHeightMeasurement.Checked) { permission += new HeightMeasurement().permissionFlag; } if (CheckBoxTypeWeightMeasurement.Checked) { permission += new WeightMeasurement().permissionFlag; } if (CheckBoxTypeTemperatureReading.Checked) { permission += new TemperatureReading().permissionFlag; } if (CheckBoxTypeBloodPressureReading.Checked) { permission += new BloodPressureReading().permissionFlag; } if (CheckBoxTypeECGReading.Checked) { permission += new ECGReading().permissionFlag; } if (CheckBoxTypeMRI.Checked) { permission += new MRI().permissionFlag; } if (CheckBoxTypeXRay.Checked) { permission += new XRay().permissionFlag; } if (CheckBoxTypeGait.Checked) { permission += new Gait().permissionFlag; } therapistBLL.SubmitRequest(nric, permission); ScriptManager.RegisterStartupScript(this, GetType(), "alert", "$('#modalSelectPermissions').modal('hide');toastr['success']('Request Submitted to " + nric + " for Permissions.');", true); Bind_GridViewPatient(); } catch { ScriptManager.RegisterStartupScript(this, GetType(), "alert", "$('#modalSelectPermissions').modal('hide');toastr['error']('Error occured when Submitting Request.');", true); } }
/// <summary> /// Denna metoden tar in en fil som användaren har valt, /// filen läses in som en temporär fil på hårddisken och tas bort så fort den inte behövs mer. /// Använder OpenReadStream(20000000) då filen var större än default värdet. /// När datan har lästs in från fil, skapar vi upp entiteter som läggs i en lista /// som vi sedan skickar in till databasen och sparar. /// </summary> /// <param name="browserFile">Filen som användaren har valt.</param> /// <returns>En boolean på om det lyckats eller inte.</returns> public async Task <bool> ConvertAndAdd(IBrowserFile browserFile) { var dataList = new List <TemperatureReading>(); var filePath = Path.GetTempFileName(); using (var stream = File.Create(filePath)) { await browserFile.OpenReadStream(20000000).CopyToAsync(stream); } var data = await File.ReadAllLinesAsync(filePath); File.Delete(filePath); for (int i = 0; i < data.Length; i++) { var item = data[i]; if (item != null) { var splittedData = item.Split(","); if (splittedData.Length == 4) { try { TemperatureReading temperatureReading = new TemperatureReading() { Date = DateTime.Parse(splittedData[0].Replace(" ", "T")), Thermometer = splittedData[1], Temperature = double.Parse(splittedData[2], NumberFormatInfo.InvariantInfo), Humidity = int.Parse(splittedData[3]) }; dataList.Add(temperatureReading); } catch (Exception e) { System.Diagnostics.Debug.WriteLine(e.Message); System.Diagnostics.Debug.WriteLine(i + 1); return(false); } } } } await _weatherDataContext.temperatureReadings.AddRangeAsync(dataList); await _weatherDataContext.SaveChangesAsync(); return(true); }
public HomeAutomationReadings() { TemperatureReading = new TemperatureReading { Quadrant = Quadrant.TopLeft }; HumidityReading = new HumidityReading { Quadrant = Quadrant.TopRight }; GarageDoorReading = new GarageDoorReading { Quadrant = Quadrant.BottomRight }; PressureReading = new PressureReading { Quadrant = Quadrant.BottomLeft }; }
public void Insert(TemperatureReading temperatureReading) { try{ if (temperatureReading.Id == 0) { _temperatureReadingRepository.Insert(temperatureReading); } else { _temperatureReadingRepository.Update(temperatureReading); } } catch (Exception ex) { throw new Exception(ex.Message); } }
// POST api/sensors public string Post([FromBody] SensorDataModel sensorDataModel) { try { var unitService = new UnitService(); var soilReadingService = new SoilReadingService(); var temperatureReadingService = new TemperatureReadingService(); var rainEventService = new RainEventService(); var cstZone = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time"); var now = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, cstZone); var unitId = unitService.ValidateProductKey(sensorDataModel.ProductKey); if (unitId == -1) { return("Invalid product key."); } var unitSettings = unitService.GetUnitById(unitId).Settings; var rainFlag = (unitSettings != null && unitSettings.RainLimit < sensorDataModel.Rain); //if (unitSettings != null && unitSettings.RainLimit < sensorDataModel.Rain) { var rainEvent = new RainEvent { DateTime = now, UnitId = unitId, RainAmount = sensorDataModel.Rain }; rainEventService.Insert(rainEvent); //rainFlag = true; //} var soilLimitsDict = sensorDataModel.SoilReadings.ToDictionary(x => (int.Parse(x.SensorNumber) - 1), x => (unitSettings != null && x.SoilMoisture > unitSettings.SoilMoistureLimit)); var tempFlag = unitSettings != null && unitSettings.StopOnFreeze && sensorDataModel.Temperature < 34.0; var commandDict = unitService.GetValveCommands(unitId, soilLimitsDict, tempFlag, rainFlag); soilReadingService.Insert(sensorDataModel.SoilReadings, unitId); var tempReading = new TemperatureReading { UnitId = unitId, DateTime = now, Temperature = sensorDataModel.Temperature }; temperatureReadingService.Insert(tempReading); var serializer = new JavaScriptSerializer(); var jsonString = serializer.Serialize(commandDict); return(jsonString); } catch (Exception ex) { return(ex.Message); } }
public IActionResult Create([FromBody] TemperatureReading reading) { LogIpAddress(); if (!this.Request.Host.ToString().ToLower().Contains("localhost")) { return(this.Unauthorized()); } var tst = this.Request; if (reading == null) { return(BadRequest()); } _context.TemperatureReadings.Add(reading); _context.SaveChanges(); return(CreatedAtRoute("GetTemperatureReading", new { id = reading.Id }, reading)); }
private static async Task SimulateDeviceAsync() { var currentTemperature = 21d; var rand = new Random(); while (true) { // Get a new temperature var temperatureDifference = Math.Round(rand.NextDouble() / 2, 2); // If the heater is on we add the value, otherwise we subtract if (!_isHeaterOn) { temperatureDifference *= rand.Next(-1, 0); } currentTemperature += temperatureDifference; // Create the message and upload to IoT Hub var reading = new TemperatureReading() { Temperature = currentTemperature, TargetTemperatureMinimum = _targetTemperatureMinimum, TargetTemperatureMaximum = _targetTemperatureMaximum }; string messageString = JsonConvert.SerializeObject(reading); var message = new Message(Encoding.ASCII.GetBytes(messageString)); message.Properties.Add("isHeaterOn", _isHeaterOn.ToString()); await _deviceClient.SendEventAsync(message); Console.WriteLine($"{DateTime.UtcNow} - Sent Message - {messageString}"); // Wait 2 seconds before sending the next message await Task.Delay(1000); } }
public void OnPriceDifference(TemperatureReading reading) { Console.WriteLine(reading.ToIndentedJson()); }
public static async Task SimulateData( ) { // registry manager to access registered devices RegistryManager registryManager = null; try { // create an IoT Hub Registry manager to get access to the device registryManager = RegistryManager.CreateFromConnectionString(Strings.IoTHubConnectionString); } catch (Exception ex) { Console.WriteLine("Couldn't create Event Hub registry manager: " + ex.Message); } try { var devices = DeviceFactory.Instance.Devices; // for each device simulate some data foreach (var deviceModel in devices) { // get the device as we need it's unique security credentials Device device = null; try { device = await registryManager.GetDeviceAsync(deviceModel.DeviceId); } catch (Exception ex) { Console.WriteLine("Error with GetDeviceAsync: " + ex.GetText(true)); } if (device != null && deviceModel.Generate) { // create the client object so we can start to send data var deviceClient = DeviceClient.Create(Strings.IotHubHostname, new DeviceAuthenticationWithRegistrySymmetricKey(device.Id, device.Authentication.SymmetricKey.PrimaryKey), Microsoft.Azure.Devices.Client.TransportType.Amqp_Tcp_Only); await deviceClient.OpenAsync(); // we will randomly generate data around these average values double avgInternalTemp = 20; // celcius Random rand = new Random(); // get the sensor readings for 4 stands double internaltemp = avgInternalTemp + (rand.NextDouble() * 4) - 1; // actual temp values from thermostat, could be anything just under 20 to about 23 double numberofPeople = 40 + (rand.NextDouble() * 4) - 1; // actual temp values from thermostat, could be anything just under 20 to about 23 // make this random to simulate somebody just pressing boost int isHeatingOn = (int)Math.Round(rand.NextDouble()); // capture the time that the reading is taken DateTime time = DateTime.Now.ToUniversalTime(); // create an object to represent the data TemperatureReading telemetryDataPoint = new TemperatureReading { DeviceId = device.Id, DeviceName = deviceModel.DeviceName, FloorArea = deviceModel.FloorArea, ExternalTemp = internaltemp - 15, Internaltemp = internaltemp, IsHeatingOn = isHeatingOn, NumberofPeople = (int)numberofPeople, Time = time }; // create the message to send var message = new Microsoft.Azure.Devices.Client.Message(Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(telemetryDataPoint))); // send to IoT Hub try { await Helpers.OperationWithBasicRetryAsync <object>(async() => { await deviceClient.SendEventAsync(message); DataPointsSent++; #if DEBUG Console.WriteLine("Sending data to hub {0} > temp: {1}, is heating on: {2}, # People: {3}", device.Id + " " + time.ToString("HH:mm:ss"), internaltemp.ToString(), isHeatingOn.ToString(), numberofPeople.ToString()); #endif return(null); }, 3); } catch (Exception ex) { System.Diagnostics.Trace.WriteLine("Error: " + ex.GetText(true)); } finally { try { await deviceClient.CloseAsync(); } catch { } } } } } catch (Exception ex) { System.Diagnostics.Trace.WriteLine("Couldn't send data to cloud: " + ex.GetText(true)); } }
public Task TempReading([FromBody] TemperatureReading reading) { return(_messaging.PublishAsync(reading)); }