public void RecentWhenNewyReturnsZero() { var record = new TemperatureRecord(TimeSpan.FromMinutes(5)); var recent = record.RecentMaximum(TimeSpan.FromSeconds(5)); Assert.Equal(0, recent); }
public async Task <ActionResult> Create(TemperatureRecord temperatureRecord) { try { //var stringContent = new StringContent(jObject.ToString()); //var response = await httpClient.PostAsync("http://www.sample.com/write", stringContent); string message = JsonConvert.SerializeObject(temperatureRecord); HttpContent hc = new StringContent(message, Encoding.UTF8, "application/json"); HttpResponseMessage response = await Client.PostAsync("https://localhost:44365/api/temperature", hc); // await Client.GetAsync("https://localhost:44365/api/temperature"); // (if status code is not 200-299 (for success)) if (!response.IsSuccessStatusCode) { return(RedirectToAction("Error", "Home")); } // get the whole response body (second await) //var responseBody = await response.Content.ReadAsStringAsync(); return(RedirectToAction(nameof(Index))); } catch { return(View()); } }
public ActionResult Save(TemperatureRecord temperatureRecord) { if (!ModelState.IsValid) { var temp = new TemperatureRecord(); temperatureRecord.ID = temp.ID; return(View("View", temp)); } if (temperatureRecord.ID == "New") { var key = Guid.NewGuid().ToString(); temperatureRecord.ID = key; _context.TemperatureRecord.Add(temperatureRecord); } else { var dataFromDb = _context.TemperatureRecord.Single(c => c.ID == temperatureRecord.ID); //dataFromDb.時間 = temperatureRecord.時間; //dataFromDb.第1段溫度顯示值 = temperatureRecord.第1段溫度顯示值; //dataFromDb.第2段溫度顯示值 = temperatureRecord.第2段溫度顯示值; //dataFromDb.第3段溫度顯示值 = temperatureRecord.第3段溫度顯示值; //dataFromDb.第4段溫度顯示值 = temperatureRecord.第4段溫度顯示值; //dataFromDb.第5段溫度顯示值 = temperatureRecord.第5段溫度顯示值; //dataFromDb.第6段溫度顯示值 = temperatureRecord.第6段溫度顯示值; var entry = _context.Entry(dataFromDb); entry.CurrentValues.SetValues(temperatureRecord); } _context.SaveChanges(); return(RedirectToAction("Index", "View")); }
public async Task <ActionResult> Edit(TemperatureRecord temperatureRecord) { try { string message = JsonConvert.SerializeObject(temperatureRecord); HttpContent hc = new StringContent(message, Encoding.UTF8, "application/json"); HttpResponseMessage response = await Client.PutAsync("https://localhost:44365/api/temperature/" + temperatureRecord.Id, hc); // await Client.GetAsync("https://localhost:44365/api/temperature"); // (if status code is not 200-299 (for success)) if (!response.IsSuccessStatusCode) { return(RedirectToAction("Error", "Home")); } return(RedirectToAction(nameof(Index))); } catch { return(View()); } }
public async Task <ActionResult> Create(TemperatureRecord record) { try { // set unit to 1 (celsius) record.Unit = 1; // use POST method, not GET, based on the route the service has defined HttpRequestMessage request = CreateRequestToService(HttpMethod.Post, "api/temperature", record); HttpResponseMessage response = await Client.SendAsync(request); if (!response.IsSuccessStatusCode) { if (response.StatusCode == HttpStatusCode.Unauthorized) { return(RedirectToAction("Login", "Account")); } return(View(record)); } return(RedirectToAction(nameof(Index))); } catch { return(View(record)); } }
public static void SaveTemperatureRecord(TemperatureRecord record) { using (var ctx = new IotContext()) { ctx.TemperatureRecords.Add(record); ctx.SaveChanges(); } }
public ActionResult New() { var temp = new TemperatureRecord(); string key = "New"; temp.ID = key; return(View("View", temp)); }
public ActionResult DeleteConfirmed(int id) { TemperatureRecord temperatureRecord = db.TemperatureRecords.Find(id); db.TemperatureRecords.Remove(temperatureRecord); db.SaveChanges(); return(RedirectToAction("Index")); }
private IEnumerable <TemperatureRecord> ReadTemperatureRecords(IDataReader reader) { while (reader.Read()) { var temperatureRecord = new TemperatureRecord(); temperatureRecord.Time = (DateTime)reader["Recorded At"]; temperatureRecord.Value = (decimal)reader["Temperature"]; yield return(temperatureRecord); } }
public FanController(FanCurve quietProfile, FanCurve sustainedProfile, int?overheatThreshold, byte maxTemperature, TimeSpan maxOverheatAllowance) { _quietProfile = quietProfile; _sustainedProfile = sustainedProfile; _overheatThreshold = (byte)(overheatThreshold ?? quietProfile.Thresholds.Max(t => t.temp)); _maxTemperature = Math.Max(maxTemperature, _overheatThreshold); _maxOverheatAllowance = maxOverheatAllowance; _temperature = new TemperatureRecord(TimeSpan.FromSeconds(Math.Max(15, maxOverheatAllowance.TotalSeconds))); _currentMode = Mode.SustainedLoad; }
public void RecentWhenOldReturnsLast() { var record = new TemperatureRecord(TimeSpan.FromMinutes(5)); record.Push(DateTime.Now - TimeSpan.FromMinutes(30), 50); record.Push(DateTime.Now - TimeSpan.FromMinutes(25), 55); var recent = record.RecentMaximum(TimeSpan.FromSeconds(5)); Assert.Equal(55, recent); }
public ActionResult Edit([Bind(Include = "TemperatureRecord1,UsersID,TemperatureReading,DateCaptured")] TemperatureRecord temperatureRecord) { if (ModelState.IsValid) { db.Entry(temperatureRecord).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Index")); } ViewBag.UsersID = new SelectList(db.Users, "UsersID", "FullName", temperatureRecord.UsersID); return(View(temperatureRecord)); }
public async Task <bool> AddTemperatureLog(TemperatureRecord temperatureRecord) { if (_context.Employees.Any(Employee => Employee.EmployeeNumber == temperatureRecord.EmployeeId)) { temperatureRecord.RecordDate = DateTime.Now; _context.TemperatureRecords.Add(temperatureRecord); await _context.SaveChangesAsync(); return(true); } return(false); }
public ActionResult Edit(string id) { var data = _context.TemperatureRecord.SingleOrDefault(c => c.ID == id); if (data == null) { return(HttpNotFound()); } var temp = new TemperatureRecord(); temp = data; return(View("View", temp)); }
// GET: TemperatureRecords/Details/5 public ActionResult Details(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } TemperatureRecord temperatureRecord = db.TemperatureRecords.Find(id); if (temperatureRecord == null) { return(HttpNotFound()); } return(View(temperatureRecord)); }
// GET: TemperatureRecords/Edit/5 public ActionResult Edit(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } TemperatureRecord temperatureRecord = db.TemperatureRecords.Find(id); if (temperatureRecord == null) { return(HttpNotFound()); } ViewBag.UsersID = new SelectList(db.Users, "UsersID", "FullName", temperatureRecord.UsersID); return(View(temperatureRecord)); }
public void PercentOverThreshold(int minutes, byte threshold, float expected) { var now = DateTime.Now; var record = new TemperatureRecord(TimeSpan.FromMinutes(40)); record.Push(now - TimeSpan.FromMinutes(30), 55); record.Push(now - TimeSpan.FromMinutes(25), 54); record.Push(now - TimeSpan.FromMinutes(10), 53); record.Push(now - TimeSpan.FromMinutes(4), 52); record.Push(now - TimeSpan.FromMinutes(3), 51); var percent = record.RecentPercentOverThreshold(TimeSpan.FromMinutes(minutes), threshold); Assert.Equal(expected, percent); }
public void RecentReturnsMostRecentOnly() { var now = DateTime.Now; var record = new TemperatureRecord(TimeSpan.FromMinutes(5)); record.Push(now - TimeSpan.FromMinutes(30), 55); record.Push(now - TimeSpan.FromMinutes(25), 54); record.Push(now - TimeSpan.FromMinutes(10), 53); record.Push(now - TimeSpan.FromMinutes(4), 52); record.Push(now - TimeSpan.FromMinutes(3), 51); record.Push(now - TimeSpan.FromMinutes(2), 50); var recent = record.RecentMaximum(TimeSpan.FromMinutes(5)); Assert.Equal(52, recent); }
protected override async Task ExecuteAsync(CancellationToken stoppingToken) { while (!stoppingToken.IsCancellationRequested) { var now = DateTime.Now; this.logger.LogInformation("Worker running at: {Time}", DateTime.Now); var temp = await this.temperatureReader.ReadTemperature(); this.logger.LogInformation($"Read temperature: {temp}"); await this.temperatureHubContext.Clients.All.SendAsync("ReceiveTemperature", temp, cancellationToken : stoppingToken); var temperatureRecord = new TemperatureRecord { Date = DateTime.Now, Value = temp }; await this.temperatureSource.AddNewTemperatureRecord(temperatureRecord); } }
static void Main(string[] args) { Options = new Options(); CommandLine.Parser.Default.ParseArguments(args, Options); Console.WriteLine("Press CTRL-C to exit emulator."); Console.WriteLine(); while (true) { var iotHub = Options.GetIotHub(); var deviceId = Options.GetDeviceId(); var key = Options.GetKey(); // Get Temperature Record var temperatureRecord = new TemperatureRecord(Options.GetMinTemperature(), Options.GetMaxTemperature()); var runtime = GetRuntime(); // Build object to send var dataPoints = new { deviceId, tempC = temperatureRecord.Celsius, tempF = temperatureRecord.Fahrenheit, runtime }; // Create message to send var messageString = JsonConvert.SerializeObject(dataPoints); var message = new Message(Encoding.ASCII.GetBytes(messageString)); Console.WriteLine($"{DateTime.Now.ToString("T")} > {messageString}"); // Initialize device client and send message var deviceClient = DeviceClient.Create( iotHub, AuthenticationMethodFactory.CreateAuthenticationWithRegistrySymmetricKey(deviceId, key)); deviceClient.SendEventAsync(message); deviceClient.Dispose(); Thread.Sleep(5000); } }
// POST api/data public HttpResponseMessage Post([FromBody] string value) { //value = this.Request.Content.ReadAsStringAsync().Result; if (!string.IsNullOrEmpty(value)) { var theValues = value.Split(','); TemperatureRecord temp = new TemperatureRecord(); LightLevelRecord light = new LightLevelRecord(); temp.Temperature = Convert.ToDecimal(theValues[0]); light.LightLevel = ConvertLightToOneToHunderRangeValue(Convert.ToInt32(theValues[1])); bool isCountIncremented = false; if (!string.IsNullOrEmpty(theValues[2]) && Convert.ToInt32(theValues[2]) > 0) { isCountIncremented = true; } var theDatabase = GetDatabase(); InfoDataHub.SendTemperature(temp); InfoDataHub.SendLightLevel(light); Task.Factory.StartNew(() => { try { theDatabase.GetCollection <TemperatureRecord>("TemperatureRecord").Insert(temp); theDatabase.GetCollection <LightLevelRecord>("LightLevelRecord").Insert(light); if (isCountIncremented) { var theTimeToTheMinute = string.Format("{0:yyyy-MM-dd HH:mm}", DateTime.Now); var update = Update.Inc("Count", 1).Set("TheTimeStamp", DateTime.Now); theDatabase.GetCollection <CrowdCountRecord>("CrowdCountRecord").Update(Query.EQ("TimeToTheMinute", theTimeToTheMinute), update, UpdateFlags.Upsert); } } catch (Exception ex) { } }); return(this.Request.CreateResponse(HttpStatusCode.Accepted)); } return(this.Request.CreateResponse(HttpStatusCode.InternalServerError)); }
public IHttpActionResult PutData(string id, TemperatureRecord record) { if (!ModelState.IsValid) { return(BadRequest()); } var data = _context.TemperatureRecord.SingleOrDefault(c => c.ID == id); if (data == null) { return(NotFound()); } data = record; _context.SaveChanges(); return(Ok()); }
public async Task <ActionResult> Edit(int id, TemperatureRecord newRecord) { try { newRecord.Unit = 1; var url = $"https://localhost:44373/api/temperature/{id}"; var response = await Client.PutAsJsonAsync(url, newRecord); if (response.IsSuccessStatusCode) { return(RedirectToAction(nameof(Index))); } return(View(newRecord)); } catch { return(View(newRecord)); } }
public async Task <ActionResult> Create(TemperatureRecord newRecord) { try { // set unit to 1 (Celsius) newRecord.Unit = 1; // use POST method, not GET, based on the route the service has defined HttpResponseMessage response = await Client.PostAsync("https://localhost:44373/api/temperature", ToContent(newRecord)); if (response.IsSuccessStatusCode) { return(RedirectToAction(nameof(Index))); } return(View(newRecord)); } catch { return(View()); } }
public async Task Given_TemperatureRepository_When_AddingATemperatureRecord_Then_TheRecordShouldBeMemorizedAsync() { await RunOnDatabaseAsync(async sut => { //Arrange var repo = new TemperatureRepository(sut); var record = new TemperatureRecord { Id = Guid.NewGuid(), UserId = Guid.NewGuid(), Value = 10, Time = new DateTime(2017, 11, 20, 11, 21, 1) }; //Act await repo.AddAsync(record); await repo.SaveChangesAsync(); //Assert var results = await repo.GetAllAsync(); results[0].ShouldBeEquivalentTo(record); }); }
public async Task Given_TemperatureRepository_When_GettingAllTemperatureRecords_Then_AllRecordsShouldBeReturnedAsync() { await RunOnDatabaseAsync(async sut => { //Arrange var repo = new TemperatureRepository(sut); var record = new TemperatureRecord { Id = Guid.NewGuid(), UserId = Guid.NewGuid(), Value = 10, Time = new DateTime(2017, 11, 20, 11, 21, 1) }; //Act await repo.AddAsync(record); await repo.SaveChangesAsync(); //Assert var results = await repo.GetAllAsync(); results.Count.Should().Be(1); }); }
public async Task Given_AddTemperatureRecord_When_AddingAValidTemperatureRecord_Then_TemperatureRecordShouldBeAddedAndIdReturnedAsync() { //Arrange var expectedId = Guid.NewGuid(); var toStore = new TemperatureRecord { Id = expectedId, UserId = Guid.NewGuid(), Value = 0, Time = new DateTime(2017, 11, 10, 12, 12, 12) }; Mapper.Setup(x => x.Map <TemperatureRecord>(It.IsAny <AddTemperatureRecordCommand>())).Returns(toStore); var sut = new AddTemperatureRecordHandler(Repo.Object, Mapper.Object); //Act var result = await sut.Handle(new AddTemperatureRecordCommand(), CancellationToken.None); //Assert Repo.Verify(x => x.AddAsync(It.IsAny <TemperatureRecord>()), Times.Once); Repo.Verify(x => x.SaveChangesAsync(), Times.Once); result.Id.Should().Be(expectedId); }
private async void ReadTemperature(ThreadPoolTimer timer) { try { TemperatureRecord tr = new TemperatureRecord(); lock (readerLock) { spiReader.TransferFullDuplex(writeBuffer, readBuffer); //voltage = ADC_value / 1024 * 3.3 = 0.621 V //TMP36 is 0.5V at 0 C and 10 mV per degree //Temp_in_C = (voltage - 0.5) / 0.01 int adcData = convertToInt(readBuffer); double inputVolt = 3.3; double sensorVolt = adcData/(double)1024*inputVolt; tr.CelsiusTemperature = Convert.ToSingle((sensorVolt - 0.5)/0.01); tr.TimeStamp = DateTime.Now.ToLocalTime(); temperatureData.AddRecord(tr); } await LogToFile("Date: " + DateTime.Now + ", temp: " + tr.CelsiusTemperature); } catch (Exception ex) { LogExceptionAsync(nameof(ReadTemperature), ex).Wait(); if (Debugger.IsAttached) { Debugger.Break(); } // If it goes to shit here, rethrow which will terminate the process - but at least we have it logged! throw ex; } }
public Task <EntityEntry <TemperatureRecord> > AddAsync(TemperatureRecord record) { return(_context.TemperatureRecords.AddAsync(record)); }
public void Send(TemperatureRecord temperature, LightLevelRecord lightLevel) { }
public static void SendTemperature(TemperatureRecord temperature) { var hubContext = GlobalHost.ConnectionManager.GetHubContext <InfoDataHub>(); hubContext.Clients.All.sendTemperature(Convert.ToInt32(temperature.Temperature).ToString()); }
/// <summary> /// Adds the specified WeatherRecord, pointint the Current property to it and adding to the data list(s). /// </summary> /// <param name="record"></param> public void AddRecord(TemperatureRecord record) { lock (Current) { Current = record; // Also, do housekeeping and aggregation if appropriate. AggregateData(); // After aggregating, insert to the CurrentHourRecords and set currentHour. // If we're in a new hour, record will become the first entry in the list. Otherwise it'll just add to the list of entries. lock (CurrentHourRecords) { CurrentHourRecords.Add(record); } currentHour = Current.TimeStamp; } }
/// <summary> /// Aggregates data if appropriate. This happenes within a lock(Current) to /// </summary> private void AggregateData() { // Still in the same hour? do nothing if (currentHour.Date == Current.TimeStamp.Date && currentHour.Hour == Current.TimeStamp.Hour) { return; } TemperatureRecord lastHour = new TemperatureRecord(); lastHour.TimeStamp = new DateTime(Current.TimeStamp.Year, Current.TimeStamp.Month, Current.TimeStamp.Day, Current.TimeStamp.Hour, 0, 0); lock (CurrentHourRecords) { lastHour.CelsiusTemperature = CurrentHourRecords.Average(wr => wr.CelsiusTemperature); CurrentHourRecords.Clear(); } // Add to our list of last 24hours, and remove any entries that are too old. lock (Last24HourRecords) { Last24HourRecords.Add(lastHour); Last24HourRecords.RemoveAll(wr => wr.TimeStamp < lastHour.TimeStamp.AddDays(-1)); } // If we're not on a new day, do not continue (as we will add a days average to the 30days list). if (currentHour.Date == Current.TimeStamp.Date) { return; } TemperatureRecord lastDay = new TemperatureRecord(); lastDay.TimeStamp = new DateTime(currentHour.Year, currentHour.Month, currentHour.Day, 0, 0, 0); lock (Last24HourRecords) { var currentDayRecords = Last24HourRecords.Where(wr => wr.TimeStamp.Day == currentHour.Day).ToList(); lastDay.CelsiusTemperature = currentDayRecords.Average(wr => wr.CelsiusTemperature); } // Add to our list of last 30 days, and remove any entries that are too old. lock (CurrentMonthRecords) { CurrentMonthRecords.Add(lastHour); CurrentMonthRecords.RemoveAll(wr => wr.TimeStamp < lastHour.TimeStamp.AddMonths(-1)); } }