/// <summary> /// Builds forecast page model for given app-chain job IDs and location /// </summary> /// <param name="jobId"></param> /// <param name="jobId2"></param> /// <param name="city"></param> /// <returns></returns> public RunResult Build(string jobId, string jobId2, string city) { mode = service.GetInfo(userName).Temperature ?? TemperatureMode.F; var _weatherWorker = new WeatherWorker(userName); var _forecastRoot = _weatherWorker.GetForecast10(city); var _runResult = new RunResult { Weather = _forecastRoot.current_observation.weather + " " + (mode == TemperatureMode.F ? _forecastRoot.current_observation.temp_f + "F" : _forecastRoot.current_observation.temp_c + "C"), Forecast = _forecastRoot, CurrentWeather = _forecastRoot.current_observation }; var _appChainResults = GetAppChainResultingRisks(jobId, jobId2); if (_forecastRoot != null) { var _alertCode = _forecastRoot.alerts.Count == 0 ? "--" : _forecastRoot.alerts[0].type; var _riskDescription = GetPersonalizedRiskDescription(_forecastRoot.forecast.simpleforecast.forecastday[0].conditions, _alertCode, _appChainResults, userName, Options.ApplicationName); _runResult.Risk = _riskDescription; _runResult.RawRisk = _appChainResults.MelanomaAppChainResult.ToString(); _runResult.Temperature = mode; _runResult.JobDateTime = _appChainResults.AppChainRunDt; } return _runResult; }
public ActionResult ChangeNotification(bool emailChk, bool smsChk, string email, string phone, string wakeupDay, string wakeupEnd, string timezoneSelect, string timezoneOffset, WeekEndMode weekendMode, TemperatureMode temperature, string countryCode) { SendInfo info = new SendInfo() { UserName = User.Identity.Name, SendEmail = emailChk, SendSms = smsChk, UserEmail = email, UserPhone = phone, TimeWeekDay = wakeupDay, TimeWeekEnd = wakeupEnd, TimeZoneValue = timezoneSelect, WeekendMode = weekendMode, Temperature = temperature, CountryCode = countryCode }; if (!string.IsNullOrEmpty(timezoneOffset)) { info.TimeZoneOffset = settingService.ParseTimeZoneOffset(timezoneOffset); } settingService.UpdateUserSettings(info); return(RedirectToAction("GoToResults", "Default")); }
/// <summary> /// Builds forecast page model for given app-chain job IDs and location /// </summary> /// <param name="jobId"></param> /// <param name="jobId2"></param> /// <param name="city"></param> /// <returns></returns> public RunResult Build(string jobId, string jobId2, string city) { mode = service.GetInfo(userName).Temperature ?? TemperatureMode.F; var _weatherWorker = new WeatherWorker(userName); var _forecastRoot = _weatherWorker.GetForecast10(city); var _runResult = new RunResult { Weather = _forecastRoot.current_observation.weather + " " + (mode == TemperatureMode.F ? _forecastRoot.current_observation.temp_f + "F" : _forecastRoot.current_observation.temp_c + "C"), Forecast = _forecastRoot, CurrentWeather = _forecastRoot.current_observation }; var _appChainResults = GetAppChainResultingRisks(jobId, jobId2); if (_forecastRoot != null) { var _alertCode = _forecastRoot.alerts.Count == 0 ? "--" : _forecastRoot.alerts[0].type; var _riskDescription = GetPersonalizedRiskDescription(_forecastRoot.forecast.simpleforecast.forecastday[0].conditions, _alertCode, _appChainResults, userName, Options.ApplicationName); _runResult.Risk = _riskDescription; _runResult.RawRisk = _appChainResults.MelanomaAppChainResult.ToString(); _runResult.Temperature = mode; _runResult.JobDateTime = _appChainResults.AppChainRunDt; } return(_runResult); }
private async Task RaiseTemperatureAsync(TemperatureMode temperatureMode) { double temperature = GetTemperatureValue(temperatureMode); if (temperature >= MaxTemperature) { return; } await PauseStatusProviderWhile(async() => { var thermostat = GetFirstThermostat(); double desiredTemperature = temperature + 1.0d; SetTemperatureValue(temperatureMode, desiredTemperature); SetThermostatTemperatureValue(temperatureMode, thermostat, desiredTemperature); var result = await _nestWebService.ChangeTemperatureAsync(thermostat, desiredTemperature, temperatureMode); if (IsErrorHandled(result.Error, result.Exception)) { return; } await _statusUpdater.UpdateStatusAsync(); }); }
private void SendEmailNotification(SendInfo _info, string _city, string _todayForecast, string _currentObservation, string _riskDescription, Forecast10Root _forecastRoot, TemperatureMode _mode, MandrillApi _api, string _subj) { var _sb = new StringBuilder(); _sb.Append("<p style='text-align:center'>") .AppendFormat( "Genetically tailored notification from your <a href='{0}' class='external'>Weather My Way +RTP</a> app", Options.BaseSiteUrl) .Append("</p>"); _sb.Append("<p style='text-align:center'><strong>"); _sb.AppendFormat("Current weather for {0}", _city).Append("</strong></p>"); _sb.Append("<p style='text-align:center'>"); _sb.Append(_currentObservation).Append("</p><br/>"); _sb.Append("<p style='text-align:center'>"); _sb.Append("<strong>Today's forecast</strong>").Append("</p>"); _sb.Append("<p style='text-align:center'>"); _sb.Append(_todayForecast).Append("</p><br/>"); _sb.Append("<p style='text-align:center'>"); _sb.Append("<strong>Your genetically tailored forecast</strong>").Append("</p>"); _sb.Append("<p style='text-align:center'>"); _sb.Append(_riskDescription).Append("</p><br/>"); _sb.Append("<p style='text-align:center'><strong>Extended forecast</strong></p>"); for (int _idx = 1; _idx < Math.Min(5, _forecastRoot.forecast.txt_forecast.forecastday.Count); _idx++) { _sb.Append("<p style='text-align:center'>"); _sb.Append(_forecastRoot.forecast.txt_forecast.forecastday[_idx].title).Append(":"); _sb.Append(_mode == TemperatureMode.F ? _forecastRoot.forecast.txt_forecast.forecastday[_idx].fcttext : _forecastRoot.forecast.txt_forecast.forecastday[_idx].fcttext_metric).Append("</p>"); } SendEmail(_api, _info, _subj, _sb.ToString()); }
public ActionResult ChangeNotification(bool emailChk, bool smsChk, string email, string phone, string wakeupDay, string wakeupEnd, string timezoneSelect, string timezoneOffset, WeekEndMode weekendMode, TemperatureMode temperature, string countryCode) { SendInfo info = new SendInfo() { UserName = User.Identity.Name, SendEmail = emailChk, SendSms = smsChk, UserEmail = email, UserPhone = phone, TimeWeekDay = wakeupDay, TimeWeekEnd = wakeupEnd, TimeZoneValue = timezoneSelect, WeekendMode = weekendMode, Temperature = temperature, CountryCode = countryCode }; if (!string.IsNullOrEmpty(timezoneOffset)) info.TimeZoneOffset = settingService.ParseTimeZoneOffset(timezoneOffset); settingService.UpdateUserSettings(info); return RedirectToAction("GoToResults", "Default"); }
public async Task LowerTemperatureAsync(TemperatureMode temperatureMode) { double temperature = GetTemperatureValue(temperatureMode); if (temperature <= MinTemperature) { return; } try { _statusProvider.Stop(); var thermostat = GetFirstThermostat(); double desiredTemperature = temperature - 1.0d; SetTemperatureValue(temperatureMode, desiredTemperature); SetThermostatTemperatureValue(temperatureMode, thermostat, desiredTemperature); var result = await _nestWebService.ChangeTemperatureAsync(thermostat, desiredTemperature, temperatureMode); if (_exceptionHandler.IsErrorHandled(result.Error, result.Exception)) { return; } await _statusUpdater.UpdateStatusAsync(); } finally { _statusProvider.Start(); } }
// Doesn't seem to work! Use SetTempUnitAndColor instead! // public void SetTempUnit(TemperatureMode mode) // { // byte f = mode==TemperatureMode.Fahrenheit ? (byte)0x01 : (byte)0x00; // var payload = new byte[] { 0x09, 0x00, 0x45, 0x01, f, 0x00 }; // var message = BuildMessage(payload); // _client.GetStream().Write(message, 0, message.Length); // } public void SetTempUnitAndColor(Color color, TemperatureMode mode = TemperatureMode.Celsius) { byte f = (mode == TemperatureMode.Fahrenheit) ? (byte)0x01 : (byte)0x00; var payload = new byte[] { 0x09, 0x00, 0x45, 0x01, f, color.R, color.G, color.B, 0x00 }; var message = BuildMessage(payload); _client.GetStream().Write(message, 0, message.Length); }
public JsonResult ChangeNotification(bool emailChk, bool smsChk, string email, string phone, string wakeupDay, string wakeupEnd, string timezoneSelect, string timezoneOffset, WeekEndMode weekendMode, TemperatureMode temperature, string token, string countryCode) { GenericResponse responseObj = null; int timeStart = DateTime.Now.TimeOfDay.Seconds; try { string name = oauthFactory.GetOAuthTokenDao().getUser(token).username; if (name != null) { SendInfo info = new SendInfo() { UserName = name, SendEmail = emailChk, SendSms = smsChk, UserEmail = email, UserPhone = phone, TimeWeekDay = wakeupDay, TimeWeekEnd = wakeupEnd, TimeZoneValue = timezoneSelect, WeekendMode = weekendMode, Temperature = temperature, CountryCode = countryCode, }; if (!string.IsNullOrEmpty(timezoneOffset)) info.TimeZoneOffset = settingsService.ParseTimeZoneOffset(timezoneOffset); settingsService.UpdateUserSettings(info); } responseObj = new GenericResponse() { Status = 0, ResponseTime = DateTime.Now.TimeOfDay.Seconds - timeStart, Message = "Settings successfully updated for user: "+ name, Data = null, }; return Json(responseObj, JsonRequestBehavior.AllowGet); } catch (Exception e) { responseObj = new GenericResponse() { Status = 1, ResponseTime = DateTime.Now.TimeOfDay.Milliseconds - timeStart, Message = e.Message, Data = null, }; ResponseLogging(responseObj); return Json(responseObj, JsonRequestBehavior.AllowGet); } }
private void SetTemperatureValue(TemperatureMode temperatureMode, double targetValue) { if (temperatureMode == TemperatureMode.RangeHigh) { TargetTemperatureHigh = targetValue; } else if (temperatureMode == TemperatureMode.RangeLow) { TargetTemperatureLow = targetValue; } else { TargetTemperature = targetValue; } }
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; } }
private double GetTemperatureValue(TemperatureMode temperatureMode) { double temperatureValue = TargetTemperature; if (temperatureMode == TemperatureMode.RangeHigh) { temperatureValue = TargetTemperatureHigh; } else if (temperatureMode == TemperatureMode.RangeLow) { temperatureValue = TargetTemperatureLow; } return(temperatureValue); }
public Temperature(TemperatureMode mode, double value) { DefaultMode = mode; Value = new Dictionary <TemperatureMode, double>(); switch (mode) { case TemperatureMode.Celsius: Value[TemperatureMode.Celsius] = value; break; case TemperatureMode.Farenhait: Value[TemperatureMode.Celsius] = (value - 32.0) / 1.8; break; case TemperatureMode.Kelvin: Value[TemperatureMode.Celsius] = value - 273.15; break; } Value[TemperatureMode.Kelvin] = Value[TemperatureMode.Celsius] + 273.15; Value[TemperatureMode.Farenhait] = Value[TemperatureMode.Celsius] * 1.8 + 32; }
public async Task LowerTemperatureAsync(TemperatureMode temperatureMode) { double temperature = GetTemperatureValue(temperatureMode); if (temperature <= MinTemperature) return; await PauseStatusProviderWhile(async () => { var thermostat = GetFirstThermostat(); double desiredTemperature = temperature - 1.0d; SetTemperatureValue(temperatureMode, desiredTemperature); SetThermostatTemperatureValue(temperatureMode, thermostat, desiredTemperature); var result = await _nestWebService.ChangeTemperatureAsync(thermostat, desiredTemperature, temperatureMode); if (IsErrorHandled(result.Error, result.Exception)) return; await _statusUpdater.UpdateStatusAsync(); }); }
/// <summary> /// Initializes a new instance of the <see cref="MonoBrick.NXT.RCXTemperatureSensor"/> class. /// </summary> /// <param name='temperatureMode'> /// Temperature mode /// </param> public RCXTemperatureSensor(TemperatureMode temperatureMode) : base(SensorType.Temperature, (SensorMode)temperatureMode) { }
public JsonResult ChangeNotification(bool emailChk, bool smsChk, string email, string phone, string wakeupDay, string wakeupEnd, string timezoneSelect, string timezoneOffset, WeekEndMode weekendMode, TemperatureMode temperature, string token, string countryCode) { GenericResponse responseObj = null; int timeStart = DateTime.Now.TimeOfDay.Seconds; try { string name = oauthFactory.GetOAuthTokenDao().getUser(token).username; if (name != null) { SendInfo info = new SendInfo() { UserName = name, SendEmail = emailChk, SendSms = smsChk, UserEmail = email, UserPhone = phone, TimeWeekDay = wakeupDay, TimeWeekEnd = wakeupEnd, TimeZoneValue = timezoneSelect, WeekendMode = weekendMode, Temperature = temperature, CountryCode = countryCode, }; if (!string.IsNullOrEmpty(timezoneOffset)) { info.TimeZoneOffset = settingsService.ParseTimeZoneOffset(timezoneOffset); } settingsService.UpdateUserSettings(info); } responseObj = new GenericResponse() { Status = 0, ResponseTime = DateTime.Now.TimeOfDay.Seconds - timeStart, Message = "Settings successfully updated for user: " + name, Data = null, }; return(Json(responseObj, JsonRequestBehavior.AllowGet)); } catch (Exception e) { responseObj = new GenericResponse() { Status = 1, ResponseTime = DateTime.Now.TimeOfDay.Milliseconds - timeStart, Message = e.Message, Data = null, }; ResponseLogging(responseObj); return(Json(responseObj, JsonRequestBehavior.AllowGet)); } }
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); }
private void SetTemperatureValue(TemperatureMode temperatureMode, double targetValue) { if (temperatureMode == TemperatureMode.RangeHigh) TargetTemperatureHigh = targetValue; else if (temperatureMode == TemperatureMode.RangeLow) TargetTemperatureLow = targetValue; else TargetTemperature = targetValue; }
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); }
private void ProcessDeviceStateQueryRequest(QueryRequestType requestType, QueryRequest alexaRequest, QueryResponse response) { IPremiseObject applianceToQuery; InformLastContact("QueryRequest:" + alexaRequest.payload.appliance.additionalApplianceDetails.path).GetAwaiter().GetResult(); try { // Find the object Guid premiseId = new Guid(alexaRequest.payload.appliance.applianceId); applianceToQuery = PremiseServer.RootObject.GetObject(premiseId.ToString("B")).GetAwaiter().GetResult(); if (applianceToQuery == null) { throw new Exception(); } switch (requestType) { /* * case QueryRequestType.PowerState: * string state = applianceToQuery.GetValue("PowerState").GetAwaiter().GetResult(); * break; * * case QueryRequestType.DimmerLevel: * string state = applianceToQuery.GetValue("Brightness").GetAwaiter().GetResult(); * break; * * case QueryRequestType.ColorTemperature: * string state = applianceToQuery.GetValue("ColorTemperature").GetAwaiter().GetResult(); * break; * * case QueryRequestType.Color: * string state = applianceToQuery.GetValue("Hue").GetAwaiter().GetResult(); * break; */ case QueryRequestType.RetrieveCameraStreamUri: { response.payload.uri = new ApplianceValue(); string host = applianceToQuery.GetValue <string>("Host").GetAwaiter().GetResult(); string port = applianceToQuery.GetValue <string>("Port").GetAwaiter().GetResult(); string path = applianceToQuery.GetValue <string>("Path").GetAwaiter().GetResult(); response.payload.uri.value = string.Format(@"rtsp://{0}:{1}{2}", host, port, path); } break; case QueryRequestType.GetTargetTemperature: Temperature coolingSetPoint = new Temperature(applianceToQuery.GetValue <double>("CoolingSetPoint").GetAwaiter().GetResult()); Temperature heatingSetPoint = new Temperature(applianceToQuery.GetValue <double>("HeatingSetPoint").GetAwaiter().GetResult()); int temperatureMode = applianceToQuery.GetValue <int>("TemperatureMode").GetAwaiter().GetResult(); response.payload.temperatureMode = new ApplianceTemperatureMode { value = TemperatureMode.ModeToString(temperatureMode) }; response.payload.heatingTargetTemperature = new ApplianceTemperatureReading { value = double.Parse(string.Format("{0:N2}", heatingSetPoint.Celcius)), scale = "CELSIUS" }; response.payload.coolingTargetTemperature = new ApplianceTemperatureReading { value = double.Parse(string.Format("{0:N2}", coolingSetPoint.Celcius)), scale = "CELSIUS" }; //response.payload.applianceResponseTimestamp = DateTime.UtcNow.ToUniversalTime().ToString("yyyy-MM-dd'T'HH:mm:ss.ffZ");// XmlConvert.ToString(DateTime.UtcNow.ToUniversalTime(), XmlDateTimeSerializationMode.Utc); break; case QueryRequestType.GetTemperatureReading: Temperature temperature = new Temperature(applianceToQuery.GetValue <double>("Temperature").GetAwaiter().GetResult()); response.payload.temperatureReading = new ApplianceTemperatureReading { value = double.Parse(string.Format("{0:N2}", temperature.Celcius)), scale = "CELSIUS" }; //response.payload.applianceResponseTimestamp = DateTime.UtcNow.ToUniversalTime().ToString("yyyy-MM-dd'T'HH:mm:ss.ffZ"); //XmlConvert.ToString(DateTime.UtcNow.ToUniversalTime(), XmlDateTimeSerializationMode.Utc); break; default: response.header.@namespace = Faults.QueryNamespace; response.header.name = Faults.UnsupportedOperationError; response.payload.exception = new ExceptionResponsePayload { errorInfo = new ErrorInfo { description = "Unsupported Query Request Type" } }; break; } } catch { response.header.@namespace = Faults.QueryNamespace; response.header.name = Faults.NoSuchTargetError; response.payload.exception = new ExceptionResponsePayload(); } }
private double GetTemperatureValue(TemperatureMode temperatureMode) { double temperatureValue = TargetTemperature; if (temperatureMode == TemperatureMode.RangeHigh) temperatureValue = TargetTemperatureHigh; else if (temperatureMode == TemperatureMode.RangeLow) temperatureValue = TargetTemperatureLow; return temperatureValue; }
public PersonalizedForecastResultBuilder(string userName, TemperatureMode mode) { this.userName = userName; this.mode = mode; }
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; }
/// <summary> /// Returning value as concrete <see cref="TemperatureMode"/>. /// </summary> /// <param name="mode"></param> /// <returns></returns> public double Get(TemperatureMode mode) { return(System.Math.Round(Value[mode], 0)); }
/// <summary> /// Initializes a new instance of the <see cref="MonoBrick.EV3.TemperatureSensor"/> class. /// </summary> /// <param name="mode">Mode.</param> public TemperatureSensor(TemperatureMode mode) : base((SensorMode)mode) { }
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)); }
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 ControlResponse Control(ControlRequest alexaRequest) { //IPremiseObject PremiseServer.HomeObject, rootObject; var response = new ControlResponse(); #region CheckRequest if ((alexaRequest == null) || (alexaRequest.header == null) || (alexaRequest.header.payloadVersion != "2")) { response.header.@namespace = Faults.Namespace; response.header.name = Faults.UnexpectedInformationReceivedError; response.payload.exception = new ExceptionResponsePayload { faultingParameter = "alexaRequest" }; return(response); } #endregion CheckRequest #region BuildResponse try { response.header.messageId = alexaRequest.header.messageId; response.header.@namespace = alexaRequest.header.@namespace; response.header.name = alexaRequest.header.name.Replace("Request", "Confirmation"); } catch (Exception) { response.header.@namespace = Faults.Namespace; response.header.name = Faults.UnexpectedInformationReceivedError; response.payload.exception = new ExceptionResponsePayload { faultingParameter = "alexaRequest.header.name" }; return(response); } #endregion BuildResponse //SYSClient client = new SYSClient(); #region ConnectToPremise if (PremiseServer.HomeObject == null) { response.header.@namespace = Faults.Namespace; response.header.name = Faults.DependentServiceUnavailableError; response.payload.exception = new ExceptionResponsePayload { dependentServiceName = "Premise Server" }; return(response); } #endregion ConnectToPremise try { if (!CheckAccessToken(alexaRequest.payload.accessToken).GetAwaiter().GetResult()) { response.header.@namespace = Faults.Namespace; response.header.name = Faults.InvalidAccessTokenError; response.payload.exception = new ExceptionResponsePayload(); return(response); } InformLastContact("ControlRequest:" + alexaRequest.payload.appliance.additionalApplianceDetails.path).GetAwaiter().GetResult(); // check request types ControlRequestType requestType = ControlRequestType.Unknown; DeviceType deviceType = DeviceType.Unknown; string command = alexaRequest.header.name.Trim().ToUpper(); switch (command) { case "TURNOFFREQUEST": requestType = ControlRequestType.TurnOffRequest; deviceType = DeviceType.OnOff; break; case "TURNONREQUEST": requestType = ControlRequestType.TurnOnRequest; deviceType = DeviceType.OnOff; break; case "SETTARGETTEMPERATUREREQUEST": requestType = ControlRequestType.SetTargetTemperature; deviceType = DeviceType.Thermostat; break; case "INCREMENTTARGETTEMPERATUREREQUEST": requestType = ControlRequestType.IncrementTargetTemperature; deviceType = DeviceType.Thermostat; break; case "DECREMENTTARGETTEMPERATUREREQUEST": requestType = ControlRequestType.DecrementTargetTemperature; deviceType = DeviceType.Thermostat; break; case "SETPERCENTAGEREQUEST": requestType = ControlRequestType.SetPercentage; deviceType = DeviceType.Dimmer; break; case "INCREMENTPERCENTAGEREQUEST": requestType = ControlRequestType.IncrementPercentage; deviceType = DeviceType.Dimmer; break; case "DECREMENTPERCENTAGEREQUEST": requestType = ControlRequestType.DecrementPercentage; deviceType = DeviceType.Dimmer; break; case "SETCOLORREQUEST": requestType = ControlRequestType.SetColorRequest; deviceType = DeviceType.ColorLight; break; case "SETCOLORTEMPERATUREREQUEST": requestType = ControlRequestType.SetColorTemperatureRequest; deviceType = DeviceType.ColorLight; break; case "INCREMENTCOLORTEMPERATUREREQUEST": requestType = ControlRequestType.IncrementColorTemperature; deviceType = DeviceType.ColorLight; break; case "DECREMENTCOLORTEMPERATUREREQUEST": requestType = ControlRequestType.DecrementColorTemperature; deviceType = DeviceType.ColorLight; break; default: response.header.@namespace = Faults.Namespace; response.header.name = Faults.UnsupportedOperationError; response.payload.exception = new ExceptionResponsePayload(); return(response); } // get the object IPremiseObject applianceToControl = null; try { Guid premiseId = new Guid(alexaRequest.payload.appliance.applianceId); applianceToControl = PremiseServer.RootObject.GetObject(premiseId.ToString("B")).GetAwaiter().GetResult(); if (applianceToControl == null) { throw new Exception(); } } catch { response.header.@namespace = Faults.Namespace; response.header.name = Faults.NoSuchTargetError; response.payload.exception = new ExceptionResponsePayload(); return(response); } if (deviceType == DeviceType.OnOff) { switch (requestType) { case ControlRequestType.TurnOnRequest: applianceToControl.SetValue("PowerState", "True").GetAwaiter().GetResult(); break; case ControlRequestType.TurnOffRequest: applianceToControl.SetValue("PowerState", "False").GetAwaiter().GetResult(); break; default: break; } } else if (deviceType == DeviceType.Dimmer) { double currentValue = 0.0; double adjustValue = 0.0; double valueToSend = 0.0; switch (requestType) { case ControlRequestType.SetPercentage: // obtain the adjustValue adjustValue = Math.Round(double.Parse(alexaRequest.payload.percentageState.value), 2).LimitToRange(0.00, 100.00); // convert from percentage and maintain fractional accuracy valueToSend = Math.Round(adjustValue / 100.00, 4); applianceToControl.SetValue("Brightness", valueToSend.ToString()).GetAwaiter().GetResult(); break; case ControlRequestType.IncrementPercentage: // obtain the adjustValue adjustValue = Math.Round(double.Parse(alexaRequest.payload.deltaPercentage.value) / 100.00, 2).LimitToRange(0.00, 100.00); currentValue = Math.Round(applianceToControl.GetValue <Double>("Brightness").GetAwaiter().GetResult(), 2); // maintain fractional accuracy valueToSend = Math.Round(currentValue + adjustValue, 2).LimitToRange(0.00, 1.00); applianceToControl.SetValue("Brightness", valueToSend.ToString()).GetAwaiter().GetResult(); break; case ControlRequestType.DecrementPercentage: // obtain the adjustValue adjustValue = Math.Round(double.Parse(alexaRequest.payload.deltaPercentage.value) / 100.00, 2).LimitToRange(0.00, 100.00); currentValue = Math.Round(applianceToControl.GetValue <Double>("Brightness").GetAwaiter().GetResult(), 2); // maintain fractional accuracy valueToSend = Math.Round(currentValue - adjustValue, 2).LimitToRange(0.00, 1.00); applianceToControl.SetValue("Brightness", valueToSend.ToString()).GetAwaiter().GetResult(); break; default: break; } } else if (deviceType == DeviceType.ColorLight) { const double adjustValue = 100.0; double currentValue = 0.0; double valueToSend = 0.0; response.payload.achievedState = new AchievedState(); switch (requestType) { case ControlRequestType.SetColorRequest: // obtain the adjustValue double hue = Math.Round(alexaRequest.payload.color.hue.LimitToRange(0, 360), 1); double saturation = Math.Round(alexaRequest.payload.color.saturation, 4); double brightness = Math.Round(alexaRequest.payload.color.brightness, 4); // set the values applianceToControl.SetValue("Hue", hue.ToString()).GetAwaiter().GetResult(); applianceToControl.SetValue("Saturation", saturation.ToString()).GetAwaiter().GetResult(); applianceToControl.SetValue("Brightness", brightness.ToString()).GetAwaiter().GetResult(); // read them back for achieved state response.payload.achievedState.color = new ApplianceColorValue { hue = Math.Round(applianceToControl.GetValue <Double>("Hue").GetAwaiter().GetResult(), 1), saturation = Math.Round(applianceToControl.GetValue <Double>("Saturation").GetAwaiter().GetResult(), 4), brightness = Math.Round(applianceToControl.GetValue <Double>("Brightness").GetAwaiter().GetResult(), 4) }; break; case ControlRequestType.SetColorTemperatureRequest: valueToSend = alexaRequest.payload.colorTemperature.value.LimitToRange(1000, 10000); // set the value applianceToControl.SetValue("Temperature", Math.Round(valueToSend, 0).ToString()).GetAwaiter().GetResult(); // read it back response.payload.achievedState.colorTemperature = new ApplianceColorTemperatureValue { value = applianceToControl.GetValue <int>("Temperature").GetAwaiter().GetResult() }; break; case ControlRequestType.IncrementColorTemperature: currentValue = applianceToControl.GetValue <int>("Temperature").GetAwaiter().GetResult(); valueToSend = Math.Round(currentValue + adjustValue, 0).LimitToRange(1000, 10000); // set the value applianceToControl.SetValue("Temperature", valueToSend.ToString()).GetAwaiter().GetResult(); // read it back response.payload.achievedState.colorTemperature = new ApplianceColorTemperatureValue { value = applianceToControl.GetValue <int>("Temperature").GetAwaiter().GetResult() }; break; case ControlRequestType.DecrementColorTemperature: currentValue = Math.Round(applianceToControl.GetValue <Double>("Temperature").GetAwaiter().GetResult(), 2); valueToSend = Math.Round(currentValue - adjustValue, 0).LimitToRange(1000, 10000); // set the value applianceToControl.SetValue("Temperature", valueToSend.ToString()).GetAwaiter().GetResult(); // read it back response.payload.achievedState.colorTemperature = new ApplianceColorTemperatureValue { value = applianceToControl.GetValue <int>("Temperature").GetAwaiter().GetResult() }; break; default: break; } } else if (deviceType == DeviceType.Thermostat) { int previousTemperatureMode; int temperatureMode; Temperature previousTargetTemperature = null; Temperature targetTemperature = null; double deltaTemperatureC = 0.0; // in C // obtain previous state (sys stores temperatures as K) previousTemperatureMode = applianceToControl.GetValue <int>("TemperatureMode").GetAwaiter().GetResult(); previousTargetTemperature = new Temperature(applianceToControl.GetValue <double>("CurrentSetPoint").GetAwaiter().GetResult()); switch (requestType) { case ControlRequestType.SetTargetTemperature: // get target temperature in C targetTemperature = new Temperature { Celcius = double.Parse(alexaRequest.payload.targetTemperature.value) }; break; case ControlRequestType.IncrementTargetTemperature: // get delta temp in C deltaTemperatureC = double.Parse(alexaRequest.payload.deltaTemperature.value); // increment the targetTemp targetTemperature = new Temperature { Celcius = previousTargetTemperature.Celcius + deltaTemperatureC }; break; case ControlRequestType.DecrementTargetTemperature: // get delta temp in C deltaTemperatureC = double.Parse(alexaRequest.payload.deltaTemperature.value); // decrement the targetTemp targetTemperature = new Temperature { Celcius = previousTargetTemperature.Celcius - deltaTemperatureC }; break; default: targetTemperature = new Temperature(0.00); previousTemperatureMode = 10; // error break; } // set new target temperature applianceToControl.SetValue("CurrentSetPoint", targetTemperature.Kelvin.ToString()).GetAwaiter().GetResult(); response.payload.targetTemperature = new ApplianceValue { value = targetTemperature.Celcius.ToString() }; // get new mode temperatureMode = applianceToControl.GetValue <int>("TemperatureMode").GetAwaiter().GetResult(); // report new mode response.payload.temperatureMode = new ApplianceValue { value = TemperatureMode.ModeToString(temperatureMode) }; // alloc a previousState object response.payload.previousState = new AppliancePreviousState { // report previous mode mode = new ApplianceValue { value = TemperatureMode.ModeToString(previousTemperatureMode) }, // report previous targetTemperature in C targetTemperature = new ApplianceValue { value = previousTargetTemperature.Celcius.ToString() } }; } else { response.header.@namespace = Faults.Namespace; response.header.name = Faults.UnsupportedOperationError; response.payload.exception = new ExceptionResponsePayload(); } } catch { response.header.@namespace = Faults.Namespace; response.header.name = Faults.DriverpublicError; response.payload.exception = new ExceptionResponsePayload(); } return(response); }
/// <summary> /// Initializes a new instance of the <see cref="MonoBrick.EV3.TemperatureSensor"/> class. /// </summary> /// <param name="mode">Mode.</param> public TemperatureSensor (TemperatureMode mode) : base((SensorMode)mode) { }