public MainWindow() { InitializeComponent(); //this.CoursePart.ImageSource = new BitmapImage(new Uri("book-icon.png", UriKind.Relative)); //先将图片右键生成操作设置成resource this.TeacherPart.ImageSource = new BitmapImage(new Uri("ceateacher.png", UriKind.Relative)); this.RoomPart.ImageSource = new BitmapImage(new Uri("ceaclass.png", UriKind.Relative)); this.StudentPart.ImageSource = new BitmapImage(new Uri("ceastudent.png", UriKind.Relative)); this.TeacherPart.SelectedImageSource = new BitmapImage(new Uri("ceateacherselected.png", UriKind.Relative)); this.RoomPart.SelectedImageSource = new BitmapImage(new Uri("ceaclassselected.png", UriKind.Relative)); this.StudentPart.SelectedImageSource = new BitmapImage(new Uri("ceastudentselected.png", UriKind.Relative)); //this.CoursePart.ButtonClick += CoursePart_ButtonClick; this.RoomPart.ButtonClick += RoomPart_ButtonClick; this.TeacherPart.ButtonClick += TeacherPart_ButtonClick; this.StudentPart.ButtonClick += StudentPart_ButtonClick; imageWX.Source = new BitmapImage(new Uri("Images/ceawxgzh.png", UriKind.Relative)); if (System.Configuration.ConfigurationManager.AppSettings["IsDev"] == "true") { this.Topmost = false; } //时间天气信息 string weatherInfo = WeatherHelper.GetWeather(); this.txtDate.Text = DateTime.Now.ToString("yyyy年 MM月dd日"); this.txtTime.Text = DateTime.Now.ToString("HH:mm"); this.txtWeather.Text = weatherInfo; aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent); aTimer.Interval = 1000 * 60; aTimer.Start(); }
public string GetWeatherForDate(WorldDate date, string context = "Default") { GameLocation.LocationContext ctx; switch (context) { case "Default": ctx = GameLocation.LocationContext.Default; break; case "Island": ctx = GameLocation.LocationContext.Island; break; case "Desert": return("Sun"); default: throw new ArgumentException("Invalid location context"); } int weather = Mod.Weather.GetWeatherForDate(Mod.GetBaseWorldSeed(), date, ctx); return(WeatherHelper.GetWeatherStringID(weather)); }
public IActionResult Post([FromBody] WeatherReport report) { if (report == null) { return(BadRequest()); } DateTime reportDate; bool isDate; WeatherHelper.CheckInputDate(report.DATE, out reportDate, out isDate); if (!isDate) { return(BadRequest("Enter valid date in YYYYMMDD format")); } if (db.dailyWeather.Any(x => x.DATE == report.DATE)) { return(BadRequest("Already Exists")); } db.dailyWeather.Add(report); db.SaveChanges(); return(CreatedAtAction("Get", new { date = report.DATE }, new { DATE = report.DATE })); }
public static void Main(string[] args) { I2cConnectionSettings settings = new I2cConnectionSettings(1, Si7021.DefaultI2cAddress); I2cDevice device = I2cDevice.Create(settings); using (Si7021 sensor = new Si7021(device, Resolution.Resolution1)) { while (true) { var tempValue = sensor.Temperature; var humValue = sensor.Humidity; Console.WriteLine($"Temperature: {tempValue.DegreesCelsius:0.#}\u00B0C"); Console.WriteLine($"Relative humidity: {humValue.Percent: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"); Console.WriteLine(); Thread.Sleep(1000); } } }
public static void GetWeather() { var data = WeatherHelper.GetWeather(); }
/// <summary> /// Calculates the pressure at sea level when given a known altitude in meter /// </summary> /// <param name="altitude" > /// Altitude in meters /// </param> /// <returns> /// Pressure /// </returns> public Pressure ReadSeaLevelPressure(double altitude = 0.0) { return(WeatherHelper.CalculateSeaLevelPressure(ReadPressure(), altitude, ReadTemperature())); }
public HttpResponseMessage GetHour(int?hour = null) { // this needs to get called hourly at about 15 minutes past the hour; set pull time in config settings (admin login) and if it's a pull time, it'll post to discord // the local time conversion is in case your server has a different time zone than your local time - forecast times are all local time DateTime thisTime = DateTime.Now; TimeZoneInfo tst = TimeZoneInfo.FindSystemTimeZoneById(Resources.TimeZoneId); var now = DateTime.Now.ToUniversalTime(); var localTime = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(now, tst.Id); var date = localTime.Date; var localHour = localTime.Hour; int fch = int.Parse(db.ConfigSettings.Find(1).Value); WeatherEntry we = new WeatherEntry(); if (hour != null) { we = db.WeatherEntries.Where(w => w.Date == date && w.Hour == hour).FirstOrDefault(); } else { if (localHour == fch || localHour == (fch + 8) || localHour == (fch + 16)) { we = db.WeatherEntries.OrderByDescending(w => w.Id).FirstOrDefault(); } else { return(Request.CreateResponse(HttpStatusCode.OK, "not time yet")); } } // get WeatherEntry (and all values) for today's date and the specified hour if (we != null && we.WeatherValues != null) { var wv = we.WeatherValues.ToArray(); // then, create forecast StringBuilder forecast = new StringBuilder(); forecast.AppendLine("Forecast at " + TimeZoneInfo.ConvertTimeBySystemTimeZoneId(now, tst.Id).ToString("h:mm tt")); for (var i = 0; i < 8; i++) { var w = wv[i]; var types = new List <string>(); var tps = w.PgoWeather.PokemonTypes.ToArray(); for (var j = 0; j < tps.Length; j++) { types.Add(tps[j].Name); } var ts = types.ToArray(); int forecastHour = w.DateTime.Hour; string fcTime = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(w.DateTime, tst.Id).ToString("h:mm tt"); string fc1 = fcTime + ": " + w.PgoWeather.Description; string fc2 = "Boosted types: " + string.Join(", ", ts); string fc3 = "---"; forecast.AppendLine(fc1); forecast.AppendLine(fc2); forecast.AppendLine(fc3); } forecast.AppendLine("=^..^= =^..^= =^..^="); // then, post to Discord DiscordJson js = new DiscordJson() { content = forecast.ToString() }; string url = Resources.DiscordWebhook; int firstHour = wv[0].DateTime.Hour; string json = JsonConvert.SerializeObject(js); using (WebClient client = new WebClient()) { client.Headers.Add(HttpRequestHeader.ContentType, "application/json"); var resp = client.UploadString(url, json); } // now clean up weather values table (remove old values) Task.Factory.StartNew(() => WeatherHelper.RemoveStale()); //WeatherHelper.RemoveStale(); // finally, return success return(Request.CreateResponse(HttpStatusCode.OK, firstHour)); } return(Request.CreateResponse(HttpStatusCode.OK, "no valid forecast for this date/time")); }
/// <summary> /// Entry point for example program /// </summary> /// <param name="args">Command line arguments</param> public static void Main(string[] args) { Console.WriteLine("Hello Bme280!"); // 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, Bme280.DefaultI2cAddress); var i2cDevice = I2cDevice.Create(i2cSettings); var i2CBmpe80 = new Bme280(i2cDevice); using (i2CBmpe80) { while (true) { // set higher sampling i2CBmpe80.TemperatureSampling = Sampling.LowPower; i2CBmpe80.PressureSampling = Sampling.UltraHighResolution; i2CBmpe80.HumiditySampling = Sampling.Standard; // set mode forced so device sleeps after read i2CBmpe80.SetPowerMode(Bmx280PowerMode.Forced); // wait for measurement to be performed var measurementTime = i2CBmpe80.GetMeasurementDuration(); Thread.Sleep(measurementTime); // read values i2CBmpe80.TryReadTemperature(out var tempValue); i2CBmpe80.TryReadPressure(out var preValue); i2CBmpe80.TryReadHumidity(out var humValue); // Note that if you already have the pressure value and the temperature, you could also calculate altitude by using // var altValue = WeatherHelper.CalculateAltitude(preValue, defaultSeaLevelPressure, tempValue) which would be more performant. i2CBmpe80.TryReadAltitude(defaultSeaLevelPressure, out var altValue); 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); // change sampling and filter i2CBmpe80.TemperatureSampling = Sampling.UltraHighResolution; i2CBmpe80.PressureSampling = Sampling.UltraLowPower; i2CBmpe80.HumiditySampling = Sampling.UltraLowPower; i2CBmpe80.FilterMode = Bmx280FilteringMode.X2; // set mode forced and read again i2CBmpe80.SetPowerMode(Bmx280PowerMode.Forced); // wait for measurement to be performed measurementTime = i2CBmpe80.GetMeasurementDuration(); Thread.Sleep(measurementTime); // read values i2CBmpe80.TryReadTemperature(out tempValue); i2CBmpe80.TryReadPressure(out preValue); i2CBmpe80.TryReadHumidity(out humValue); // Note that if you already have the pressure value and the temperature, you could also calculate altitude by using // var altValue = WeatherHelper.CalculateAltitude(preValue, defaultSeaLevelPressure, tempValue) which would be more performant. i2CBmpe80.TryReadAltitude(defaultSeaLevelPressure, out altValue); 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(5000); } } }
/// <summary> /// Calculates the altitude in meters from the specified sea-level pressure. /// </summary> /// <param name="seaLevelPressure"> /// Sea-level pressure /// </param> /// <returns> /// Height above sea level /// </returns> public Length ReadAltitude(Pressure seaLevelPressure) { return(WeatherHelper.CalculateAltitude(ReadPressure(), seaLevelPressure, ReadTemperature())); }
/// <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)) { 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); // 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, 280, 80, 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); // 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(); } } }
private void ReadSensor(object state) { if (!_debugMode && _bme280 == null) { return; } var readingOK = true; if (!_debugMode) { try { // set mode forced and read again _bme280.SetPowerMode(Bmx280PowerMode.Forced); // wait for measurement to be performed var measurementTime = _bme280.GetMeasurementDuration(); Thread.Sleep(measurementTime); // read values _bme280.TryReadTemperature(out var tempValue); _bme280.TryReadPressure(out var preValue); _bme280.TryReadHumidity(out var humValue); var itsRaining = DigitalIOConnector.Instance.ReadRainSensorDetectsRain(); var rainCorrected = false; if (itsRaining && tempValue.DegreesCelsius >= _maxTemperatureForRain) { itsRaining = false; rainCorrected = true; _logger.Information("Raining sensor corrected ({Temp}° greater than {MaxTempRain}°)", tempValue.DegreesCelsius, _maxTemperatureForRain); } _lastReadingPoint = new Measurement() { TimeStamp = DateTime.Now, Temperature = tempValue.DegreesCelsius, Pressure = preValue.Hectopascals, Humidity = humValue.Percent, DewPoint = WeatherHelper.CalculateDewPoint(tempValue, humValue).DegreesCelsius, Raining = itsRaining, RainCorrected = rainCorrected }; } catch (Exception ex) { readingOK = false; _lastReadingPoint = null; _logger.Error(ex, "Error while reading"); } } else { _lastReadingPoint = new Measurement() { TimeStamp = DateTime.Now, Temperature = (double)_random.Next(1000, 4000) / 100d, Pressure = (double)_random.Next(95000, 110000) / 100d, Humidity = (double)_random.Next(5000, 9000) / 100d, DewPoint = 12.12345d, Raining = _random.Next(0, 1) == 1 }; } OnPropertyChanged(readingOK ? "Reading done" : "Reading Error"); }
public void SaturatedVaporPressureOverIce(double expected, double celsius) { var saturatedVaporPressure = WeatherHelper.CalculateSaturatedVaporPressureOverIce(Temperature.FromDegreesCelsius(celsius)); Assert.Equal(expected, saturatedVaporPressure.Pascals, 1); }
public void HeatIndexIsCalculatedCorrectly(double expected, double celsius, double relativeHumidity) { var heatIndex = WeatherHelper.CalculateHeatIndex(Temperature.FromDegreesCelsius(celsius), Ratio.FromPercent(relativeHumidity)); Assert.Equal(expected, Math.Round(heatIndex.DegreesCelsius)); }
public void TemperatureIsCalculatedCorrectly(double expected, double pressure, double seaLevelPressure, double altitude) { var temperature = WeatherHelper.CalculateTemperature(Pressure.FromHectopascals(pressure), Pressure.FromHectopascals(seaLevelPressure), Length.FromMeters(altitude)); Assert.Equal(expected, Math.Round(temperature.DegreesCelsius, 0)); }
public void PressureIsCalculatedCorrectly(double expected, double seaLevelPressure, double altitude, double celsius) { var pressure = WeatherHelper.CalculatePressure(Pressure.FromHectopascals(seaLevelPressure), Length.FromMeters(altitude), Temperature.FromDegreesCelsius(celsius)); Assert.Equal(expected, Math.Round(pressure.Hectopascals, 2)); }
public void AltitudeIsCalculatedCorrectly(double expected, double hpa, double seaLevelHpa, double celsius) { var altitude = WeatherHelper.CalculateAltitude(Pressure.FromHectopascals(hpa), Pressure.FromHectopascals(seaLevelHpa), Temperature.FromDegreesCelsius(celsius)); Assert.Equal(expected, Math.Round(altitude.Meters, 2)); }
/// <inheritdoc/> public override void Initialize() { this.LogStartInitialization(); this.i2cDevice = this.Controller.GetI2CConnection(this.DeviceId); this.sensor = new Bme280(this.i2cDevice) { TemperatureSampling = Sampling.LowPower, PressureSampling = Sampling.UltraHighResolution, HumiditySampling = Sampling.Standard, }; var readResult = this.sensor.ReadStatus(); this.LogMessage($"BME280 status {readResult}"); var result = this.sensor.Read(); if (result.Humidity.HasValue && result.Pressure.HasValue && result.Temperature.HasValue) { var pressure = result.Pressure.Value; var temperature = new Temperature(result.Temperature.Value.DegreesCelsius - this.calibrationOffset, UnitsNet.Units.TemperatureUnit.DegreeCelsius); var humidity = result.Humidity.Value; var actualAltitude = new Length(this.altitudeInMeters, UnitsNet.Units.LengthUnit.Meter); var calculatedAltitude = WeatherHelper.CalculateAltitude(pressure, WeatherHelper.MeanSeaLevel, temperature); double absHumidity = WeatherHelper.CalculateAbsoluteHumidity(temperature, humidity).GramsPerCubicMeter; double dewPoint = WeatherHelper.CalculateDewPoint(temperature, humidity).DegreesCelsius; double heatIndex = WeatherHelper.CalculateHeatIndex(temperature, humidity).DegreesCelsius; double vapourPressure = WeatherHelper.CalculateActualVaporPressure(temperature, humidity).Hectopascals; double barometricPressure = WeatherHelper.CalculateBarometricPressure(pressure, temperature, actualAltitude, humidity).Hectopascals; double vapourPressureOverIce = WeatherHelper.CalculateSaturatedVaporPressureOverIce(temperature).Hectopascals; double vapourPressureOverWater = WeatherHelper.CalculateSaturatedVaporPressureOverWater(temperature).Hectopascals; double seaLevelPressure = WeatherHelper.CalculateSeaLevelPressure(pressure, actualAltitude, temperature).Hectopascals; this.LogMessage($"Temperature: {temperature.DegreesCelsius:0.#}\u00B0C"); this.LogMessage($"Pressure: {pressure.Hectopascals:0.##}hPa"); this.LogMessage($"Barometric Pressure: {barometricPressure:0.##}hPa"); this.LogMessage($"Sea level Pressure: {seaLevelPressure:0.##}hPa"); this.LogMessage($"Over ice Pressure: {vapourPressureOverIce:0.##}hPa"); this.LogMessage($"Over water Pressure: {vapourPressureOverWater:0.##}hPa"); this.LogMessage($"Relative humidity: {humidity.Percent:0.#}%"); this.LogMessage($"Absolute humidity: {absHumidity:0.#}g/m3"); this.LogMessage($"Vapour pressure: {vapourPressure:0.#}hPa"); this.LogMessage($"Calculate altitude: {calculatedAltitude.Meters:0.##}m"); this.LogMessage($"Actual altitude: {actualAltitude.Meters:0.##}m"); this.LogMessage($"Heat index: {heatIndex:0.#}\u00B0C"); this.LogMessage($"Dew point: {dewPoint:0.#}\u00B0C"); Thread.Sleep(1000); // set sane defaults this.sensor.TemperatureSampling = Sampling.UltraLowPower; this.sensor.PressureSampling = Sampling.UltraLowPower; this.sensor.HumiditySampling = Sampling.UltraLowPower; this.sensor.FilterMode = Bmx280FilteringMode.Off; this.sensor.SetPowerMode(Iot.Device.Bmxx80.PowerMode.Bmx280PowerMode.Forced); this.IsInitialized = true; this.LogStartSuccess(); } this.LogError("Couldn't read from BME280"); }
public async void GetCurrentCondition() { CurrentCondition = await WeatherHelper.GetCurrentCondition(SelectedCity.Key); }
public void ActualVaporPressureIsCalculatedCorrectly(double expected, double celsius, double relativeHumidity) { var actualVaporPressure = WeatherHelper.CalculateActualVaporPressure(Temperature.FromDegreesCelsius(celsius), Ratio.FromPercent(relativeHumidity)); Assert.Equal(expected, Math.Round(actualVaporPressure.Pascals, 0)); }
/// <summary> /// Entry point for example program /// </summary> /// <param name="args">Command line arguments</param> public static void StartBmp(string[] args) { Console.WriteLine("Hello Bmp280!"); Length stationHeight = Length.FromMeters(640); // Elevation of the sensor // bus id on the raspberry pi 3 and 4 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, Bmp280.DefaultI2cAddress); var i2cDevice = I2cDevice.Create(i2cSettings); var i2CBmp280 = new Bmp280(i2cDevice); using (i2CBmp280) { while (true) { // set higher sampling i2CBmp280.TemperatureSampling = Sampling.LowPower; i2CBmp280.PressureSampling = Sampling.UltraHighResolution; // set mode forced so device sleeps after read i2CBmp280.SetPowerMode(Bmx280PowerMode.Forced); // wait for measurement to be performed var measurementTime = i2CBmp280.GetMeasurementDuration(); Thread.Sleep(measurementTime); // read values i2CBmp280.TryReadTemperature(out var tempValue); Console.WriteLine($"Temperature: {tempValue.DegreesCelsius} \u00B0C"); i2CBmp280.TryReadPressure(out var preValue); Console.WriteLine($"Pressure: {preValue.Hectopascals} hPa"); // Note that if you already have the pressure value and the temperature, you could also calculate altitude by using // double altValue = WeatherHelper.CalculateAltitude(preValue, defaultSeaLevelPressure, tempValue) which would be more performant. i2CBmp280.TryReadAltitude(out var altValue); Console.WriteLine($"Calculated Altitude: {altValue} m"); Thread.Sleep(1000); // change sampling rate i2CBmp280.TemperatureSampling = Sampling.UltraHighResolution; i2CBmp280.PressureSampling = Sampling.UltraLowPower; i2CBmp280.FilterMode = Bmx280FilteringMode.X4; // set mode forced and read again i2CBmp280.SetPowerMode(Bmx280PowerMode.Forced); // wait for measurement to be performed measurementTime = i2CBmp280.GetMeasurementDuration(); Thread.Sleep(measurementTime); // read values i2CBmp280.TryReadTemperature(out tempValue); Console.WriteLine($"Temperature: {tempValue.DegreesCelsius} \u00B0C"); i2CBmp280.TryReadPressure(out preValue); Console.WriteLine($"Pressure: {preValue.Hectopascals} hPa"); // This time use altitude calculation altValue = WeatherHelper.CalculateAltitude(preValue, defaultSeaLevelPressure, tempValue); Console.WriteLine($"Calculated Altitude: {altValue} m"); // Calculate the barometric (corrected) pressure for the local position. // Change the stationHeight value above to get a correct reading, but do not be tempted to insert // the value obtained from the formula above. Since that estimates the altitude based on pressure, // using that altitude to correct the pressure won't work. var correctedPressure = WeatherHelper.CalculateBarometricPressure(preValue, tempValue, stationHeight); Console.WriteLine($"Pressure corrected for altitude {stationHeight.Meters} m (with average humidity): {correctedPressure.Hectopascals} hPa"); Thread.Sleep(5000); } } }
public ActionResult Index() { var date = WeatherHelper.GetWeatcherByCityName("柳州"); return(View(date)); }
public void DewPointIsCalculatedCorrectly(double expected, double fahrenheit, double relativeHumidity) { var dewPoint = WeatherHelper.CalculateDewPoint(Temperature.FromDegreesFahrenheit(fahrenheit), Ratio.FromPercent(relativeHumidity)); Assert.Equal(expected, Math.Round(dewPoint.DegreesFahrenheit, 2)); }
private void DisplayWeather(GenericWeather weather) { CurrentTemperature = $"{((Settings.IsFahrenheit) ? Math.Round(weather.CurrentObservation.Temperature) : Math.Round(WeatherHelper.GetCelsius(weather.CurrentObservation.Temperature)))}{TempUnit}"; if (!Settings.IsFahrenheit) { foreach (var day in weather.Forecast.Days) { day.TemperatureHigh = Math.Round(WeatherHelper.GetCelsius(day.TemperatureHigh)); day.TemperatureLow = Math.Round(WeatherHelper.GetCelsius(day.TemperatureLow)); } } ForecastCollection = weather.Forecast.Days; AttributionText = weather.Source; }
public void AbsoluteHumidityIsCalculatedCorrectly(double expected, double fahrenheit, double relativeHumidity) { var absoluteHumidity = WeatherHelper.CalculateAbsoluteHumidity(Temperature.FromDegreesFahrenheit(fahrenheit), Ratio.FromPercent(relativeHumidity)); Assert.Equal(expected, absoluteHumidity.GramsPerCubicMeter, 0); }
/// <summary> /// Calculates the pressure at sea level when given a known altitude /// </summary> /// <param name="altitude" > /// Altitude in meters /// </param> /// <returns> /// Pressure /// </returns> public Pressure ReadSeaLevelPressure(Length altitude) { return(WeatherHelper.CalculateSeaLevelPressure(ReadPressure(), altitude, ReadTemperature())); }
public void AltitudeIsCalculatedCorrectlyAtMslpAndDefaultTemp(double expected, double hpa) { var altitude = WeatherHelper.CalculateAltitude(Pressure.FromHectopascals(hpa)); Assert.Equal(expected, Math.Round(altitude.Meters, 2)); }
public static void DisplayModes(ArduinoBoard board) { const int Gpio2 = 2; const int MaxMode = 10; Length stationAltitude = Length.FromMeters(650); int mode = 0; var gpioController = board.CreateGpioController(); gpioController.OpenPin(Gpio2); gpioController.SetPinMode(Gpio2, PinMode.Input); CharacterDisplay disp = new CharacterDisplay(board); Console.WriteLine("Display output test"); Console.WriteLine("The button on GPIO 2 changes modes"); Console.WriteLine("Press x to exit"); disp.Output.ScrollUpDelay = TimeSpan.FromMilliseconds(500); AutoResetEvent buttonClicked = new AutoResetEvent(false); void ChangeMode(object sender, PinValueChangedEventArgs pinValueChangedEventArgs) { mode++; if (mode > MaxMode) { // Don't change back to 0 mode = 1; } buttonClicked.Set(); } gpioController.RegisterCallbackForPinValueChangedEvent(Gpio2, PinEventTypes.Falling, ChangeMode); var device = board.CreateI2cDevice(new I2cConnectionSettings(0, Bmp280.DefaultI2cAddress)); Bmp280?bmp; try { bmp = new Bmp280(device); bmp.StandbyTime = StandbyTime.Ms250; bmp.SetPowerMode(Bmx280PowerMode.Normal); } catch (IOException) { bmp = null; Console.WriteLine("BMP280 not available"); } OpenHardwareMonitor hardwareMonitor = new OpenHardwareMonitor(); hardwareMonitor.EnableDerivedSensors(); TimeSpan sleeptime = TimeSpan.FromMilliseconds(500); string modeName = string.Empty; string previousModeName = string.Empty; int firstCharInText = 0; while (true) { if (Console.KeyAvailable && Console.ReadKey(true).KeyChar == 'x') { break; } // Default sleeptime = TimeSpan.FromMilliseconds(500); switch (mode) { case 0: modeName = "Display ready"; disp.Output.ReplaceLine(1, "Button for mode"); // Just text break; case 1: { modeName = "Time"; disp.Output.ReplaceLine(1, DateTime.Now.ToLongTimeString()); sleeptime = TimeSpan.FromMilliseconds(200); break; } case 2: { modeName = "Date"; disp.Output.ReplaceLine(1, DateTime.Now.ToShortDateString()); break; } case 3: modeName = "Temperature / Barometric Pressure"; if (bmp != null && bmp.TryReadTemperature(out Temperature temp) && bmp.TryReadPressure(out Pressure p2)) { Pressure p3 = WeatherHelper.CalculateBarometricPressure(p2, temp, stationAltitude); disp.Output.ReplaceLine(1, string.Format(CultureInfo.CurrentCulture, "{0:s1} {1:s1}", temp, p3)); }
/// <summary> /// Invoked when the application is launched normally by the end user. Other entry points /// will be used such as when the application is launched to open a specific file. /// </summary> /// <param name="e">Details about the launch request and process.</param> protected override async void OnLaunched(LaunchActivatedEventArgs e) { LogService.Write(); // Check if this is the first time the app is being launched // If OnLaunched is called again when the app is still running (e.g. selecting "Switch to" in WDP // while the app is running), the initialization code should not run again if (!(Window.Current.Content is Frame rootFrame)) { // Create a Frame to act as the navigation context and navigate to the first page rootFrame = new Frame(); rootFrame.NavigationFailed += OnNavigationFailed; // Place the frame in the current Window Window.Current.Content = rootFrame; // Try to set the map token from file located in LocalState folder await WeatherHelper.SetMapTokenFromFileAsync("MapToken.config"); // Enable kiosk mode if file is detected Settings.KioskMode = await FileUtil.ReadFileAsync("kiosk_mode") != null; // Use MEF to import features and components from other assemblies in the appx package. foreach (var feature in AppComposer.Imports.Features) { try { LogService.Write($"Loading Feature: {feature.FeatureName}"); feature.OnLoaded(this); } catch (Exception ex) { LogService.Write(ex.ToString()); } } // Enable multi-view MultiViewManager = new MultiViewManager(Window.Current.Dispatcher, ApplicationView.GetForCurrentView().Id); MultiViewManager.ViewAdded += MultiViewManager_ViewAdded; // Subscribe for IoT Hub property updates if available var iotHubService = GetForCurrentContext().GetRegisteredService <IIoTHubService>(); if (iotHubService != null) { iotHubService.DesiredPropertyUpdated += App_DesiredPropertyUpdated; } // Make sure we weren't launched in the background if (e != null && e.PrelaunchActivated == false) { // When the navigation stack isn't restored navigate to the first page, // configuring the new page by passing required information as a navigation // parameter #if !FORCE_OOBE_WELCOME_SCREEN if (ApplicationData.Current.LocalSettings.Values.ContainsKey(Constants.HasDoneOOBEKey)) { rootFrame.Navigate(typeof(MainPage), e.Arguments); } else #endif { rootFrame.Navigate(typeof(OOBEWelcomePage), e.Arguments); } } } // Ensure the current window is active Window.Current.Activate(); // Update asynchronously var updateAsyncTask = NetworkPresenter.UpdateAvailableNetworksAsync(false); }
private async static Task PostWeiboAsync(Weather weather) { string token = ConfigHelper.Get("Weibo:Token"); // weibo token string status = $"{weather.DateTime.ToString("yyyy/MM/dd HH:mm")} {weather.WeatherName}%0a" + $"温度:{Math.Round(weather.Temperature, 1)} ℃ 体感温度:{Math.Round(WeatherHelper.CalHeatIndex(weather.Temperature, weather.Humidity), 1)} ℃%0a" + $"相对湿度:{Math.Round(weather.Humidity)} %25%0a" + $"气压:{Math.Round(weather.Pressure / 100, 2)} hPa%0a" + $"{ConfigHelper.Get("Weibo:StatusUrl")}"; using HttpClient client = new HttpClient(); using FileStream imageStream = File.OpenRead(ConfigHelper.Get("UsbCamera:ImagePath")); MultipartFormDataContent content = new MultipartFormDataContent { { new StringContent(token, Encoding.UTF8), "access_token" }, { new StringContent(status, Encoding.UTF8), "status" }, { new StreamContent(imageStream, (int)imageStream.Length), "pic", "image.jpg" } }; HttpResponseMessage response = await client.PostAsync("https://api.weibo.com/2/statuses/share.json", content); }
public void AbsoluteHumidityIsCalculatedCorrectly(double expected, double fahrenheit, double relativeHumidity) { var absoluteHumidity = WeatherHelper.CalculateAbsoluteHumidity(Temperature.FromFahrenheit(fahrenheit), relativeHumidity); Assert.Equal(expected, Math.Round(absoluteHumidity, 0)); }