public static double CalculateAmbientTemperature(byte[] rawData, TemperatureScale scale)
 {
     var temperature = BitConverter.ToUInt16(rawData, 2) / 128.0;
     if (scale == TemperatureScale.Farenheit)
         return ConvertToFahrenheit(temperature);
     return temperature;
 }
 /// <summary>
 /// Calculates the target temperature.
 /// </summary>
 /// <param name="sensorData">Complete array of data retrieved from the sensor</param>
 /// <param name="scale"></param>
 /// <returns></returns>
 public static double CalculateTargetTemperature(byte[] sensorData, TemperatureScale scale)
 {
     Validator.RequiresNotNull(sensorData);
     if (scale == TemperatureScale.Celsius)
         return CalculateTargetTemperature(sensorData, (BitConverter.ToUInt16(sensorData, 2) / 128.0));
     else
         return CalculateTargetTemperature(sensorData, (BitConverter.ToUInt16(sensorData, 2) / 128.0)) * 1.8 + 32;
 }
示例#3
0
        private static double ConvertTo(TemperatureScale toScale, double celciusTemperature)
        {
            if (toScale == TemperatureScale.Fahrenheit)
            {
                return(celciusTemperature.CelciusToFahrenheit());
            }

            return(celciusTemperature);
        }
示例#4
0
 public void LoadAll()
 {
     _wifiOnly      = Preferences.Get("wifiOnly", DefaultSettings.WifiOnly(), sharedName);
     _newsCacheTime = Preferences.Get("newsCacheTime", DefaultSettings.NewsCacheTime(), sharedName);
     _themeOption   = (Theme)Preferences.Get("themeOption", DefaultSettings.ThemeOption(), sharedName);
     _onlyShowNextCycleWhenImminent = Preferences.Get("onlyShowNextCycleWhenImminent", DefaultSettings.OnlyShowNextCycleWhenImminent(), sharedName);
     _marsBackground   = Preferences.Get("marsBackground", DefaultSettings.MarsBackground(), sharedName);
     _temperatureScale = (TemperatureScale)Preferences.Get("temperatureScale", DefaultSettings.TemperatureScale(), sharedName);
 }
 /// <summary>
 /// Calculates the target temperature.
 /// </summary>
 /// <param name="sensorData">Complete array of data retrieved from the sensor</param>
 /// <param name="ambientTemperature">calculated ambient temperature, saves another calculation of the ambient temoerature.</param>
 /// <param name="scale"></param>
 /// <returns></returns>
 public static double CalculateTargetTemperature(byte[] sensorData, double ambientTemperature, TemperatureScale scale)
 {
     Validator.RequiresNotNull(sensorData, "sensorData");
     Validator.RequiresNotNull(ambientTemperature, "ambientTemperature");
     Validator.RequiresArgument(!double.IsNaN(ambientTemperature), "ambientTemperature cannot be double.NaN");
     if (scale == TemperatureScale.Celsius)
         return CalculateTargetTemperature(sensorData, ambientTemperature);
     else
         return CalculateTargetTemperature(sensorData, ambientTemperature) * 1.8 + 32;
 }
示例#6
0
 public static double CalculateAmbientTemperature(byte[] sensorData, TemperatureScale scale)
 {
     if (scale == TemperatureScale.Celsius)
     {
         return(BitConverter.ToUInt16(sensorData, 2) / 128.0);
     }
     else
     {
         return((BitConverter.ToUInt16(sensorData, 2) / 128.0) * 1.8 + 32);
     }
 }
示例#7
0
 /// <summary>
 /// Calculates the target temperature.
 /// </summary>
 /// <param name="sensorData">Complete array of data retrieved from the sensor</param>
 /// <param name="scale"></param>
 /// <returns></returns>
 private static double CalculateTargetTemperature(byte[] sensorData, TemperatureScale scale)
 {
     if (scale == TemperatureScale.Celsius)
     {
         return(CalculateTargetTemperature(sensorData, (BitConverter.ToUInt16(sensorData, 2) / 128.0)));
     }
     else
     {
         return(CalculateTargetTemperature(sensorData, (BitConverter.ToUInt16(sensorData, 2) / 128.0)) * 1.8 + 32);
     }
 }
 /// <summary>
 ///Temperature conversion method.
 /// </summary>
 public double ConvertTemperature(double temperature, TemperatureScale scale)
 {
     if (scale == TemperatureScale.Celsius)
     {
         return(0);
     }
     else
     {
         return(0);
     }
 }
示例#9
0
    private static String GetCurrentTemperature()
    {
        DateTime         dat   = DateTime.Now;
        Decimal          temp  = 20.6m;
        TemperatureScale scale = TemperatureScale.Celsius;
        String           result;

        result = String.Format("At {0:t} on {1:D}, the temperature is {2:F1} {3:G}",
                               dat, temp, scale);
        return(result);
    }
 /// <summary>
 /// Calculates the target temperature.
 /// </summary>
 /// <param name="sensorData">Complete array of data retrieved from the sensor</param>
 /// <param name="scale"></param>
 /// <returns></returns>
 public static double CalculateTargetTemperature(byte[] sensorData, TemperatureScale scale)
 {
     Validator.RequiresNotNull(sensorData);
     if (scale == TemperatureScale.Celsius)
     {
         return(CalculateTargetTemperature(sensorData, (BitConverter.ToUInt16(sensorData, 2) / 128.0)));
     }
     else
     {
         return(CalculateTargetTemperature(sensorData, (BitConverter.ToUInt16(sensorData, 2) / 128.0)) * 1.8 + 32);
     }
 }
示例#11
0
        /// <summary>Constructs a new instance.</summary>
        /// <param name="socketNumber">The socket that this module is plugged in to.</param>
        public Thermocouple(int socketNumber)
        {
            Socket socket = Socket.GetSocket(socketNumber, true, this, null);

            socket.EnsureTypeIsSupported(new char[] { 'X', 'Y' }, this);

            this.miso = GTI.DigitalInputFactory.Create(socket, Socket.Pin.Three, GTI.GlitchFilterMode.Off, GTI.ResistorMode.PullUp, this);
            this.clk  = GTI.DigitalOutputFactory.Create(socket, Socket.Pin.Four, false, this);
            this.cs   = GTI.DigitalOutputFactory.Create(socket, Socket.Pin.Five, true, this);

            this.Scale = TemperatureScale.Celsius;
        }
示例#12
0
        public void SetTemperature(double v, TemperatureScale scale)
        {
            switch (scale)
            {
            case TemperatureScale.Fahrenheit:
                Fahrenheit = v;
                break;

            default:
                Celsius = v;
                break;
            }
        }
示例#13
0
文件: Tools.cs 项目: ankstek/fluidity
        public static readonly double R_THROUGH_CV = 1.31950791077289; //precalculated for when volume is halved

        public static double getDisplayTemperature(double temperatureK, TemperatureScale playerTempScale)
        {
            switch (playerTempScale)
            {
            case TemperatureScale.KELVIN: return(temperatureK);

            case TemperatureScale.CELSIUS: return(temperatureK - 272.15);

            case TemperatureScale.FARENHEIT: return(temperatureK * (1.8) - 459.67);

            default: return(temperatureK);
            }
        }
示例#14
0
 internal ThresholdInfo(
     string name,
     double temperature,
     TemperatureScale scale,
     double sensitivity,
     double?lastNotificationTemperature
     )
 {
     Name        = name;
     Temperature = temperature;
     Scale       = scale;
     Sensitivity = sensitivity;
     LastNotificationTemperature = lastNotificationTemperature;
 }
        public static double CalculateAmbientTemperature(byte[] sensorData, TemperatureScale scale)
        {
            const double SCALE_LSB = 0.03125;
            double       ambient   = ((double)(BitConverter.ToUInt16(sensorData, 0) >> 2)) * SCALE_LSB;

            if (scale == TemperatureScale.Celsius)
            {
                return(ambient);
            }
            else
            {
                return(ambient * 1.8 + 32);
            }
        }
        public static string ToFriendlyString(this TemperatureScale tempScale)
        {
            switch (tempScale)
            {
            case TemperatureScale.Celsius:
                return("C");

            case TemperatureScale.Fahrenheit:
                return("F");

            default:
                return(string.Empty);
            }
        }
示例#17
0
        private Temperature CreateTemperature(float value, TemperatureScale unit)
        {
            switch (unit)
            {
            case TemperatureScale.Fahrenheit:
                return(new FahrenheitTemperature(value));

            case TemperatureScale.Celsius:
                return(new CelsiusTemperature(value));

            default:
                throw new ArgumentOutOfRangeException(nameof(unit), unit, $"Temperature unit {unit} is not yet implemented");
            }
        }
        public static string ToUnitsType(this TemperatureScale tempScale)
        {
            switch (tempScale)
            {
            case TemperatureScale.Celsius:
                return("metric");

            case TemperatureScale.Fahrenheit:
                return("imperial");

            default:
                return(string.Empty);
            }
        }
        public static double CalculateHumidityTempareture(byte[] sensorData, TemperatureScale scale)
        {
            int    temp  = BitConverter.ToUInt16(sensorData, 0);
            double htemp = ((double)temp / 65536) * 165 - 40;

            if (scale == TemperatureScale.Celsius)
            {
                return(htemp);
            }
            else
            {
                return(htemp * 1.8 + 32);
            }
        }
示例#20
0
        public static string ToString(this TemperatureScale scale, double amount)
        {
            switch (scale)
            {
            case TemperatureScale.Fahrenheit:
                return(((int)amount) + "°F");

            case TemperatureScale.Celsius:
                return(((int)amount) + "°C");

            case TemperatureScale.Kelvin:
                return(((int)amount) + "K");
            }
            // Complier doesn't know this won't happen
            return(null);
        }
示例#21
0
        public void SetCurrentTemperatureType(TemperatureScale temperatureScale)
        {
            switch (temperatureScale)
            {
            case TemperatureScale.Fahrenheit:
                TemperatureValueDataMember = "Weather.FahrenheitTemperature";
                TemperatureString          = Weather.FahrenheitTemperatureString;
                CrosshairLabelPattern      = "{A:g} : {V} °F";
                break;

            case TemperatureScale.Celsius:
                TemperatureValueDataMember = "Weather.CelsiusTemperature";
                TemperatureString          = Weather.CelsiusTemperatureString;
                CrosshairLabelPattern      = "{A:g} : {V} °C";
                break;
            }
        }
示例#22
0
        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>());
        }
示例#23
0
        public static string ToText(this TemperatureScale temperatureScale)
        {
            switch (temperatureScale)
            {
            case TemperatureScale.Kelvin:
                return("kelvin");

            case TemperatureScale.Celsius:
                return("metric");

            case TemperatureScale.Fahrenheit:
                return("imperial");

            default:
                throw new ArgumentException(nameof(temperatureScale));
            }
        }
        public async Task <OpenWeatherMapResponse> GetCurrentWeatherAsync(
            string city, string countryCode, TemperatureScale tempScale, Language lang)
        {
            const string WEATHER_CACHE_KEY = "Weather";

            // Look for cache key
            if (!_cache.TryGetValue(WEATHER_CACHE_KEY, out OpenWeatherMapResponse currentWeather))
            {
                // Key not in cache, so get data

                // Fetch the user secret
                var apiKey = _configuration.GetValue <string>("OpenWeatherMapApiKey");

                if (String.IsNullOrWhiteSpace(apiKey))
                {
                    throw new ArgumentException("Unable to find an OpenWeatherMap API key in the user secret store.");
                }

                string langCode  = lang.ToLanguageCode();
                string unitsType = tempScale.ToUnitsType();
                IConfigurationSection weatherConfig = _configuration.GetSection("Weather");
                var baseUrl     = weatherConfig.GetValue <string>("ApiBaseUrl");
                var endpointUrl = $"{baseUrl}?q={city},{countryCode}&lang={langCode}&units={unitsType}&appid={apiKey}";

                var client   = _httpClient.CreateClient();
                var response = await client.GetStringAsync(endpointUrl);

                currentWeather = JsonConvert.DeserializeObject <OpenWeatherMapResponse>(response);
                // currentWeather = JsonConvert.DeserializeObject<OpenWeatherMapResponse>(
                //     @"{""coord"":{""lon"":-80.14,""lat"":26.12},""weather"":[{""id"":801,""main"":""Clouds"",""description"":""few clouds"",""icon"":""02d""}],""base"":""stations"",""main"":{""temp"":74.3,""pressure"":1020,""humidity"":73,""temp_min"":73.4,""temp_max"":75.2},""visibility"":16093,""wind"":{""speed"":11.41,""deg"":40},""clouds"":{""all"":20},""dt"":1517867580,""sys"":{""type"":1,""id"":657,""message"":0.0035,""country"":""US"",""sunrise"":1517832128,""sunset"":1517872047},""id"":4155966,""name"":""Fort Lauderdale"",""cod"":200}"
                // );

                // Keep in cache for this duration; reset time if accessed
                var cacheEntryOptions = new MemoryCacheEntryOptions
                {
                    SlidingExpiration = TimeSpan.FromSeconds(
                        weatherConfig.GetValue <int>("CacheDuration"))
                };

                // Save data in cache
                _cache.Set(WEATHER_CACHE_KEY, currentWeather, cacheEntryOptions);
            }

            return(currentWeather);
        }
        public static double CalculatePressureTempareture(byte[] sensorData, TemperatureScale scale)
        {
            byte[] rawData = new byte[4];
            rawData[0] = sensorData[0];
            rawData[1] = sensorData[1];
            rawData[2] = sensorData[2];
            rawData[3] = 0;
            var raw = BitConverter.ToUInt32(rawData, 0);

            if (scale == TemperatureScale.Celsius)
            {
                return(raw / 100.0);
            }
            else
            {
                return(((double)raw) / 100.0 * 1.8 + 32);
            }
        }
        public double?GetReading(TemperatureScale requestedScale)
        {
            // No reading set yet?
            if (_reading == null)
            {
                return(null);
            }

            if (requestedScale == TemperatureScale.Fahrenheit)
            {
                return(_scale == TemperatureScale.Fahrenheit ? _reading : (_reading * 9 / 5) + 32);
            }

            if (requestedScale == TemperatureScale.Celsius)
            {
                return(_scale == TemperatureScale.Celsius ? _reading : (1 - 32) * 5 / 9);
            }

            throw new ArgumentOutOfRangeException("Only Celsius and Fahrenheit are supported temperature scales.");
        }
 public GetWheaterForCityFixture ResultIn(TemperatureScale temperatureScale)
 {
     FixtureElements.TemperatureScale = temperatureScale;
     return(this);
 }
		private static double ConvertTo(TemperatureScale toScale, double celsiusTemperature) {
			if (toScale == TemperatureScale.Fahrenheit)
				return celsiusTemperature.CelsiusToFahrenheit();

			return celsiusTemperature;
		}
 /// <summary>
 /// Gets the temperature value.
 /// </summary>
 /// <returns>
 /// The temperature value in the specified scale.
 /// </returns>
 /// <param name="scale">
 /// The scale to get the temperature measurement in.
 /// </param>
 public Double GetTemperature(TemperatureScale scale)
 {
     return(TemperatureConversion.Convert(this.Scale, scale, this.Temperature));
 }
示例#30
0
		/// <summary>
		/// Gets the scale postfix.
		/// </summary>
		/// <returns>
		/// The scale postfix
		/// .</returns>
		/// <param name="scale">
		/// The scale to get the postfix for.
		/// </param>
		public static Char GetScalePostfix(TemperatureScale scale) {
			return GetScaleName(scale).ToCharArray()[0];
		}
        public WeatherData GetWeatherReport(CultureInfo culture, LocationData location, TemperatureScale tempScale)
        {
            var url = string.Format(tempScale == TemperatureScale.Celsius ? RequestForCelsius : RequestForFahrenheit, culture.Name, location.Code);

            XDocument doc;
            try
            {
                doc = XDocument.Load(url);
            }
            catch (Exception)
            {
                return null;
            }

            //parse current weather
            var weather = from x in doc.Descendants("weather")
                          let xElement = x.Element("current")
                          where xElement != null
                          select
                              new
                              {
                                  feelslike = xElement.Attribute("feelslike").Value,
                                  windspeed = xElement.Attribute("windspeed").Value,
                                  humidity = xElement.Attribute("humidity").Value,
                                  temp = xElement.Attribute("temperature").Value,
                                  text = xElement.Attribute("skytext").Value,
                                  skycode = xElement.Attribute("skycode").Value,
                                  windstring = xElement.Attribute("winddisplay").Value,
                                  time = xElement.Attribute("observationtime").Value
                              };

            var result = new WeatherData();
            var currentWeather = weather.FirstOrDefault();
            if (currentWeather == null)
                return null;

            result.ProviderCopyright = doc.Descendants("weather").Attributes("attribution").First().Value + " " +
                doc.Descendants("weather").Attributes("attribution2").First().Value;
            var t = 0;
            int.TryParse(currentWeather.temp, out t);
            result.Temperature = t;

            int.TryParse(currentWeather.feelslike, out t);
            result.FeelsLike = t;

            result.Curent = new ForecastData()
            {
                Text = currentWeather.text,
                //SkyCode = GetWeatherPic(Convert.ToInt32(currentWeather.skycode), 4, 22)
            };

            result.Location = location;
            if (doc.Descendants("weather").FirstOrDefault() == null)
                return null;
            var locString = doc.Descendants("weather").FirstOrDefault().Attribute("weatherlocationname").Value;
            if (locString.Contains(","))
            {
                result.Location.City = locString.Substring(0, locString.IndexOf(","));
                result.Location.Country = locString.Substring(locString.IndexOf(",") + 2);
            }
            else
            {
                result.Location.City = locString;
            }

            ////parse coordinates
            //var coords = from x in doc.Descendants("weather")
            //             select new
            //             {
            //                 lon = x.Attribute("long").Value,
            //                 lat = x.Attribute("lat").Value
            //             };
            //double lat, lon = double.MinValue;
            //double.TryParse(coords.FirstOrDefault().lat, NumberStyles.Float, CultureInfo.GetCultureInfo("en-US").NumberFormat, out lat);
            //double.TryParse(coords.FirstOrDefault().lon, NumberStyles.Float, CultureInfo.GetCultureInfo("en-US").NumberFormat, out lon);
            //result.Location.Lat = lat;
            //result.Location.Lon = lon;
            result.Curent.SkyCode = GetWeatherPic(Convert.ToInt32(currentWeather.skycode));

            //parse forecast
            var forecastUrl = string.Format(tempScale == TemperatureScale.Celsius ? ForecastUrlForCelsius : ForecastUrlForFahrenheit, location.Code);

            var f = new List<ForecastData>();
            foreach (var day in doc.Descendants("forecast"))
            {
                f.Add(new ForecastData());
                var temp = 0;
                int.TryParse(day.Attribute("high").Value, out temp);
                f[f.Count - 1].HighTemperature = temp;
                int.TryParse(day.Attribute("low").Value, out temp);
                f[f.Count - 1].LowTemperature = temp;
                f[f.Count - 1].Text = day.Attribute("skytextday").Value;
                f[f.Count - 1].SkyCode = GetWeatherPic(Convert.ToInt32(day.Attribute("skycodeday").Value));
                f[f.Count - 1].Url = forecastUrl;
                f[f.Count - 1].Day = day.Attribute("day").Value;
                f[f.Count - 1].Precipitation = Convert.ToInt32(day.Attribute("precip").Value);
            }

            if (f.Count > 0)
            {
                result.Curent.HighTemperature = f[0].HighTemperature;
                result.Curent.LowTemperature = f[0].LowTemperature;
                result.Curent.Precipitation = f[0].Precipitation;
            }

            result.ForecastList = f;

            DateTime time;
            if (DateTime.TryParse(currentWeather.time, out time))
            {
                float leftHours = 23 - time.Hour;
                float tempChange = result.Curent.HighTemperature - result.Curent.LowTemperature;
                float lastTemp = result.Curent.HighTemperature;

                for (int i = 1; i <= 3; i++)
                {
                    var hourForecast = new HourForecastData();
                    var newTime = DateTime.Now.AddHours(DateTime.Now.Hour + 4*i);
                    hourForecast.Time = new DateTime(1, 1, 1, newTime.Hour, 0, 0).ToShortTimeString();
                    hourForecast.Precipitation = result.Curent.Precipitation; //NOTE here must be some calculations too
                    float tempChangePerHour = 0;
                    if ((newTime.Hour >= 19 && newTime.Hour <= 23) || (newTime.Hour >= 0 && newTime.Hour <= 6))
                    {
                        tempChangePerHour = -tempChange / leftHours;
                    }
                    else
                    {
                        tempChangePerHour = tempChange / leftHours;
                    }
                    lastTemp = lastTemp + 4.0f * tempChangePerHour;
                    hourForecast.Temperature = Math.Round(lastTemp).ToString();
                    result.HourForecastList.Add(hourForecast);

                }
            }

            return result;
        }
        /// <summary>
        /// Provides a simple method for converting the LM35 temperature sensor lecture to celsius with the MCP3008
        /// </summary>
        /// <param name="mv">Milivolts from readmvFromPort</param>
        /// <returns>LM35 temp meausre in Celsius</returns>
        public static double LM35mvToTemp(double mv, TemperatureScale temp)
        {
            var tempC = mv / 10.0;

            if(temp == TemperatureScale.Celsius)
            {
                return tempC;
            }
            else
            {
                return (tempC * 9.0 / 5.0) + 32;
            }
            
        }
 /// <summary>
 /// Changes the temperature scale.
 /// </summary>
 /// <param name="scale">
 /// The scale to change to.
 /// </param>
 public void ChangeScale(TemperatureScale scale)
 {
     lock (this) {
         this._scale = scale;
     }
 }
        /// <summary>
        /// Sets the target temperature of the thermostat to the given value.
        /// </summary>
        /// <param name="accessToken">OAuth access token.</param>
        /// <param name="thermostatDeviceId">The DeviceId of the thermostat.</param>
        /// <param name="thermostatTemperatureScale">The temperature scale of the target temperature.</param>
        /// <param name="targetTemperature">The target temperature, in °C or °F depending on the temperature scale.</param>
        public void SetThermostatTargetTemperature(string accessToken, string thermostatDeviceId, TemperatureScale thermostatTemperatureScale, decimal targetTemperature)
        {
            if (_log.IsInfoEnabled)
            {
                _log.InfoFormat("Setting thermostat '{0}' to {1} {2}.", thermostatDeviceId, targetTemperature, thermostatTemperatureScale);
            }

            string setTargetTemperatureUrl;

            if (_session.TemperatureSetSubsequentUrl.ContainsKey(thermostatDeviceId) && _session.PreviousThermostats[thermostatDeviceId].TemperatureScale == thermostatTemperatureScale)
            {
                setTargetTemperatureUrl = _session.TemperatureSetSubsequentUrl[thermostatDeviceId];
            }
            else
            {
                setTargetTemperatureUrl = string.Format(
                    "https://developer-api.nest.com/devices/thermostats/{0}/target_temperature_{1}?auth={2}",
                    thermostatDeviceId,
                    Utils.ToEnumString(thermostatTemperatureScale).ToLower(),
                    accessToken);
            }

            var targetTemperatureString = thermostatTemperatureScale == TemperatureScale.Celcuis ? targetTemperature.ToString("0.0") : targetTemperature.ToString();
            string subsequentTemperatureSetUrl;

            SetNewValue(setTargetTemperatureUrl, targetTemperatureString, out subsequentTemperatureSetUrl);

            _session.TemperatureSetSubsequentUrl[thermostatDeviceId] = subsequentTemperatureSetUrl;
        }
示例#35
0
 public WeatherDataBuilder SetMaxTemperature(float value, TemperatureScale unit)
 {
     return(Do(x => x.TemperatureMax = CreateTemperature(value, unit)));
 }
示例#36
0
 public static double CalculateAmbientTemperature(byte[] sensorData, TemperatureScale scale)
 {
     const double SCALE_LSB = 0.03125;
     double ambient = ((double)(BitConverter.ToUInt16(sensorData, 0) >> 2)) * SCALE_LSB;
     if (scale == TemperatureScale.Celsius)
         return ambient;
     else
         return ambient * 1.8 + 32;
 }
		/// <summary>
		/// Initializes a new instance of the
		/// <see cref="CyrusBuilt.MonoPi.Components.Temperature.TemperatureSensorComponent"/>
		/// class with the clock, data, and reset pins needed for the sensor,
		/// as well as the scale to get the temperature readings in.
		/// </summary>
		/// <param name="scale">
		/// The scale to get the temperature readings in.
		/// </param>
		/// <param name="clock">
		/// The GPIO pin used for the clock.
		/// </param>
		/// <param name="data">
		/// The GPIO pin used for data.
		/// </param>
		/// <param name="reset">
		/// The GPIO pin used to trigger reset.
		/// </param>
		/// <exception cref="ArgumentNullException">
		/// Pins cannot be null.
		/// </exception>
		public TemperatureSensorComponent(TemperatureScale scale, IGpio clock, IGpio data, IGpio reset)
			: base(clock, data, reset) {
			this._scale = scale;
		}
示例#38
0
		/// <summary>
		/// Convert the temperature in degrees Farenheit to the specified scale.
		/// </summary>
		/// <returns>
		/// The temperature value in the specified scale.
		/// </returns>
		/// <param name="scale">
		/// The scale to convert to.
		/// </param>
		/// <param name="temp">
		/// The temperature in degrees Farenheit.
		/// </param>
		public static Double ConvertFromFarenheit(TemperatureScale scale, Double temp) {
			Double val = 0;
			switch (scale) {
				case TemperatureScale.Farenheit:
					val = temp;
					break;
				case TemperatureScale.Celcius:
					val = ConvertFarenheitToCelcius(temp);
					break;
				case TemperatureScale.Kelvin:
					val = ConvertFarenheitToKelvin(temp);
					break;
				case TemperatureScale.Rankine:
					val = ConvertFarenheitToRankine(temp);
					break;
				default:
					break;
			}
			return val;
		}
示例#39
0
        public async Task <JObject> AdjustTemperatureAsync(string deviceId, float degrees, TemperatureScale scale, TemperatureSettingType type = TemperatureSettingType.None)
        {
            var url = BASE_URL + "devices/thermostats/{0}?auth={1}";

            var field = "target_temperature_{0}{1}";

            var tempScale = scale.ToString().ToLower();

            var tempType = string.Empty;

            if (type != TemperatureSettingType.None)
            {
                tempType = type.ToString().ToLower() + "_";
            }

            var thermostat = await GetThermostatAsync(deviceId);

            var exMsg = string.Empty;

            if (thermostat.IsUsingEmergencyHeat)
            {
                exMsg = "Can't adjust target temperature while using emergency heat";
            }
            else if (thermostat.HvacMode == HvacMode.HeatCool && type == TemperatureSettingType.None)
            {
                exMsg = "Can't adjust targt temperature while in Heat + Cool Mode, use High/Low TemperatureSettingTypes instead";
            }
            else if (thermostat.HvacMode != HvacMode.HeatCool && type != TemperatureSettingType.None)
            {
                exMsg = "Can't adjust target temperature type.ToString () while in Heat or Cool mode.  Use None for TemperatureSettingType instead";
            }
            //TODO: Get the structure instead and check for away
//            else if (1 == 2) { // Check for 'away'
//                exMsg = "Can't adjust target temperature while in Away or Auto-Away mode";
//            }

            if (!string.IsNullOrEmpty(exMsg))
            {
                throw new ArgumentException(exMsg);
            }

            var formattedUrl = string.Format(
                url,
                thermostat.DeviceId,
                AccessToken);

            var formattedField = string.Format(
                field,
                tempType,
                tempScale);

            var json = @"{""" + formattedField + @""": " + degrees + "}";


            var r = await http.PutAsync(formattedUrl, new StringContent (
                                            json,
                                            Encoding.UTF8,
                                            "application/json"));

            r.EnsureSuccessStatusCode();

            var data = await r.Content.ReadAsStringAsync();

            return(JObject.Parse(data));
        }
示例#40
0
		private static double ConvertFrom(TemperatureScale fromScale, double fromTemperature) {
			if (fromScale == TemperatureScale.Fahrenheit)
				return fromTemperature.FahrenheitToCelsius();

			return fromTemperature;
		}
示例#41
0
 public static double CalculateTargetTemperature(byte[] sensorData, double ambientTemperature, TemperatureScale scale)
 {
     const double SCALE_LSB = 0.03125;
     double otemprate = ((double)(BitConverter.ToUInt16(sensorData, 2) >> 2)) * SCALE_LSB;
     if (scale == TemperatureScale.Celsius)
         return otemprate;
     else
         return otemprate * 1.8 + 32;
 }
示例#42
0
 public static double CalculateTargetTemperature(byte[] sensorData, double ambientTemperature, TemperatureScale scale)
 {
     if (scale == TemperatureScale.Celsius)
         return CalculateTargetTemperature(sensorData, ambientTemperature);
     else
         return CalculateTargetTemperature(sensorData, ambientTemperature) * 1.8 + 32;
 }
示例#43
0
 public WeatherDataBuilder SetApparentTemperature(float value, TemperatureScale unit)
 {
     return(Do(x => x.TemperatureApparent = CreateTemperature(value, unit)));
 }
示例#44
0
		/// <summary>
		/// Gets the name of the scale.
		/// </summary>
		/// <returns>
		/// The scale name.
		/// </returns>
		/// <param name="scale">
		/// The scale to get the name of.
		/// </param>
		public static String GetScaleName(TemperatureScale scale) {
			return Enum.GetName(typeof(TemperatureScale), scale);
		}
示例#45
0
 public static double CalculateAmbientTemperature(byte[] sensorData, TemperatureScale scale)
 {
     if (scale == TemperatureScale.Celsius)
         return BitConverter.ToUInt16(sensorData, 2) / 128.0;
     else
         return (BitConverter.ToUInt16(sensorData, 2) / 128.0) * 1.8 + 32;
 }
 /// <summary>
 /// Initializes a new instance of the
 /// <see cref="CyrusBuilt.MonoPi.Components.Temperature.TemperatureSensorComponent"/>
 /// class with the clock, data, and reset pins needed for the sensor,
 /// as well as the scale to get the temperature readings in.
 /// </summary>
 /// <param name="scale">
 /// The scale to get the temperature readings in.
 /// </param>
 /// <param name="clock">
 /// The GPIO pin used for the clock.
 /// </param>
 /// <param name="data">
 /// The GPIO pin used for data.
 /// </param>
 /// <param name="reset">
 /// The GPIO pin used to trigger reset.
 /// </param>
 /// <exception cref="ArgumentNullException">
 /// Pins cannot be null.
 /// </exception>
 public TemperatureSensorComponent(TemperatureScale scale, GpioFile clock, GpioFile data, GpioFile reset)
     : base(clock, data, reset)
 {
     this._scale = scale;
 }
 /// <summary>
 /// Initializes a new instance of the
 /// <see cref="CyrusBuilt.MonoPi.Components.Temperature.TemperatureSensorComponent"/>
 /// class with the scale to get the temperature in.
 /// </summary>
 /// <param name="scale">
 /// The scale to get the temperature readings in.
 /// </param>
 public TemperatureSensorComponent(TemperatureScale scale)
     : base()
 {
     this._scale = scale;
 }
示例#48
0
 /// <summary>
 /// Gets the temperature value.
 /// </summary>
 /// <returns>
 /// The temperature value in the specified scale.
 /// </returns>
 /// <param name="scale">
 /// The scale to get the temperature measurement in.
 /// </param>
 public Double GetTemperature(TemperatureScale scale)
 {
     return TemperatureConversion.Convert(this.Scale, scale, this.Temperature);
 }
 public Temperature(decimal degrees, TemperatureScale scale)
 {
     Degrees = degrees;
     Scale   = scale;
 }
 public Temperature(Temperature toCopy)
 {
     Degrees = toCopy.Degrees;
     Scale   = toCopy.Scale;
 }
示例#51
0
		/// <summary>
		/// Converts the specified temperature from one scale to another.
		/// </summary>
		/// <param name="from">
		/// The scale to convert the temperature from.
		/// </param>
		/// <param name="to">
		/// The scale to convert the temperature to.
		/// </param>
		/// <param name="temp">
		/// The temperature value to convert.
		/// </param>
		public static Double Convert(TemperatureScale from, TemperatureScale to, Double temp) {
			Double val = 0;
			switch (from) {
				case TemperatureScale.Farenheit:
					val = ConvertFromFarenheit(to, temp);
					break;
				case TemperatureScale.Celcius:
					val = ConvertFromCelcius(to, temp);
					break;
				case TemperatureScale.Kelvin:
					val = ConvertFromKelvin(to, temp);
					break;
				case TemperatureScale.Rankine:
					val = ConvertFromRankine(to, temp);
					break;
				default:
					break;
			}
			return val;
		}
示例#52
0
文件: default.xaml.cs 项目: dfr0/moon
		void ChangeTemperatureScale ()
		{
			scale++;
			if (scale == TemperatureScale.Max)
				scale = TemperatureScale.Min + 1;
			SetTemperature ();
		}