public void InsertTemperature(Temperature temperature) { try { using (var conn = new SqlConnection(ConnectionString)) { var cmd = new SqlCommand("app.usp_InsertTemperature", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add("@RoomID", SqlDbType.TinyInt, 1).Value = temperature.RoomID; cmd.Parameters.Add("@Temp", SqlDbType.Int, 4).Value = temperature.Temp; //cmd.Parameters.Add("@MemberID", SqlDbType.Int, 4).Direction = ParameterDirection.Output; conn.Open(); cmd.ExecuteNonQuery(); //temperature.MemberID = (int)cmd.Parameters["@MemberID"].Value; } } catch { throw new ApplicationException("Ett fel inträffade då temperaturen skulle läggas till i databasen."); } }
public void VerifyAllEnums() { var acceleration = new Acceleration(1, AccelerationUnit.BaseUnit); var angle = new Angle(1, AngleUnit.BaseUnit); var angularAcceleration = new AngularAcceleration(1, AngularAccelerationUnit.BaseUnit); var area = new Area(1, AreaUnit.BaseUnit); var density = new MassDensity(1, MassDensityUnit.BaseUnit); var electricCurrent = new ElectricCurrent(1, ElectricCurrentUnit.BaseUnit); var electricResistance = new ElectricResistance(1, ElectricResistanceUnit.BaseUnit); var electricVoltage = new ElectricPotential(1, ElectricPotentialUnit.BaseUnit); var energy = new Energy(1, EnergyUnit.BaseUnit); var force = new Force(1, ForceUnit.BaseUnit); var frequency = new Frequency(1, FrequencyUnit.BaseUnit); var jerk = new Jerk(1, JerkUnit.BaseUnit); var length = new Length(1, LengthUnit.BaseUnit); var mass = new Mass(1, MassUnit.BaseUnit); var massFlowRate = new MassFlowRate(1, MassFlowRateUnit.BaseUnit); var momentum = new Momentum(1, MomentumUnit.BaseUnit); var numeric = new Numeric(1, NumericUnit.BaseUnit); var power = new Power(1, PowerUnit.BaseUnit); var pressure = new Pressure(1, PressureUnit.BaseUnit); var speed = new Speed(1, SpeedUnit.BaseUnit); var temperature = new Temperature(1, TemperatureUnit.BaseUnit); var time = new Time(1, TimeUnit.BaseUnit); var torque = new Torque(1, TorqueUnit.BaseUnit); var volume = new Volume(1, VolumeUnit.BaseUnit); var volumetricFlowRate = new VolumetricFlowRate(1, VolumetricFlowRateUnit.BaseUnit); }
/// <summary> /// check if this is duplicate record /// </summary> public bool IsDuplicate(Temperature temp) { // TODO: checking duplicate data, may want to add some factors //if (CompareTimeStamp(temp)) return true; if (this.RemoteId == temp.RemoteId) return true; return false; }
public bool PosTest1() { bool retVal = true; // Add your scenario description here TestLibrary.TestFramework.BeginScenario("PosTest1: Verify interface IComparable ."); try { IComparable temp = new Temperature(); int expected = 0; int actual = temp.CompareTo(temp); if (actual != expected) { TestLibrary.TestFramework.LogError("001.1", "Method IComparable.CompareTo Err ."); TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("001.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; }
public async Task<IHttpActionResult> PutTemperature(int id, Temperature temperature) { if (!ModelState.IsValid) { return BadRequest(ModelState); } if (id != temperature.Id) { return BadRequest(); } db.Entry(temperature).State = EntityState.Modified; try { await db.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!TemperatureExists(id)) { return NotFound(); } else { throw; } } return StatusCode(HttpStatusCode.NoContent); }
private ClothingItem AddClothingItem(string name, ClothingType clothingType, WeatherCondition weatherCondition, Temperature temperature) { return clothingItemList[LastId++] = new ClothingItem(LastId, name, clothingType, new Weather(weatherCondition, temperature)); }
/// <summary> /// The class constructor. /// </summary> public WeatherData(Location loc, Time time, Temperature temp, string clouds) { this.Loc = loc; this.Time = time; this.Temperature = temp; this.Clouds = clouds; }
public async Task<IHttpActionResult> PostTemperature(Temperature temperature) { //pass stff with this. if (!ModelState.IsValid) { return BadRequest(ModelState); } if(temperature.CollectionTime == null) { temperature.CollectionTime = DateTime.UtcNow; } db.Temperatures.Add(temperature); try { await db.SaveChangesAsync(); } catch (DbUpdateException) { if (TemperatureExists(temperature.Id)) { return Conflict(); } else { throw; } } return CreatedAtRoute("DefaultApi", new { id = temperature.Id }, temperature); }
public void ConvertToFarhenheitTest() { Temperature t = new Temperature(); double x = 60; double expected = t.ConvertToFarhenheit(x); Assert.AreEqual(expected, ((x * 9) / 5) + 32, 0.00001); }
public void ConvertToCelsiusTest() { Temperature t = new Temperature(); double x = 212; double expected = t.ConvertToCelsius(x); Assert.AreEqual(expected, (5.0 / 9.0) * (x - 32), 0.00001); }
public static void Main() { Temperature t = new Temperature(new TimeSpan(0, 0, 1)); t.NewTemperatureFahrenheit += new Temperature.NewTemperatureDelegate(t_NewTemperatureFahrenheit); Thread.Sleep(Timeout.Infinite); }
private bool CompareTimeStamp(Temperature temp) { var myTime = Math.Round(this.Time, 2); var theirTime = Math.Round(temp.Time, 2); if (myTime == theirTime) return true; return false; }
public WeatherDaily() : base() { TemperatureNight = new Temperature(); TemperatureDay = new Temperature(); TemperatureMorning = new Temperature(); TemperatureEvening = new Temperature(); }
public void OpAddition() { var temperature1 = new Temperature(68, TemperatureUnit.Fahrenheit); var temperature2 = new Temperature(20, TemperatureUnit.Celsius); var expected = new Temperature(104, TemperatureUnit.Fahrenheit); (temperature1 + temperature2).ShouldEqual(expected); (temperature2 + temperature1).ShouldEqual(expected); }
static void Main(string[] args) { Temperature t = new Temperature(20); t.setTemp(21); Console.Write("Todays Temperature :"+t.getTemp()); Console.ReadKey(); }
public Substance(Pressure pressure, Enthalpy enthalpy) { Pressure = pressure; //Checking what region the Substanse belong to: //1. check if it is region 1 try { Temperature = new Temperature(Region1BackwardEquation_Tph.CalculateTemperature(pressure.Value, enthalpy.Value)); CalculateProperties(Temperature, Pressure); } catch (CantDetermineRegionException) { } if (SpecificEnthalpy!=null && Math.Round(SpecificEnthalpy.Value) == Math.Round(enthalpy.Value)) { //it is region 1 return; } //2. check if it is region 2 if (pressure.Value<=4) { Temperature = new Temperature(Region2aBackwardEquation_Tph.CalculateTemperature(pressure.Value, enthalpy.Value)); CalculateProperties(Temperature, Pressure); if (Math.Round(SpecificEnthalpy.Value, 1) == Math.Round(enthalpy.Value, 1)) { //it is region 2a return; } } else if (Region2B2bcEquation.is2cSubregion(pressure.Value, enthalpy.Value) == false) { Temperature = new Temperature(Region2bBackwardEquation_Tph.CalculateTemperature(pressure.Value, enthalpy.Value)); CalculateProperties(Temperature, Pressure); if (Math.Round(SpecificEnthalpy.Value, 1) == Math.Round(enthalpy.Value, 1)) { //it is region 2b return; } } else if (Region2B2bcEquation.is2cSubregion(pressure.Value, enthalpy.Value)) { Temperature = new Temperature(Region2cBackwardEquation_Tph.CalculateTemperature(pressure.Value, enthalpy.Value)); CalculateProperties(Temperature, Pressure); if (Math.Round(SpecificEnthalpy.Value, 1) == Math.Round(enthalpy.Value, 1)) { //it is region 2c return; } } else { throw new CantDetermineRegionException("It seems no region fits to these values pressure and enthalpy"); } }
public PinKit() { accelerometer = new Accelerometer(); temperature = new Temperature(); led = new BoardFullColorLED(); #if (USE_LIGHTSENSE) lightSensor = new LightSensor(); #endif }
public Freezer(FreezerModes fMode, int tempForFastFreezeMode, int tempForFreezingMode, int tempForStorageMode, Temperature temper, Mode mod) { Temper = temper; Mod = mod; Mod.CurrentMode = (UniversalMode)fMode; TempForFastFreezeMode = tempForFastFreezeMode; TempForFreezingMode = tempForFreezingMode; TempForStorageMode = tempForStorageMode; }
// GET /api/values/5 public Temperature GetTemperature(Temperature t) { Temperature t3 = Temperature.temps.Single(t2 => t.ID == t2.ID); if (t3 == null) { throw new HttpResponseException(HttpStatusCode.NotFound); } return t3; }
// POST /api/values public HttpResponseMessage<Temperature> PostTemperature(Temperature t) { Temperature.temps.Add(t); var response = new HttpResponseMessage<Temperature>(t, HttpStatusCode.Created); var relativePath = "/api/Temerature/" + t.ID; response.Headers.Location = new Uri(Request.RequestUri, relativePath); return response; }
public static void LogTemperature(int thermostatId, int degrees, Int16 precision) { Temperature t = new Temperature(); t.Degrees = degrees; t.LogDate = DateTime.Now; t.ThermostatId = thermostatId; t.Precision = precision; Temperature.SaveTemperature(t); }
public Weather() { Precipitation = new Precipitation(); Wind = new Wind(); Temperature = new Temperature(); Pressure = new Pressure(); Humidity = new Humidity(); Clouds = new Clouds(); }
public Heater(bool power, HeaterModes hm, int tempForModeStreet, int tempForModeInRoom, Temperature temper, Mode mod) { Power = power; Temperature = temper; Mode = mod; Mode.CurrentMode = (UniversalMode)hm; TempForModeInRoom = tempForModeInRoom; TempForModeStreet = tempForModeStreet; }
public void OpGreaterThanOrEqual() { var temperature1 = new Temperature(68, TemperatureUnit.Fahrenheit); var temperature2 = new Temperature(20, TemperatureUnit.Celsius); var temperature3 = new Temperature(104, TemperatureUnit.Fahrenheit); (temperature1 >= temperature3).ShouldBeFalse(); (temperature3 >= temperature1).ShouldBeTrue(); (temperature1 >= temperature2).ShouldBeTrue(); (temperature2 >= temperature1).ShouldBeTrue(); }
public void OpInverseEquals() { var temperature1 = new Temperature(68, TemperatureUnit.Fahrenheit); var temperature2 = new Temperature(20, TemperatureUnit.Celsius); var temperature3 = new Temperature(104, TemperatureUnit.Fahrenheit); (temperature1 != temperature2).ShouldBeFalse(); (temperature2 != temperature1).ShouldBeFalse(); (temperature1 != temperature3).ShouldBeTrue(); (temperature3 != temperature1).ShouldBeTrue(); }
public Forecast(string country, string city, string clouds, Temperature temperature) { if (string.IsNullOrWhiteSpace(country)) throw new ArgumentException("Country must not be empty.", nameof(country)); if (string.IsNullOrWhiteSpace(city)) throw new ArgumentException("City must not be empty.", nameof(city)); Country = country; City = city; Clouds = clouds; UpdateTemperature(temperature.Number, temperature.Unit); }
public AirConditioning(bool power, AirConditioningModes acm, int maxHeatingModeTemperatureValue, int minCoolingModeTemperatureValue, int temperatureForVentilation, Temperature temper, Mode mod) { Power = power; Temperature = temper; Mode = mod; Mode.CurrentMode = (UniversalMode)acm; MaxHeatingModeTemperatureValue = maxHeatingModeTemperatureValue; MinCoolingModeTemperatureValue = minCoolingModeTemperatureValue; TempForModeVentilation = temperatureForVentilation; }
public void OpDivision() { var temperature1 = new Temperature(68, TemperatureUnit.Fahrenheit); var temperature2 = new Temperature(20, TemperatureUnit.Celsius); (temperature1 / temperature2).ShouldBeWithinEpsilonOf(1); (temperature2 / temperature1).ShouldBeWithinEpsilonOf(1); (temperature1 / 2).ShouldEqual(new Temperature(50, TemperatureUnit.Fahrenheit)); (temperature2 / 2).ShouldEqual(new Temperature(10, TemperatureUnit.Celsius)); }
public void InsertTemperature(Temperature temperature) { ICollection<ValidationResult> validationResults; if (!temperature.Validate(out validationResults)) { throw new AggregateException("Objektet klarade inte valideringen.", validationResults.Select(vr => new ValidationException(vr.ErrorMessage)).ToList().AsReadOnly()); } TemperatureDAL.InsertTemperature(temperature); }
public Fridge(bool power, FridgeModes fm, int tempForManualMode, int tempForNormalMode, int tempForWarmMode, int tempForLowTemperatureMode, Temperature temper, Mode mod) { Power = power; Mode = mod; Mode.CurrentMode = (UniversalMode)fm; TempForManualMode = tempForManualMode; TempForNormalMode = tempForNormalMode; TempForWarmMode = tempForWarmMode; TempForLowTemperatureMode = tempForLowTemperatureMode; Temperature = temper; }
public void Initialize(Temperature temperature) { }
private static void CreateTopology() { Console.WriteLine("Creating Topology ... start"); //Making sure it has not been already added if (context.AsQueryable <Floor>().FirstOrDefault() == null) { //Create a floor 1 Floor floor1 = context.CreateResource <Floor>(ns + "f1"); floor1.Name = "floor 1"; floor1.Commit(); //Create a floor 2 Floor floor2 = context.CreateResource <Floor>(ns + "f2"); floor2.Name = "floor 2"; floor2.Commit(); //Create a Building 1 Building building1 = context.CreateResource <Building>(ns + "b1"); building1.Description = "North face Building"; building1.Name = "b1"; building1.Floors.Add(floor1); building1.Floors.Add(floor2); building1.Commit(); //Create a Temperature measurement Temperature temp1 = context.CreateResource <Temperature>(ns + "t1"); temp1.Description = "this is indoor temperature"; temp1.UnitOfMeasure = TemperatureUnit.Celsius; temp1.Name = "temp1"; temp1.TimeStamp = DateTime.UtcNow; temp1.Value = 32; temp1.Commit(); //Create a Temperature Sensor Sensor temperatureSensor = context.CreateResource <Sensor>(ns + "s1"); temperatureSensor.Description = "This is sensor s1"; temperatureSensor.Name = "TempSensor1"; temperatureSensor.Measures.Add(temp1); temperatureSensor.PhysicalLocation = floor1; temperatureSensor.Commit(); //Create a Humidity measurement Humidity humidity1 = context.CreateResource <Humidity>(ns + "h1"); humidity1.Description = "this is indoor humidity"; humidity1.UnitOfMeasure = HumidityUnit.RelativeHumidity; humidity1.Name = "h1"; humidity1.TimeStamp = DateTime.UtcNow; humidity1.Value = 64; humidity1.Commit(); //Create a Humidity Sensor Sensor humiditySensor = context.CreateResource <Sensor>(ns + "hum1"); humiditySensor.Description = "This is humidity sensor 1"; humiditySensor.Name = "hum1"; humiditySensor.Measures.Add(humidity1); humiditySensor.PhysicalLocation = floor2; humiditySensor.Commit(); } else { Console.WriteLine("Topology already created, not re-adding it"); } Console.WriteLine("Creating Topology ... done"); }
public void PressureIsCalculatedCorrectly(double expected, double seaLevelPressure, double altitude, double celsius) { Pressure pressure = WeatherHelper.CalculatePressure(Pressure.FromHectopascals(seaLevelPressure), Length.FromMeters(altitude), Temperature.FromDegreesCelsius(celsius)); Assert.Equal(expected, Math.Round(pressure.Hectopascals, 2)); }
public void HeatIndexIsCalculatedCorrectly(double expected, double celsius, double relativeHumidity) { Temperature heatIndex = WeatherHelper.CalculateHeatIndex(Temperature.FromDegreesCelsius(celsius), RelativeHumidity.FromPercent(relativeHumidity)); Assert.Equal(expected, Math.Round(heatIndex.DegreesCelsius)); }
/// <summary> /// Reads the temperature from the sensor /// </summary> /// <returns> /// Temperature in degrees celsius /// </returns> public Temperature ReadTemperature() { return(Temperature.FromCelsius((CalculateTrueTemperature() + 8) / 160.0)); }
public static double ConvertTo(Temperature input, string targetScale) => input.ValueIn(targetScale);
public TempratureRange(Temperature low, Temperature high) { Low = low; High = high; }
public void AbsoluteHumidityIsCalculatedCorrectly(double expected, double fahrenheit, double relativeHumidity) { Density absoluteHumidity = WeatherHelper.CalculateAbsoluteHumidity(Temperature.FromDegreesFahrenheit(fahrenheit), RelativeHumidity.FromPercent(relativeHumidity)); Assert.Equal(expected, absoluteHumidity.GramsPerCubicMeter, 0); }
public void Cannot_Leave_House_With_Pajama(Temperature temperature) { var dressPicker = new DressPicker(temperature.ToString()); Assert.Throws <NotValidToLeaveHouseViolation>(() => dressPicker.Process((int)Command.LeaveHouse)); }
public void ActualVaporPressureIsCalculatedCorrectly(double expected, double celsius, double relativeHumidity) { Pressure actualVaporPressure = WeatherHelper.CalculateActualVaporPressure(Temperature.FromDegreesCelsius(celsius), RelativeHumidity.FromPercent(relativeHumidity)); Assert.Equal(expected, Math.Round(actualVaporPressure.Pascals, 0)); }
public void SaturatedVaporPressureOverIce(double expected, double celsius) { Pressure saturatedVaporPressure = WeatherHelper.CalculateSaturatedVaporPressureOverIce(Temperature.FromDegreesCelsius(celsius)); Assert.Equal(expected, saturatedVaporPressure.Pascals, 1); }
public void Can_Remove_Pajama(Temperature temperature) { var dressPicker = new DressPicker(temperature.ToString()); Assert.AreEqual("Removing PJs", dressPicker.Process((int)Command.TakeOffPajama)); }
public string IsError() { if (string.IsNullOrWhiteSpace(GrsName)) { return("Укажите наименование ГРС"); } if (string.IsNullOrWhiteSpace(SubGrsName)) { return("Укажите наименование замерной нитки"); } if (Psantimeter > 0) { if (V1 + V2 + V3 + V9 + V10 + V11 > 0) { CalculateSmallK(); } else { K = SmallKConstants.KAll; } } else { if (V1 != 0 && !V1.CheckIntervalParams(90m, 97.9m)) { return("V1 параметр \"Объёмная концентрация метана\" несоответсвует"); } if (V2 != 0 && !V2.CheckIntervalParams(0.75m, 4.75m)) { return("V2 параметр \"Объёмная концентрация этана\" несоответсвует"); } if (V3 != 0 && !V3.CheckIntervalParams(0.30m, 3.5m)) { return("V3 параметр \"Объёмная концентрация пропана\" несоответсвует"); } if (V4 != 0 && !V4.CheckIntervalParams(0.01m, 0.5m)) { return("V4 параметр \"Объёмная концентрация i-бутана\" несоответсвует"); } if (!V5.CheckIntervalParams(0m, 0.4m)) { return("V5 параметр \"Объёмная концентрация n-бутана\" несоответсвует"); } if (!V6.CheckIntervalParams(0m, 0.2m)) { return("V6 параметр \"Объёмная концентрация i-пентана\" несоответсвует"); } if (!V7.CheckIntervalParams(0m, 0.15m)) { return("V7 параметр \"Объёмная концентрация n-пентана\" несоответсвует"); } if (!V8.CheckIntervalParams(0m, 0.3m)) { return("V8 параметр \"Объёмная концентрация гексана\" несоответсвует"); } if (V9 != 0 && !V9.CheckIntervalParams(0.1m, 2.5m)) { return("V9 параметр \"Объёмная концентрация углекислого газа\" несоответсвует"); } if (V10 != 0 && !V10.CheckIntervalParams(0.2m, 1.3m)) { return("V10 параметр \"Объёмная концентрация азота\" несоответсвует"); } if (!V11.CheckIntervalParams(0m, 0.3m)) { return("V11 параметр \"Объёмная концентрация кислорода\" несоответсвует"); } if (K == 0) { CalculateSmallK(); } else if (!K.CheckIntervalParams(1.24m, 2.1m)) { return("k параметр \"Объёмный показатель адиабаты\" несоответсвует"); } else { this.IsCalculateK = false; } } if (Z == 0) { this.Z = 0.882m; } else if (!Z.CheckIntervalParams(0.6m, 0.9999m)) { return("z параметр \"Коэффициент сжимаемости\" несоответсвует"); } if (!Pvxod.CheckIntervalParams(0.01m, 6m)) { return("Pвх параметр \"Давление газа на входе в ДГА\" несоответсвует"); } if (!Pvixod.CheckIntervalParams(0.01m, 4m)) { return("Pвых параметр \"Давление газа на выходе из ДГА\" несоответсвует"); } if (!Q.CheckIntervalParams(100m, 100000000m)) { return("Q параметр \"Расход газа по нитке\" несоответсвует"); } if (!Temperature.CheckIntervalParams(10m, 90m)) { return("t параметр \"Температура\" несоответсвует"); } if ((Nnominal > 0 && EffectProcent == 0) || (Nnominal == 0 && EffectProcent > 0)) { return("Укажите Nnominal и Procent, чтобы узнать эффективность расчета"); } CalculateParams(); return(string.Empty); }
public void ConstructorSecondsTest() { var temperature = new Temperature(100d); Assert.AreEqual(100d, temperature.Kelvin); }
public IOperation GetOperation(Temperature temperature) { Setup(); return(new TemperatureOperation(_model, temperature)); }
/// <summary> /// Updates the state of the bodies atmosphere. Run this after adding removing gasses or modifing albedo. /// @note For info on how I have tweaked this from aurora see: http://en.wikipedia.org/wiki/Stefan%E2%80%93Boltzmann_law /// @todo Calc Hydrosphere changes & update albedo accordingly. /// </summary> public void UpdateState() { if (Exists) { // clear old values. _atmosphereDescriptionInATM = ""; _atmosphereDescriptionInPercent = ""; Pressure = 0; _greenhousePressure = 0; foreach (var gas in _composition) { _atmosphereDescriptionInATM += gas.Value.ToString("N4") + "atm " + gas.Key.Name + " " + gas.Key.ChemicalSymbol + ", "; Pressure += gas.Value; // only add a greenhouse gas if it is not frozen: if (SurfaceTemperature >= gas.Key.BoilingPoint) { // actual greenhouse pressure adjusted by gas GreenhouseEffect. // note that this produces the same affect as in aurora if all GreenhouseEffect bvalue are -1, 0 or 1. _greenhousePressure += (float)gas.Key.GreenhouseEffect * gas.Value; } } if (ParentBody.Type == SystemBody.PlanetType.GasDwarf || ParentBody.Type == SystemBody.PlanetType.GasGiant || ParentBody.Type == SystemBody.PlanetType.IceGiant) { // special gas giant stuff, needed because we do not apply greenhouse factor to them: SurfaceTemperature = ParentBody.BaseTemperature * (1 - Albedo); Pressure = 1; // because thats the deffenition of the surface of these planets, when // atmosphereic pressure = the pressure of earths atmosphere at its surface (what we call 1 atm). } else { // From Aurora: Greenhouse Factor = 1 + (Atmospheric Pressure /10) + Greenhouse Pressure (Maximum = 3.0) GreenhouseFactor = (Pressure * 0.035F) + GreenhousePressure; // note that we do without the extra +1 as it seems to give us better temps. GreenhouseFactor = (float)GMath.Clamp(GreenhouseFactor, -3.0, 3.0); // From Aurora: Surface Temperature in Kelvin = Base Temperature in Kelvin x Greenhouse Factor x Albedo SurfaceTemperature = Temperature.ToKelvin(ParentBody.BaseTemperature); SurfaceTemperature += SurfaceTemperature * GreenhouseFactor * (float)Math.Pow(1 - Albedo, 0.25); // We need to raise albedo to the power of 1/4, see: http://en.wikipedia.org/wiki/Stefan%E2%80%93Boltzmann_law SurfaceTemperature = Temperature.ToCelsius(SurfaceTemperature); } // loop a second time to work out atmo percentages: foreach (var gas in _composition) { if (Pressure != 0) { _atmosphereDescriptionInPercent += (gas.Value / Pressure).ToString("P0") + " " + gas.Key.Name + " " + gas.Key.ChemicalSymbol + ", "; ///< @todo this is not right!! } } // trim trailing", " from the strings. _atmosphereDescriptionInATM = _atmosphereDescriptionInATM.Remove(_atmosphereDescriptionInATM.Length - 2); _atmosphereDescriptionInPercent = _atmosphereDescriptionInPercent.Remove(_atmosphereDescriptionInPercent.Length - 2); } else { // simply apply albedo, see here: http://en.wikipedia.org/wiki/Stefan%E2%80%93Boltzmann_law Pressure = 0; SurfaceTemperature = Temperature.ToKelvin(ParentBody.BaseTemperature); SurfaceTemperature = SurfaceTemperature * (float)Math.Pow(1 - Albedo, 0.25); // We need to raise albedo to the power of 1/4 _atmosphereDescriptionInATM = "None"; _atmosphereDescriptionInPercent = "None"; } }
internal override Temperature GetTemperature(byte[] readBuff) { var temp = readBuff[2] + readBuff[3] * 0.1; return(Temperature.FromDegreesCelsius(temp)); }
public void TemperatureIsCalculatedCorrectly(double expected, double pressure, double seaLevelPressure, double altitude) { Temperature temperature = WeatherHelper.CalculateTemperature(Pressure.FromHectopascals(pressure), Pressure.FromHectopascals(seaLevelPressure), Length.FromMeters(altitude)); Assert.Equal(expected, Math.Round(temperature.DegreesCelsius, 0)); }
/// <inheritdoc /> public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { var stringValue = reader.Value as string; return(Temperature.Parse(stringValue, serializer.Culture)); }
public void CompareToThrowsOnNull() { Temperature kelvin = Temperature.FromKelvins(1); Assert.Throws <ArgumentNullException>(() => kelvin.CompareTo(null)); }
public void EqualsReturnsFalseOnNull() { Temperature kelvin = Temperature.FromKelvins(1); Assert.False(kelvin.Equals(null)); }
/// <summary> /// Main entry point for the program. /// </summary> public static void Main() { Console.WriteLine("Hello BME680!"); // The I2C bus ID on the Raspberry Pi 3. const int busId = 1; // set this to the current sea level pressure in the area for correct altitude readings var defaultSeaLevelPressure = WeatherHelper.MeanSeaLevel; var i2cSettings = new I2cConnectionSettings(busId, Bme680.DefaultI2cAddress); var i2cDevice = I2cDevice.Create(i2cSettings); using (var bme680 = new Bme680(i2cDevice, Temperature.FromDegreesCelsius(20.0))) { while (true) { // get the time a measurement will take with the current settings var measurementDuration = bme680.GetMeasurementDuration(bme680.HeaterProfile); // 10 consecutive measurement with default settings for (var i = 0; i < 10; i++) { // This instructs the sensor to take a measurement. bme680.SetPowerMode(Bme680PowerMode.Forced); // wait while measurement is being taken Thread.Sleep(measurementDuration.ToTimeSpan()); // Print out the measured data bme680.TryReadTemperature(out var tempValue); bme680.TryReadPressure(out var preValue); bme680.TryReadHumidity(out var humValue); bme680.TryReadGasResistance(out var gasResistance); var altValue = WeatherHelper.CalculateAltitude(preValue, defaultSeaLevelPressure, tempValue); Console.WriteLine($"Gas resistance: {gasResistance:0.##}Ohm"); Console.WriteLine($"Temperature: {tempValue.DegreesCelsius:0.#}\u00B0C"); Console.WriteLine($"Pressure: {preValue.Hectopascals:0.##}hPa"); Console.WriteLine($"Altitude: {altValue:0.##}m"); Console.WriteLine($"Relative humidity: {humValue:0.#}%"); // WeatherHelper supports more calculations, such as saturated vapor pressure, actual vapor pressure and absolute humidity. Console.WriteLine($"Heat index: {WeatherHelper.CalculateHeatIndex(tempValue, humValue).DegreesCelsius:0.#}\u00B0C"); Console.WriteLine($"Dew point: {WeatherHelper.CalculateDewPoint(tempValue, humValue).DegreesCelsius:0.#}\u00B0C"); // when measuring the gas resistance on each cycle it is important to wait a certain interval // because a heating plate is activated which will heat up the sensor without sleep, this can // falsify all readings coming from the sensor Thread.Sleep(1000); } // change the settings bme680.TemperatureSampling = Sampling.HighResolution; bme680.HumiditySampling = Sampling.UltraHighResolution; bme680.PressureSampling = Sampling.Skipped; bme680.ConfigureHeatingProfile(Bme680HeaterProfile.Profile2, Temperature.FromDegreesCelsius(280), Duration.FromMilliseconds(80), Temperature.FromDegreesCelsius(24)); bme680.HeaterProfile = Bme680HeaterProfile.Profile2; measurementDuration = bme680.GetMeasurementDuration(bme680.HeaterProfile); // 10 consecutive measurements with custom settings for (int i = 0; i < 10; i++) { // perform the measurement bme680.SetPowerMode(Bme680PowerMode.Forced); Thread.Sleep(measurementDuration.ToTimeSpan()); // Print out the measured data bme680.TryReadTemperature(out var tempValue); bme680.TryReadPressure(out var preValue); bme680.TryReadHumidity(out var humValue); bme680.TryReadGasResistance(out var gasResistance); var altValue = WeatherHelper.CalculateAltitude(preValue, defaultSeaLevelPressure, tempValue); Console.WriteLine($"Gas resistance: {gasResistance:0.##}Ohm"); Console.WriteLine($"Temperature: {tempValue.DegreesCelsius:0.#}\u00B0C"); Console.WriteLine($"Pressure: {preValue.Hectopascals:0.##}hPa"); Console.WriteLine($"Altitude: {altValue:0.##}m"); Console.WriteLine($"Relative humidity: {humValue:0.#}%"); // WeatherHelper supports more calculations, such as saturated vapor pressure, actual vapor pressure and absolute humidity. Console.WriteLine($"Heat index: {WeatherHelper.CalculateHeatIndex(tempValue, humValue).DegreesCelsius:0.#}\u00B0C"); Console.WriteLine($"Dew point: {WeatherHelper.CalculateDewPoint(tempValue, humValue).DegreesCelsius:0.#}\u00B0C"); Thread.Sleep(1000); } // reset will change settings back to default bme680.Reset(); } } }
public void TemperatureFromRankineTest() { var temperature = Temperature.FromRankine(100d); Assert.AreEqual(100, temperature.Rankine, MaxDelta); }
public void AltitudeIsCalculatedCorrectly(double expected, double hpa, double seaLevelHpa, double celsius) { Length altitude = WeatherHelper.CalculateAltitude(Pressure.FromHectopascals(hpa), Pressure.FromHectopascals(seaLevelHpa), Temperature.FromDegreesCelsius(celsius)); Assert.Equal(expected, Math.Round(altitude.Meters, 2)); }
public void EqualsReturnsFalseOnTypeMismatch() { Temperature kelvin = Temperature.FromKelvins(1); Assert.False(kelvin.Equals(new object())); }
public void TemperatureFromDelisleTest() { var temperature = Temperature.FromDelisle(100d); Assert.AreEqual(100d, temperature.Delisle, MaxDelta); }
public void TemperatureFromNewtonTest() { var temperature = Temperature.FromNewton(100d); Assert.AreEqual(100d, temperature.Newton, MaxDelta); }
public void TemperatureFromRømerTest() { var temperature = Temperature.FromRømer(100d); Assert.AreEqual(100d, temperature.Rømer, MaxDelta); }
public void DewPointIsCalculatedCorrectly(double expected, double fahrenheit, double relativeHumidity) { Temperature dewPoint = WeatherHelper.CalculateDewPoint(Temperature.FromDegreesFahrenheit(fahrenheit), RelativeHumidity.FromPercent(relativeHumidity)); Assert.Equal(expected, Math.Round(dewPoint.DegreesFahrenheit, 2)); }
public void TemperatureInFahrenheitTooLow_ThrowsException() { ArgumentOutOfRangeException ex = Assert.Throws <ArgumentOutOfRangeException>(() => Temperature.CreateFromFahrenheit(-1000.0)); Assert.Equal("temperature", ex.ParamName); }