private static string GetTemperaturePropertyString(Thermostat thermostat, double desiredTemperature, TemperatureMode temperatureMode) { string temperatureTargetString = "\"target_temperature\":{0}"; string temperatureRangeString = "\"target_temperature_low\":{0},\"target_temperature_high\":{1}"; TemperatureScale scale = thermostat.TemperatureScale; double desiredTempCelsius = ConvertFrom(scale, desiredTemperature); string temperatureProperty = null; if (temperatureMode == TemperatureMode.RangeLow) { double highTempCelsius = ConvertFrom(scale, thermostat.TargetTemperatureHigh); temperatureProperty = string.Format(temperatureRangeString, desiredTempCelsius, highTempCelsius); } else if (temperatureMode == TemperatureMode.RangeHigh) { double lowTempCelsius = ConvertFrom(scale, thermostat.TargetTemperatureLow); temperatureProperty = string.Format(temperatureRangeString, lowTempCelsius, desiredTempCelsius); } else { temperatureProperty = string.Format(temperatureTargetString, desiredTempCelsius); } return(temperatureProperty); }
public void SetUp() { _statusProvider = new Mock<IStatusProvider>(); _sessionProvider = new Mock<ISessionProvider>(); _analyticsService = new Mock<IAnalyticsService>(); _nestWebService = new Mock<INestWebService>(); _statusUpdaterService = new Mock<IStatusUpdaterService>(); _structure = new Structure("1"); _firstThermostat = new Thermostat("1"); _secondThermostat = new Thermostat("1"); _structure.Thermostats.Add(_firstThermostat); _structure.Thermostats.Add(_secondThermostat); var structures = new List<Structure> { _structure }; _nestWebService.Setup(w => w.LoginAsync(It.IsAny<string>(), It.IsAny<string>())).Returns(Task.FromResult(new WebServiceResult())); _nestWebService.Setup(w => w.UpdateTransportUrlAsync()).Returns(Task.FromResult(new WebServiceResult())); _nestWebService.Setup(w => w.SetAwayMode(It.IsAny<Structure>(), It.IsAny<bool>())).Returns(Task.FromResult(new WebServiceResult())); _nestWebService.Setup(w => w.GetFullStatusAsync()).Returns(Task.FromResult(new GetStatusResult(structures))); _nestWebService.Setup(w => w.ChangeTemperatureAsync(It.IsAny<Thermostat>(), It.IsAny<double>(), It.IsAny<TemperatureMode>())).Returns(Task.FromResult(new WebServiceResult())); _nestWebService.Setup(w => w.SetFanModeAsync(It.IsAny<Thermostat>(), It.IsAny<FanMode>())).Returns(Task.FromResult(new WebServiceResult())); _nestWebService.Setup(w => w.SetHvacModeAsync(It.IsAny<Thermostat>(), It.IsAny<HvacMode>())).Returns(Task.FromResult(new WebServiceResult())); _statusUpdaterService.Setup(s => s.UpdateStatusAsync()).Returns(Task.Delay(0)); ServiceContainer.RegisterService<IStatusProvider>(_statusProvider.Object); ServiceContainer.RegisterService<ISessionProvider>(_sessionProvider.Object); ServiceContainer.RegisterService<IAnalyticsService>(_analyticsService.Object); ServiceContainer.RegisterService<INestWebService>(_nestWebService.Object); ServiceContainer.RegisterService<IStatusUpdaterService>(_statusUpdaterService.Object); _viewModel = new NestViewModel(); }
private async Task <GetThermostatStatusResult> GetSharedThermostatPropertiesAsync(Thermostat thermostat) { string url = string.Format("{0}/v2/subscribe", _sessionProvider.TransportUrl); IWebRequest request = GetPostJsonRequest(url); SetAuthorizationHeaderOnRequest(request, _sessionProvider.AccessToken); SetNestHeadersOnRequest(request, _sessionProvider.UserId); string requestString = string.Format("{{\"keys\":[{{\"key\":\"shared.{0}\"}}]}}", thermostat.ID); await request.SetRequestStringAsync(requestString); Exception exception; try { IWebResponse response = await request.GetResponseAsync(); string strContent = await response.GetResponseStringAsync(); var updatedThermostat = new Thermostat(thermostat.ID); _deserializer.UpdateThermostatStatusFromSharedStatusResult(strContent, updatedThermostat); return(new GetThermostatStatusResult(updatedThermostat)); } catch (Exception ex) { exception = ex; } var error = await _deserializer.ParseWebServiceErrorAsync(exception); return(new GetThermostatStatusResult(error, exception)); }
public async Task <WebServiceResult> SetFanModeAsync(Thermostat thermostat, FanMode fanMode) { string url = string.Format(@"{0}/v2/put/device.{1}", _sessionProvider.TransportUrl, thermostat.ID); string fanModeString = GetFanModeString(fanMode); string requestString = string.Format("{{\"fan_mode\":\"{0}\"}}", fanModeString); return(await SendPutRequestAsync(url, requestString)); }
public async Task <WebServiceResult> SetHvacModeAsync(Thermostat thermostat, HvacMode hvacMode) { string url = string.Format(@"{0}/v2/put/shared.{1}", _sessionProvider.TransportUrl, thermostat.ID); string hvacModeString = _deserializer.GetHvacModeString(hvacMode); string requestString = string.Format("{{\"target_temperature_type\":\"{0}\"}}", hvacModeString); return(await SendPutRequestAsync(url, requestString)); }
public IEnumerable <Structure> ParseStructuresFromGetStatusResult(string responseString, string userId) { var structureResults = new List <Structure>(); var values = JObject.Parse(responseString); var structures = values["user"][userId]["structures"]; foreach (var structure in structures) { string structureId = structure.Value <string>().Replace("structure.", ""); var structureModel = new Structure(structureId); structureModel.IsAway = values["structure"][structureId]["away"].Value <bool>(); structureResults.Add(structureModel); } int deviceCount = 0; foreach (var structureResult in structureResults) { var structure = values["structure"][structureResult.ID]; var devices = structure["devices"]; foreach (var device in devices) { deviceCount++; string thermostatId = device.Value <string>().Replace("device.", ""); var thermostat = new Thermostat(thermostatId); structureResult.Thermostats.Add(thermostat); } } foreach (var structureResult in structureResults) { foreach (var thermostat in structureResult.Thermostats) { var thermostatValues = values["device"][thermostat.ID]; thermostat.FanMode = GetFanModeFromString(thermostatValues["fan_mode"].Value <string>()); thermostat.IsLeafOn = thermostatValues["leaf"].Value <bool>(); TemperatureScale scale = GetTemperatureScaleFromString(thermostatValues["temperature_scale"].Value <string>()); thermostat.TemperatureScale = scale; thermostatValues = values["shared"][thermostat.ID]; double temperature = double.Parse(thermostatValues["target_temperature"].Value <string>()); thermostat.TargetTemperature = Math.Round(ConvertTo(scale, temperature)); double temperatureLow = double.Parse(thermostatValues["target_temperature_low"].Value <string>()); thermostat.TargetTemperatureLow = Math.Round(ConvertTo(scale, temperatureLow)); double temperatureHigh = double.Parse(thermostatValues["target_temperature_high"].Value <string>()); thermostat.TargetTemperatureHigh = Math.Round(ConvertTo(scale, temperatureHigh)); double currentTemperature = double.Parse(thermostatValues["current_temperature"].Value <string>()); thermostat.CurrentTemperature = Math.Round(ConvertTo(scale, currentTemperature)); thermostat.IsHeating = thermostatValues["hvac_heater_state"].Value <bool>(); thermostat.IsCooling = thermostatValues["hvac_ac_state"].Value <bool>(); thermostat.HvacMode = GetHvacModeFromString(thermostatValues["target_temperature_type"].Value <string>()); } } return(structureResults); }
public async Task <WebServiceResult> ChangeTemperatureAsync(Thermostat thermostat, double desiredTemperature, TemperatureMode temperatureMode) { string temperatureProperty = GetTemperaturePropertyString(thermostat, desiredTemperature, temperatureMode); string url = string.Format(@"{0}/v2/put/shared.{1}", _sessionProvider.TransportUrl, thermostat.ID); string requestString = string.Format("{{\"target_change_pending\":true,{0}}}", temperatureProperty); return(await SendPutRequestAsync(url, requestString)); }
public void TearDown() { _statusProvider = null; _sessionProvider = null; _analyticsService = null; _nestWebService = null; _statusUpdaterService = null; _viewModel = null; _structure = null; _firstThermostat = null; _secondThermostat = null; }
public void ShouldUpdateTargetTemperature() { var structure = new Structure(""); var thermostat = new Thermostat("") {TargetTemperature = 48d}; structure.Thermostats.Add(thermostat); var status = new GetStatusResult(new[] {structure}); thermostat.TargetTemperature = 48d; _statusProvider.Raise(provider => provider.StatusUpdated += null, new StatusEventArgs(status)); Assert.AreEqual(thermostat.TargetTemperature, _viewModel.TargetTemperature, "Expected TargetTemperature to update from status change."); }
public IEnumerable<Structure> ParseStructuresFromGetStatusResult(string responseString, string userId) { var structureResults = new List<Structure>(); var values = JObject.Parse(responseString); var structures = values["user"][userId]["structures"]; foreach (var structure in structures) { string structureId = structure.Value<string>().Replace("structure.", ""); var structureModel = new Structure(structureId); structureModel.IsAway = values["structure"][structureId]["away"].Value<bool>(); structureResults.Add(structureModel); } int deviceCount = 0; foreach (var structureResult in structureResults) { var structure = values["structure"][structureResult.ID]; var devices = structure["devices"]; foreach (var device in devices) { deviceCount++; string thermostatId = device.Value<string>().Replace("device.", ""); var thermostat = new Thermostat(thermostatId); structureResult.Thermostats.Add(thermostat); } } foreach (var structureResult in structureResults) { foreach (var thermostat in structureResult.Thermostats) { var thermostatValues = values["device"][thermostat.ID]; thermostat.FanMode = GetFanModeFromString(thermostatValues["fan_mode"].Value<string>()); thermostat.IsLeafOn = thermostatValues["leaf"].Value<bool>(); TemperatureScale scale = GetTemperatureScaleFromString(thermostatValues["temperature_scale"].Value<string>()); thermostat.TemperatureScale = scale; thermostatValues = values["shared"][thermostat.ID]; double temperature = double.Parse(thermostatValues["target_temperature"].Value<string>()); thermostat.TargetTemperature = Math.Round(ConvertTo(scale, temperature)); double temperatureLow = double.Parse(thermostatValues["target_temperature_low"].Value<string>()); thermostat.TargetTemperatureLow = Math.Round(ConvertTo(scale, temperatureLow)); double temperatureHigh = double.Parse(thermostatValues["target_temperature_high"].Value<string>()); thermostat.TargetTemperatureHigh = Math.Round(ConvertTo(scale, temperatureHigh)); double currentTemperature = double.Parse(thermostatValues["current_temperature"].Value<string>()); thermostat.CurrentTemperature = Math.Round(ConvertTo(scale, currentTemperature)); thermostat.IsHeating = thermostatValues["hvac_heater_state"].Value<bool>(); thermostat.IsCooling = thermostatValues["hvac_ac_state"].Value<bool>(); thermostat.HvacMode = GetHvacModeFromString(thermostatValues["target_temperature_type"].Value<string>()); } } return structureResults; }
public void UpdateThermostatStatusFromSharedStatusResult(string strContent, Thermostat thermostatToUpdate) { var values = JObject.Parse(strContent); double temperatureCelsius = double.Parse(values["target_temperature"].Value<string>()); double temperatureLowCelsius = double.Parse(values["target_temperature_low"].Value<string>()); double temperatureHighCelsius = double.Parse(values["target_temperature_high"].Value<string>()); double currentTemperatureCelsius = double.Parse(values["current_temperature"].Value<string>()); TemperatureScale scale = thermostatToUpdate.TemperatureScale; thermostatToUpdate.CurrentTemperature = Math.Round(ConvertTo(scale, currentTemperatureCelsius)); thermostatToUpdate.TargetTemperature = Math.Round(ConvertTo(scale, temperatureCelsius)); thermostatToUpdate.TargetTemperatureLow = Math.Round(ConvertTo(scale, temperatureLowCelsius)); thermostatToUpdate.TargetTemperatureHigh = Math.Round(ConvertTo(scale, temperatureHighCelsius)); thermostatToUpdate.IsHeating = values["hvac_heater_state"].Value<bool>(); thermostatToUpdate.IsCooling = values["hvac_ac_state"].Value<bool>(); thermostatToUpdate.HvacMode = GetHvacModeFromString(values["target_temperature_type"].Value<string>()); }
public async Task <GetThermostatStatusResult> GetThermostatStatusAsync(Thermostat thermostat) { if (_sessionProvider.IsSessionExpired) { return(new GetThermostatStatusResult(WebServiceError.SessionTokenExpired, new SessionExpiredException())); } GetThermostatStatusResult result = await GetSharedThermostatPropertiesAsync(thermostat); if (result.Exception == null) { result = await GetDeviceThermostatPropertiesAsync(thermostat, result); } return(result); }
public void UpdateThermostatStatusFromSharedStatusResult(string strContent, Thermostat thermostatToUpdate) { var values = JObject.Parse(strContent); double temperatureCelsius = double.Parse(values["target_temperature"].Value <string>()); double temperatureLowCelsius = double.Parse(values["target_temperature_low"].Value <string>()); double temperatureHighCelsius = double.Parse(values["target_temperature_high"].Value <string>()); double currentTemperatureCelsius = double.Parse(values["current_temperature"].Value <string>()); TemperatureScale scale = thermostatToUpdate.TemperatureScale; thermostatToUpdate.CurrentTemperature = Math.Round(ConvertTo(scale, currentTemperatureCelsius)); thermostatToUpdate.TargetTemperature = Math.Round(ConvertTo(scale, temperatureCelsius)); thermostatToUpdate.TargetTemperatureLow = Math.Round(ConvertTo(scale, temperatureLowCelsius)); thermostatToUpdate.TargetTemperatureHigh = Math.Round(ConvertTo(scale, temperatureHighCelsius)); thermostatToUpdate.IsHeating = values["hvac_heater_state"].Value <bool>(); thermostatToUpdate.IsCooling = values["hvac_ac_state"].Value <bool>(); thermostatToUpdate.HvacMode = GetHvacModeFromString(values["target_temperature_type"].Value <string>()); }
private void SetThermostatTemperatureValue(TemperatureMode temperatureMode, Thermostat thermostat, double targetValue) { if (temperatureMode == TemperatureMode.RangeHigh) thermostat.TargetTemperatureHigh = targetValue; else if (temperatureMode == TemperatureMode.RangeLow) thermostat.TargetTemperatureLow = targetValue; else thermostat.TargetTemperature = targetValue; }
public void ShouldUpdateCurrentTemperatureCelcius() { var thermostat = new Thermostat("") {TemperatureScale = TemperatureScale.Celsius}; _deserializer.UpdateThermostatStatusFromSharedStatusResult(FakeJsonMessages.GetSharedStatusResult, thermostat); double expectedTemperature = Math.Round(21.89d); Assert.AreEqual(expectedTemperature, thermostat.CurrentTemperature); }
public async Task<WebServiceResult> SetFanModeAsync(Thermostat thermostat, FanMode fanMode) { string url = string.Format(@"{0}/v2/put/device.{1}", _sessionProvider.TransportUrl, thermostat.ID); string fanModeString = GetFanModeString(fanMode); string requestString = string.Format("{{\"fan_mode\":\"{0}\"}}", fanModeString); return await SendPutRequestAsync(url, requestString); }
public GetThermostatStatusResult(Thermostat thermostat) { Thermostat = thermostat; }
public async Task<WebServiceResult> ChangeTemperatureAsync(Thermostat thermostat, double desiredTemperature, TemperatureMode temperatureMode) { string temperatureProperty = GetTemperaturePropertyString(thermostat, desiredTemperature, temperatureMode); string url = string.Format(@"{0}/v2/put/shared.{1}", _sessionProvider.TransportUrl, thermostat.ID); string requestString = string.Format("{{\"target_change_pending\":true,{0}}}", temperatureProperty); return await SendPutRequestAsync(url, requestString); }
public async Task<WebServiceResult> SetHvacModeAsync(Thermostat thermostat, HvacMode hvacMode) { string url = string.Format(@"{0}/v2/put/shared.{1}", _sessionProvider.TransportUrl, thermostat.ID); string hvacModeString = _deserializer.GetHvacModeString(hvacMode); string requestString = string.Format("{{\"target_temperature_type\":\"{0}\"}}", hvacModeString); return await SendPutRequestAsync(url, requestString); }
public void ShouldUpdateHvacMode() { var structure = new Structure(""); var thermostat = new Thermostat(""){HvacMode = HvacMode.HeatAndCool}; structure.Thermostats.Add(thermostat); var status = new GetStatusResult(new[] {structure}); _statusProvider.Raise(provider => provider.StatusUpdated += null, new StatusEventArgs(status)); Assert.AreEqual(thermostat.HvacMode, _viewModel.HvacMode, "Expected HvacMode to update from status change."); }
public async Task ShouldUseCorrectUrl() { var thermostat = new Thermostat("id123"); await _webService.SetHvacModeAsync(thermostat, HvacMode.Off); var expectedUri = new Uri(BaseUrl + "/v2/put/shared.id123"); _requestProvider.Verify(r => r.CreateRequest(expectedUri)); }
public async Task ShouldSetContentTypeToJson() { var thermostat = new Thermostat("id123"); await _webService.SetHvacModeAsync(thermostat, HvacMode.Off); _webRequest.VerifySet(w => w.ContentType = ContentType.Json); }
public async Task ShouldSetNestHeadersOnRequest() { string userId = "userId"; _sessionProvider.SetupGet(s => s.UserId).Returns(userId); var thermostat = new Thermostat("id123"); await _webService.SetHvacModeAsync(thermostat, HvacMode.Off); _webHeaderCollection.VerifySet(w => w["X-nl-protocol-version"] = "1"); _webHeaderCollection.VerifySet(w => w["X-nl-user-id"] = userId); }
public void ShouldUpdateTargetTemperatureLow() { var thermostat = new Thermostat(""); _deserializer.UpdateThermostatStatusFromSharedStatusResult(FakeJsonMessages.GetSharedStatusResultTempRangeMode, thermostat); double expectedTemperature = Math.Round(20d.CelsiusToFahrenheit()); Assert.AreEqual(expectedTemperature, thermostat.TargetTemperatureLow); }
private static string GetTemperaturePropertyString(Thermostat thermostat, double desiredTemperature, TemperatureMode temperatureMode) { string temperatureTargetString = "\"target_temperature\":{0}"; string temperatureRangeString = "\"target_temperature_low\":{0},\"target_temperature_high\":{1}"; TemperatureScale scale = thermostat.TemperatureScale; double desiredTempCelsius = ConvertFrom(scale, desiredTemperature); string temperatureProperty = null; if (temperatureMode == TemperatureMode.RangeLow) { double highTempCelsius = ConvertFrom(scale, thermostat.TargetTemperatureHigh); temperatureProperty = string.Format(temperatureRangeString, desiredTempCelsius, highTempCelsius); } else if (temperatureMode == TemperatureMode.RangeHigh) { double lowTempCelsius = ConvertFrom(scale, thermostat.TargetTemperatureLow); temperatureProperty = string.Format(temperatureRangeString, lowTempCelsius, desiredTempCelsius); } else { temperatureProperty = string.Format(temperatureTargetString, desiredTempCelsius); } return temperatureProperty; }
public async Task<GetThermostatStatusResult> GetThermostatStatusAsync(Thermostat thermostat) { if (_sessionProvider.IsSessionExpired) return new GetThermostatStatusResult(WebServiceError.SessionTokenExpired, new SessionExpiredException()); GetThermostatStatusResult result = await GetSharedThermostatPropertiesAsync(thermostat); if (result.Exception == null) { result = await GetDeviceThermostatPropertiesAsync(thermostat, result); } return result; }
public void ShouldUpdateTargetTemperatureHighCelcius() { var thermostat = new Thermostat("") {TemperatureScale = TemperatureScale.Celsius}; _deserializer.UpdateThermostatStatusFromSharedStatusResult(FakeJsonMessages.GetSharedStatusResultTempRangeMode, thermostat); double expectedTemperature = Math.Round(24d); Assert.AreEqual(expectedTemperature, thermostat.TargetTemperatureHigh); }
public void ShouldUpdateIsLeafOn() { var structure = new Structure(""); var thermostat = new Thermostat("") {IsLeafOn = true}; structure.Thermostats.Add(thermostat); var status = new GetStatusResult(new[] {structure}); _statusProvider.Raise(provider => provider.StatusUpdated += null, new StatusEventArgs(status)); Assert.AreEqual(thermostat.IsLeafOn, _viewModel.IsLeafOn, "Expected IsLeafOn to update from status change."); }
public async Task ShouldSetHvacModeInRequestString() { _webServiceDeserializer.Setup(d => d.GetHvacModeString(It.IsAny<HvacMode>())).Returns("testing"); var thermostat = new Thermostat("id123"); await _webService.SetHvacModeAsync(thermostat, HvacMode.Off); string expectedString = "\"target_temperature_type\":\"testing\""; _webRequest.Verify(r=>r.SetRequestStringAsync(It.Is<string>(s => s.Contains(expectedString)))); }
private async Task<GetThermostatStatusResult> GetSharedThermostatPropertiesAsync(Thermostat thermostat) { string url = string.Format("{0}/v2/subscribe", _sessionProvider.TransportUrl); IWebRequest request = GetPostJsonRequest(url); SetAuthorizationHeaderOnRequest(request, _sessionProvider.AccessToken); SetNestHeadersOnRequest(request, _sessionProvider.UserId); string requestString = string.Format("{{\"keys\":[{{\"key\":\"shared.{0}\"}}]}}", thermostat.ID); await request.SetRequestStringAsync(requestString); Exception exception; try { IWebResponse response = await request.GetResponseAsync(); string strContent = await response.GetResponseStringAsync(); var updatedThermostat = new Thermostat(thermostat.ID); _deserializer.UpdateThermostatStatusFromSharedStatusResult(strContent, updatedThermostat); return new GetThermostatStatusResult(updatedThermostat); } catch (Exception ex) { exception = ex; } var error = await _deserializer.ParseWebServiceErrorAsync(exception); return new GetThermostatStatusResult(error, exception); }
public async Task ShouldSetAuthorizationHeaderOnRequest() { string accessToken = "token"; _sessionProvider.SetupGet(s => s.AccessToken).Returns(accessToken); var thermostat = new Thermostat("id123"); await _webService.SetHvacModeAsync(thermostat, HvacMode.Off); _webHeaderCollection.VerifySet(w => w["Authorization"] = "Basic " + accessToken); }
public async Task ShouldSetMethodToPost() { var thermostat = new Thermostat("id123"); await _webService.SetHvacModeAsync(thermostat, HvacMode.Off); _webRequest.VerifySet(w => w.Method = "POST"); }
public void ShouldUpdateHvacMode() { var thermostat = new Thermostat(""); _deserializer.UpdateThermostatStatusFromSharedStatusResult(FakeJsonMessages.GetSharedStatusResultTempRangeMode, thermostat); Assert.AreEqual(HvacMode.HeatAndCool, thermostat.HvacMode); }