コード例 #1
0
			public async Task ShouldAddKeyForStructure() {
				var structureId = "id";
				var structure = new Structure(structureId);
				await _webService.GetStructureAndDeviceStatusAsync(structure);

				_webRequest.Verify(w => w.SetRequestStringAsync(It.Is<string>(s => s.Contains("\"key\":\"structure.id\""))));
			}
コード例 #2
0
			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();
			}
コード例 #3
0
			public async Task ShouldUseCorrectUrl() {
				var structure = new Structure("id");
				await _webService.GetStructureAndDeviceStatusAsync(structure);
				var expectedUri = new Uri(BaseUrl + "/v2/subscribe");

				_requestProvider.Verify(r => r.CreateRequest(expectedUri));
			}
コード例 #4
0
		public Structure ParseStructureFromGetStructureStatusResult(string result, string structureId) {
			var structure = new Structure(structureId);
			var values = JObject.Parse(result);
			structure.IsAway = values["away"].Value<bool>();

			return structure;
		}
コード例 #5
0
		private async Task UpdateStatusAsync(Structure structure) {
			GetStatusResult result = await _nestWebService.GetStructureAndDeviceStatusAsync(structure);
			if (result.Exception != null)
				Stop();

			_delayedStatusProvider.CacheStatus(result);
		}
コード例 #6
0
        public void ShouldPassCurrentStructureToWebServiceForStatus()
        {
            var expectedStructure = new Structure("id");
            _updaterService.CurrentStructure = expectedStructure;

            _timerCallback(null);

            _mockWebService.Verify(w=>w.GetStructureAndDeviceStatusAsync(expectedStructure));
        }
コード例 #7
0
			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.");
			}
コード例 #8
0
			public void TearDown() {
				_statusProvider = null;
				_sessionProvider = null;
				_analyticsService = null;
				_nestWebService = null;
				_statusUpdaterService = null;
				_viewModel = null;
				_structure = null;
				_firstThermostat = null;
				_secondThermostat = null;
			}
コード例 #9
0
		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;
		}
コード例 #10
0
ファイル: NestWebService.cs プロジェクト: garyjohnson/wpnest
		public async Task<GetStatusResult> GetStructureAndDeviceStatusAsync(Structure structure) {
			var structureResult = await GetStructureStatusAsync(structure);
			if (structureResult.Exception != null)
				return structureResult;

			foreach (var thermostat in structure.Thermostats) {
				GetThermostatStatusResult sharedResult = await GetSharedThermostatPropertiesAsync(thermostat);
				if (sharedResult.Exception != null)
					return new GetStatusResult(sharedResult.Error, sharedResult.Exception);
				GetThermostatStatusResult thermostatResult = await GetDeviceThermostatPropertiesAsync(thermostat, sharedResult);
				if (thermostatResult.Exception != null)
					return new GetStatusResult(thermostatResult.Error, thermostatResult.Exception);

				structureResult.Structures.ElementAt(0).Thermostats.Add(sharedResult.Thermostat);
			}
			return structureResult;
		}
コード例 #11
0
ファイル: NestWebService.cs プロジェクト: garyjohnson/wpnest
		private async Task<GetStatusResult> GetStructureStatusAsync(Structure structure) {
			string url = string.Format("{0}/v2/subscribe", _sessionProvider.TransportUrl);
			var request = GetPostJsonRequest(url);

			SetAuthorizationHeaderOnRequest(request, _sessionProvider.AccessToken);
			SetNestHeadersOnRequest(request, _sessionProvider.UserId);

			string requestString = string.Format("{{\"keys\":[{{\"key\":\"structure.{0}\"}}]}}", structure.ID);
			await request.SetRequestStringAsync(requestString);
			Exception exception;

			try {
				IWebResponse response = await request.GetResponseAsync();
				string responseString = await response.GetResponseStringAsync();
				Structure parsedStructure = _deserializer.ParseStructureFromGetStructureStatusResult(responseString, structure.ID);
				return new GetStatusResult(new[] {parsedStructure});
			}
			catch (Exception ex) {
				exception = ex;
			}

			var error = await _deserializer.ParseWebServiceErrorAsync(exception);
			return new GetStatusResult(error, exception);
		}
コード例 #12
0
			public async Task ShouldAddSharedKeysForThermostats() {
				string thermostatId1 = "12345";
				string thermostatId2 = "54321";
				var structure = new Structure("id");
				structure.Thermostats.Add(new Thermostat(thermostatId1));
				structure.Thermostats.Add(new Thermostat(thermostatId2));
				await _webService.GetStructureAndDeviceStatusAsync(structure);

				string expectedKey1 = string.Format("\"key\":\"shared.{0}\"", thermostatId1);
				string expectedKey2 = string.Format("\"key\":\"shared.{0}\"", thermostatId2);
				_webRequest.Verify(w => w.SetRequestStringAsync(It.Is<string>(s => s.Contains(expectedKey1))), Times.Once());
				_webRequest.Verify(w => w.SetRequestStringAsync(It.Is<string>(s => s.Contains(expectedKey2))), Times.Once());
			}
コード例 #13
0
ファイル: NestWebService.cs プロジェクト: garyjohnson/wpnest
		public async Task<WebServiceResult> SetAwayMode(Structure structure, bool isAway) {
			string url = string.Format(@"{0}/v2/put/structure.{1}", _sessionProvider.TransportUrl, structure.ID);
			string requestString = string.Format("{{\"away_timestamp\":{0},\"away\":{1},\"away_setter\":0}}", 
				_timestampProvider.GetTimestamp(), isAway.ToString().ToLower());
			return await SendPutRequestAsync(url, requestString);
		}
コード例 #14
0
			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.");
			}
コード例 #15
0
			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.");
			}
コード例 #16
0
			public async Task ShouldUseCorrectUrl() {
				var structure = new Structure("id123");
				await _webService.SetAwayMode(structure, true);

				var expectedUri = new Uri(BaseUrl + "/v2/put/structure.id123");
				_requestProvider.Verify(r => r.CreateRequest(expectedUri));
			}
コード例 #17
0
			public async Task ShouldStopGettingDeviceStatusIfSharedStatusFails() {
				_webRequest.SetupSequence(r => r.GetResponseAsync())
				           .Returns(Task.FromResult(_webResponse.Object))
				           .Throws(new Exception());
				_webServiceDeserializer.Setup(d => d.ParseWebServiceErrorAsync(It.IsAny<Exception>())).Returns(Task.FromResult(WebServiceError.SessionTokenExpired));

				string firstThermostatId = "12345";
				var structure = new Structure("id");
				structure.Thermostats.Add(new Thermostat(firstThermostatId));
				structure.Thermostats.Add(new Thermostat("id"));
				await _webService.GetStructureAndDeviceStatusAsync(structure);

				string expectedKey = string.Format("\"key\":\"device.{0}\"", firstThermostatId);
				_webRequest.Verify(w => w.SetRequestStringAsync(It.Is<string>(s => s.Contains(expectedKey))), Times.Never());
			}
コード例 #18
0
			public async Task ShouldUseFanModeFromDeserializer() {
				var expectedFanMode = FanMode.On;
				_webServiceDeserializer.Setup(d => d.ParseFanModeFromDeviceSubscribeResult(It.IsAny<string>()))
				                       .Returns(expectedFanMode);
				_webResponse.SetupSequence(w => w.GetResponseStringAsync())
				            .Returns(Task.FromResult(FakeJsonMessages.GetStructureStatusResult))
				            .Returns(Task.FromResult(FakeJsonMessages.GetDeviceStatusResult));

				var structure = new Structure("");
				structure.Thermostats.Add(new Thermostat(""));
				GetStatusResult result = await _webService.GetStructureAndDeviceStatusAsync(structure);
				Assert.AreEqual(expectedFanMode, result.Structures.ElementAt(0).Thermostats[0].FanMode);
			}
コード例 #19
0
			public async Task ShouldGetLeafFromDeserializer() {
				_webResponse.SetupSequence(w => w.GetResponseStringAsync())
				            .Returns(Task.FromResult(FakeJsonMessages.GetStructureStatusResult))
				            .Returns(Task.FromResult(FakeJsonMessages.GetSharedStatusResult))
				            .Returns(Task.FromResult(FakeJsonMessages.GetDeviceStatusResult));

				var structure = new Structure("");
				structure.Thermostats.Add(new Thermostat(""));
				await _webService.GetStructureAndDeviceStatusAsync(structure);

				_webServiceDeserializer.Verify(d => d.ParseLeafFromDeviceSubscribeResult(FakeJsonMessages.GetDeviceStatusResult));
			}
コード例 #20
0
			public async Task ShouldAddDeviceKeyForThermostats() {
				string thermostatId = "12345";
				var structure = new Structure("id");
				structure.Thermostats.Add(new Thermostat(thermostatId));
				await _webService.GetStructureAndDeviceStatusAsync(structure);

				string expectedKey = string.Format("\"key\":\"device.{0}\"", thermostatId);
				_webRequest.Verify(w => w.SetRequestStringAsync(It.Is<string>(s => s.Contains(expectedKey))));
			}
コード例 #21
0
			public async Task ShouldReturnStructureFromDeserializer() {
				var expectedStructure = new Structure("structureId");
				_webServiceDeserializer.Setup(d => d.ParseStructureFromGetStructureStatusResult(It.IsAny<string>(), It.IsAny<string>())).Returns(expectedStructure);

				GetStatusResult result = await _webService.GetStructureAndDeviceStatusAsync(new Structure(""));

				Assert.AreEqual(expectedStructure, result.Structures.ElementAt(0));
			}