public static void Main(string[] args) { WeatherData weatherData = new WeatherData(); CurrentConditionsDisplay currentDisplay = new CurrentConditionsDisplay(weatherData); weatherData.setMeasurements(80, 65, 30.4f); weatherData.setMeasurements(82, 70, 29.2f); weatherData.setMeasurements(78, 90, 29.2f); }
public void UpdateDisplay2() { var weatherData = new WeatherData(); weatherData.SetMeasurements(82, 70, 29.2f); Assert.IsTrue(sw.ToString().Contains("Current conditions: 82F degrees and 70% humidity")); Assert.IsTrue(sw.ToString().Contains("Watch out for cooler, rainy weather")); Assert.IsTrue(sw.ToString().Contains("Avg/Max/Min temperature = 82.00F/82F/82F")); }
public void UpdateDisplay1() { var weatherData = new WeatherData(); weatherData.SetMeasurements(80, 65, 30.4f); Assert.IsTrue(sw.ToString().Contains("Current conditions: 80F degrees and 65% humidity")); Assert.IsTrue(sw.ToString().Contains("Improving weather on the way!")); Assert.IsTrue(sw.ToString().Contains("Avg/Max/Min temperature = 80.00F/80F/80F")); }
static void Main(string[] args) { var weatherData = new WeatherData(); var currentConditionsDisplay = new CurrentConditionasDisplay(weatherData); var heatIndexDisplay = new HeatIndexDisplay(weatherData); weatherData.SetMeasurement(80, 45,34); weatherData.SetMeasurement(56, 33, 23); weatherData.SetMeasurement(11, 45, 55); Console.ReadKey(); }
public void Main(string[] args) { WeatherData weatherData = new WeatherData(); CurrentConditionsDisplay currentDisplay = new CurrentConditionsDisplay(weatherData); StatisticsDisplay statisticsDisplay = new StatisticsDisplay(weatherData); ForecastDisplay forecastDisplay = new ForecastDisplay(weatherData); HeatIndexDisplay heatIndexDisplay = new HeatIndexDisplay(weatherData); weatherData.SetMeasurements(80, 65, 30.4f); weatherData.SetMeasurements(82, 70, 29.2f); weatherData.SetMeasurements(78, 90, 29.2f); }
static async Task SendEvent(DeviceClient deviceClient) { string[] filePath = Directory.GetFiles(@"C:\Weblog\", "*.csv"); string csv_file_path = string.Empty; int size = filePath.Length; for (int i = 0; i < size; i++) { Console.WriteLine(filePath[i]); csv_file_path = filePath[i]; } DataTable csvData = GetDataTableFromCSVFile(csv_file_path); Console.WriteLine("Rows count:" + csvData.Rows.Count); DataTable table = csvData; foreach (DataRow row in table.Rows) { foreach (var item in row.ItemArray) data = item.ToString(); Console.Write(data); try { foreach (DataRow rows in table.Rows) { var info = new WeatherData { weatherDate = rows.ItemArray[0].ToString(), weatherTime = rows.ItemArray[1].ToString(), Type = rows.ItemArray[2].ToString(), AirTemperature = rows.ItemArray[3].ToString(), RelativeHumidity = rows.ItemArray[4].ToString(), WindSpeed = rows.ItemArray[5].ToString(), SolarRadiation = rows.ItemArray[6].ToString(), Temperature = rows.ItemArray[7].ToString(), }; var serializedString = JsonConvert.SerializeObject(info); var message = data; Console.WriteLine("{0}> Sending events: {1}", DateTime.Now.ToString(), serializedString.ToString()); await deviceClient.SendEventAsync(new Message(Encoding.UTF8.GetBytes(serializedString.ToString()))); } } catch (Exception ex) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("{ 0} > Exception: { 1}", DateTime.Now.ToString(), ex.Message); Console.ResetColor(); } } Console.WriteLine("Press Ctrl - C to stop the sender process"); Console.WriteLine("Press Enter to start now"); Console.ReadLine(); }
static void Main(string[] args) { WeatherData weatherData = new WeatherData(); // CurrentConditionsDisplay currentDisplay = new CurrentConditionsDisplay(weatherData); StatisticsDisplay statisticsDisplay = new StatisticsDisplay(weatherData); ForecastDisplay forecastDisplay = new ForecastDisplay(weatherData); // Simula alterações das medições weatherData.SetMeasurements(80, 65, 30.4); weatherData.SetMeasurements(82, 70, 29.2); weatherData.SetMeasurements(78, 90, 29.2); Console.ReadKey(); }
/////////////////////////////////////////////////////////////////////// // http://developer.yahoo.com/weather/ public static WeatherData GetWeather(String woeid) { var url = String.Format("http://weather.yahooapis.com/forecastrss?u=c&w={0}", woeid); _logger.Debug("GetWeather({0})", url); XElement elem = XDocument.Load(url).Root; // find our elements of interest (quick-n-dirty) XElement cond = elem.Element("yweather:condition"); XElement wind = elem.Element("yweather:wind"); XElement atmos = elem.Element("yweather:atmosphere"); var data = new WeatherData { Temperature = int.Parse(cond.Attribute("temp").Value), Humidity = int.Parse(atmos.Attribute("humidity").Value), Pressure = decimal.Parse(atmos.Attribute("pressure").Value), WindSpeed = int.Parse(wind.Attribute("speed").Value) }; return data; }
public override async Task GetTownWeatherStream( IAsyncStreamReader <TownWeatherRequest> requestStream, IServerStreamWriter <TownWeatherForecast> responseStream, ServerCallContext context) { var rng = new Random(); var now = DateTime.UtcNow; // we'll use a channel here to handle in-process 'messages' concurrently being written to and read from the channel. var channel = Channel.CreateUnbounded <TownWeatherForecast>(); // background task which uses async streams to write each forecast from the channel to the response steam. _ = Task.Run(async() => { await foreach (var forecast in channel.Reader.ReadAllAsync()) { await responseStream.WriteAsync(forecast); } }); // a list of tasks handling requests concurrently var getTownWeatherRequestTasks = new List <Task>(); try { // async streams used to process each request from the stream as they are receieved await foreach (var request in requestStream.ReadAllAsync()) { _logger.LogInformation($"Getting weather for {request.TownName}"); getTownWeatherRequestTasks.Add(GetTownWeatherAsync(request.TownName)); // start and add the request handling task } _logger.LogInformation("Client finished streaming"); } catch (Exception e) { _logger.LogError(e, "An exception occurred"); } // wait for all responses to be written to the channel // from the concurrent tasks handling each request await Task.WhenAll(getTownWeatherRequestTasks); channel.Writer.TryComplete(); // wait for all responses to be read from the channel and streamed as responses await channel.Reader.Completion; _logger.LogInformation("Completed response streaming"); // a local function which defines a task to handle a town forecast request // it produces 10 forecasts for each town, simulating a 0.5s time to gather each forecast // multiple instances of this will run concurrently for each recieved request async Task GetTownWeatherAsync(string town) { for (var i = 0; i < 10; i++) { var forecast = new WeatherData { DateTimeStamp = Timestamp.FromDateTime(now.AddDays(i)), TemperatureC = rng.Next(-20, 55), Summary = Summaries[rng.Next(Summaries.Length)] }; await Task.Delay(500); // Gotta look busy // write the forecast to the channel which will be picked up concurrently by the channel reading background task await channel.Writer.WriteAsync(new TownWeatherForecast { TownName = town, WeatherData = forecast }); } } }
static void Main(string[] args) { Location newlocation = new Location("london"); IWeatherDataService open_map_weather = WeatherDataServiceFactory.getWeatherDataService(WeatherDataServiceFactory.OPEN_WEATHER_MAP); WeatherData opachki = open_map_weather.getWeatherData(newlocation); }
/// <summary> /// Unregisters a subscriber. /// </summary> /// <param name="observer">Observer for unsubscribing.</param> public void Unregister(WeatherData weather) { weather.NewMail -= Update; }
public static WeatherData[] GetBasicData() { WeatherData[] weatherReadings = new WeatherData[10]; weatherReadings[0] = new WeatherData() { City = "Boulder", State = "CO", Date = DateTime.Now, HighTemp = 100, LowTemp = 40 }; weatherReadings[1] = new WeatherData() { City = "Boulder", State = "CO", Date = DateTime.Now.AddMonths(-1), HighTemp = 100, LowTemp = 40 }; weatherReadings[2] = new WeatherData() { City = "Boulder", State = "CO", Date = DateTime.Now, HighTemp = 100, LowTemp = 40 }; weatherReadings[3] = new WeatherData() { City = "Boulder", State = "CO", Date = DateTime.Now.AddMonths(-1), HighTemp = 100, LowTemp = 40 }; weatherReadings[4] = new WeatherData() { City = "Boulder", State = "CO", Date = DateTime.Now, HighTemp = 100, LowTemp = 40 }; weatherReadings[5] = new WeatherData() { City = "Boulder", State = "CO", Date = DateTime.Now.AddMonths(-1), HighTemp = 100, LowTemp = 40 }; weatherReadings[6] = new WeatherData() { City = "Boulder", State = "CO", Date = DateTime.Now, HighTemp = 100, LowTemp = 40 }; weatherReadings[7] = new WeatherData() { City = "Boulder", State = "CO", Date = DateTime.Now.AddMonths(-1), HighTemp = 100, LowTemp = 40 }; weatherReadings[8] = new WeatherData() { City = "Boulder", State = "CO", Date = DateTime.Now, HighTemp = 100, LowTemp = 40 }; weatherReadings[9] = new WeatherData() { City = "Boulder", State = "CO", Date = DateTime.Now.AddMonths(-1), HighTemp = 100, LowTemp = 40 }; return(weatherReadings); }
public Weather(SimpleSubrecord <String> EditorID, RecordReference ImageSpaceModifierSunrise, RecordReference ImageSpaceModifierDay, RecordReference ImageSpaceModifierSunset, RecordReference ImageSpaceModifierNight, RecordReference ImageSpaceModifierHighNoon, RecordReference ImageSpaceModifierMidnight, SimpleSubrecord <String> CloudTextureLayer0, SimpleSubrecord <String> CloudTextureLayer1, SimpleSubrecord <String> CloudTextureLayer2, SimpleSubrecord <String> CloudTextureLayer3, Model Model, SimpleSubrecord <Byte[]> Unknown, CloudLayerSpeed CloudLayerSpeed, CloudLayerColors CloudLayerColors, EnvironmentalColors EnvironmentalColors, WeatherFogDistance WeatherFogDistance, SimpleSubrecord <Byte[]> Unused, WeatherData Data, List <WeatherSound> Sounds) { this.EditorID = EditorID; this.CloudTextureLayer0 = CloudTextureLayer0; this.CloudTextureLayer1 = CloudTextureLayer1; this.CloudTextureLayer2 = CloudTextureLayer2; this.CloudTextureLayer3 = CloudTextureLayer3; this.Unknown = Unknown; this.CloudLayerSpeed = CloudLayerSpeed; this.EnvironmentalColors = EnvironmentalColors; this.WeatherFogDistance = WeatherFogDistance; this.Unused = Unused; this.Data = Data; }
/// <summary>地点情報読み込み処理</summary> /// <param name="pwData">PWeatherDataオブジェクト</param> /// <param name="bStrm">読み取りStream</param> private static void getHourlyData(ref WeatherDataTable pwData, BufferedStream bStrm) { LocationInformation locationInfo = pwData.Location; byte[] buffer; //年月日情報 buffer = new byte[8]; //最終行の場合は終了 bStrm.Read(buffer, 0, 8); string dTime = System.Text.Encoding.GetEncoding(932).GetString(buffer); int year = int.Parse(dTime.Substring(0, 4)); int month = int.Parse(dTime.Substring(4, 2)); int day = int.Parse(dTime.Substring(6, 2)); DateTime cTime = new DateTime(year, month, day, 1, 0, 0); //1時間データまでシーク bStrm.Seek(2, SeekOrigin.Current); //24時間データを取得 buffer = new byte[56]; WeatherData wd = new WeatherData(); wd.Source = WeatherData.DataSource.CalculatedValue; bool sunRise = false; bool hasDR = false; for (int i = 0; i < 24; i++) { WeatherRecord wr = new WeatherRecord(); wr.DataDTime = cTime; //データ取得 bStrm.Read(buffer, 0, 56); string data = System.Text.Encoding.GetEncoding(932).GetString(buffer); //気圧[Pa] double atm = wd.Value = double.Parse(data.Substring(0, 5)) * 0.01d; WeatherData.DataSource atmSource = getDataSource(data.Substring(5, 1)); wd.Source = atmSource; wr.SetData(WeatherRecord.RecordType.AtmosphericPressure, wd); //乾球温度[C] double dbt = wd.Value = double.Parse(data.Substring(12, 4)) * 0.1; WeatherData.DataSource dbtSource = getDataSource(data.Substring(16, 1)); wd.Source = dbtSource; wr.SetData(WeatherRecord.RecordType.DryBulbTemperature, wd); //相対湿度[%] double rhd = wd.Value = double.Parse(data.Substring(21, 3)); WeatherData.DataSource rhdSource = getDataSource(data.Substring(24, 1)); wd.Source = rhdSource; wr.SetData(WeatherRecord.RecordType.RelativeHumidity, wd); //風向[degree] wd.Value = getWindowDirection(int.Parse(data.Substring(25, 2))); wd.Source = getDataSource(data.Substring(27, 1)); wr.SetData(WeatherRecord.RecordType.WindDirection, wd); //風速[m/s] wd.Value = double.Parse(data.Substring(28, 3)) * 0.1; wd.Source = getDataSource(data.Substring(31, 1)); wr.SetData(WeatherRecord.RecordType.WindSpeed, wd); //雲量10分比[-] wd.Value = double.Parse(data.Substring(32, 2)) * 0.1; wd.Source = getDataSource(data.Substring(34, 1)); wr.SetData(WeatherRecord.RecordType.TotalSkyCover, wd); //天気記号 wd.Value = double.Parse(data.Substring(35, 2)); wd.Source = getDataSource(data.Substring(37, 1)); wr.SetData(WeatherRecord.RecordType.WeatherCode, wd); //露点温度[C] wd.Value = double.Parse(data.Substring(38, 4)) * 0.1; wd.Source = getDataSource(data.Substring(42, 1)); wr.SetData(WeatherRecord.RecordType.DewPointTemperature, wd); //全天日射量[W/m2] double ghRad = double.Parse(data.Substring(47, 3)) * 277.7777778 * 0.01; wd.Value = ghRad; WeatherData.DataSource ghRadSource = getDataSource(data.Substring(50, 1)); wd.Source = ghRadSource; wr.SetData(WeatherRecord.RecordType.GlobalHorizontalRadiation, wd); //降水量[mm] wd.Value = double.Parse(data.Substring(51, 4)) * 0.1; wd.Source = getDataSource(data.Substring(55, 1)); wr.SetData(WeatherRecord.RecordType.PrecipitationLevel, wd); //推定可能なデータを計算して埋める******************************************************** //絶対湿度[kg/kg(DA)] if (dbtSource != WeatherData.DataSource.MissingValue && rhdSource != WeatherData.DataSource.MissingValue) { wd.Value = MoistAir.GetAirStateFromDBRH(dbt, rhd, MoistAir.Property.HumidityRatio, atm); wd.Source = WeatherData.DataSource.CalculatedValue; wr.SetData(WeatherRecord.RecordType.HumidityRatio, wd); } //直散分離 //太陽の存在確認 bool sr = (0 < Sun.GetSunAltitude(locationInfo.Latitude, locationInfo.Longitude, 135d, cTime)); //直散分離 double dsRad, dhRad; //日出・日没調整 if (!sunRise && sr) Sun.EstimateDiffuseAndDirectNormalRadiation(ghRad, locationInfo.Latitude, locationInfo.Longitude, 135d, cTime, out dsRad, out dhRad); else if (sunRise && !sr) Sun.EstimateDiffuseAndDirectNormalRadiation(ghRad, locationInfo.Latitude, locationInfo.Longitude, 135d, cTime.AddHours(-1), out dsRad, out dhRad); else Sun.EstimateDiffuseAndDirectNormalRadiation(ghRad, locationInfo.Latitude, locationInfo.Longitude, 135d, cTime.AddHours(-0.5), out dsRad, out dhRad); sunRise = sr; //24h「観測しない」が続いた場合は欠測扱い hasDR = (ghRadSource != WeatherData.DataSource.MissingValue || hasDR); if (i != 23 || hasDR) { //直達日射量[W/m2] wd.Value = dsRad; wd.Source = WeatherData.DataSource.PredictedValue; wr.SetData(WeatherRecord.RecordType.DirectNormalRadiation, wd); //天空日射量[W/m2] wd.Value = dhRad; wd.Source = WeatherData.DataSource.PredictedValue; wr.SetData(WeatherRecord.RecordType.DiffuseHorizontalRadiation, wd); } //空白データを欠測データとして埋める****************************************************** wr.FillMissingData(); //1時間進める cTime = cTime.AddHours(1); //気象レコード追加 pwData.AddWeatherRecord(wr); } }
public IActionResult PostWeatherData(WeatherData item) { _context.AddWeatherData(item); return(StatusCode(201)); }
public override void Start() { logger.Log("Started: {0}", ToString()); //sanity check and recover the parameters if (moduleInfo.Args().Count() != 4) { logger.Log("DriverOwm: incorrect number of parameters: {0}", moduleInfo.Args().Count().ToString()); return; } string deviceId = moduleInfo.Args()[0]; appId = moduleInfo.Args()[1]; lattitude = moduleInfo.Args()[2]; longitude = moduleInfo.Args()[3]; latestWeather = new WeatherData(); //.................instantiate the port VPortInfo portInfo = GetPortInfoFromPlatform("owm-" + deviceId); weatherPort = InitPort(portInfo); // ..... initialize the list of roles we are going to export and bind to the role List<VRole> listRole = new List<VRole>() { RoleWeather.Instance }; BindRoles(weatherPort, listRole); //.................register the port after the binding is complete RegisterPortWithPlatform(weatherPort); timer = new Timer(GetWeather, null, 0, WeatherFetchPeriodMs); }
public async void GetWeather(LocationWeather location) { WeatherData weather = await WeatherModelView.GetWeather(location.Lat, location.Lon); location.Temperature = weather.main.temp.ToCelsius(); }
public HeatIndexDisplay(WeatherData weatherData) { this.weatherData = weatherData; weatherData.registerObserver(this); }
public JsonResult AjaxWeatherResponse() { WeatherData wd = Weather.GetWeatherFromSiteToday(); return(Json("[\"" + wd.Date.ToString() + "\",\"" + wd.AirTemperature.ToString() + "°C\", \"" + wd.Humidity.ToString() + "%\", \"" + wd.WindSpeed + " m/s\"," + wd.WindDirection + "]")); }
/// <summary>ファイルを元にWeatherDataTableを構成する</summary> /// <param name="filePath">読み取りファイルのパス</param> /// <param name="success">読み取り成功の真偽</param> /// <returns>構成されたPWeatherDataオブジェクト</returns> public static WeatherDataTable ToPWeatherData(string filePath, out bool success) { success = false; //読み出しファイルの存在確認 if (!File.Exists(filePath)) return null; WeatherDataTable wdTable = new WeatherDataTable(); using(StreamReader sReader = new StreamReader(filePath)) { string str; bool firstLine = true; while ((str = sReader.ReadLine()) != null) { //初回は地点情報を設定 if (firstLine) { LocationInformation lInfo = new LocationInformation(); lInfo.ID = int.Parse(str.Substring(0, 5)); lInfo.Name = lInfo.EnglishName = "TMY1" + lInfo.ID.ToString("F0"); wdTable.Location = lInfo; firstLine = false; } WeatherRecord wRecord = new WeatherRecord(); WeatherData wData; //日時 int year = int.Parse(str.Substring(5,2)); if (year < 20) year += 2000; else year += 1900; int month = int.Parse(str.Substring(7, 2)); int day = int.Parse(str.Substring(9, 2)); int hour = int.Parse(str.Substring(11, 2)) - 1; int minute = int.Parse(str.Substring(13, 2)); wRecord.DataDTime = new DateTime(year, month, day, hour, minute, 0); //直達日射[W/m2] if (str.Substring(24, 4) == "9999") wData = new WeatherData(0d, getDSource1(str.Substring(23, 1)), -1); else wData = new WeatherData(double.Parse(str.Substring(24, 4)) / 3.6d, getDSource1(str.Substring(23, 1)), -1); wRecord.SetData(WeatherRecord.RecordType.DirectNormalRadiation, wData); //水平面天空日射[W/m2] if (str.Substring(29, 4) == "9999") wData = new WeatherData(0d, getDSource1(str.Substring(28, 1)), -1); else wData = new WeatherData(double.Parse(str.Substring(29, 4)) / 3.6d, getDSource1(str.Substring(28, 1)), -1); wRecord.SetData(WeatherRecord.RecordType.DiffuseHorizontalRadiation, wData); //水平面全天日射[W/m2] if (str.Substring(54, 4) == "9999") wData = new WeatherData(0d, getDSource1(str.Substring(54, 1)), -1); else wData = new WeatherData(double.Parse(str.Substring(54, 4)) / 3.6d, getDSource1(str.Substring(53, 1)), -1); wRecord.SetData(WeatherRecord.RecordType.GlobalHorizontalRadiation, wData); //雲高さ[m] if (str.Substring(72, 4) == "7777") wData = new WeatherData(0d, WeatherData.DataSource.MissingValue, -1); if (str.Substring(72, 4) == "8888") wData = new WeatherData(0d, WeatherData.DataSource.MissingValue, -1); else wData = new WeatherData(double.Parse(str.Substring(72, 4)) * 10, WeatherData.DataSource.MeasuredValue, -1); wRecord.SetData(WeatherRecord.RecordType.CeilingHeight, wData); //視認距離[km] if (str.Substring(81, 4) == "8888") wData = new WeatherData(160d, WeatherData.DataSource.MeasuredValue, -1); else wData = new WeatherData(double.Parse(str.Substring(81, 4)) * 10, WeatherData.DataSource.MeasuredValue, -1); wRecord.SetData(WeatherRecord.RecordType.Visibility, wData); //気圧[kPa] wData = new WeatherData(double.Parse(str.Substring(98, 5)) / 100, WeatherData.DataSource.MeasuredValue, -1); double atm = wData.Value; wRecord.SetData(WeatherRecord.RecordType.AtmosphericPressure, wData); //外気乾球温度[C] wData = new WeatherData(double.Parse(str.Substring(103, 4)) / 10, WeatherData.DataSource.MeasuredValue, -1); double dbt = wData.Value; wRecord.SetData(WeatherRecord.RecordType.DryBulbTemperature, wData); //露点温度[C] wData = new WeatherData(double.Parse(str.Substring(107, 4)) / 10, WeatherData.DataSource.MeasuredValue, -1); double dpt = wData.Value; wRecord.SetData(WeatherRecord.RecordType.DewPointTemperature, wData); //その他の空気状態 double ahd = MoistAir.GetSaturatedHumidityRatio(dpt, MoistAir.Property.DryBulbTemperature, atm); MoistAir mAir = MoistAir.GetAirStateFromDBHR(dbt, ahd, atm); //相対湿度[%] wRecord.SetData(WeatherRecord.RecordType.RelativeHumidity, new WeatherData(mAir.RelativeHumidity, WeatherData.DataSource.CalculatedValue, -1)); //絶対湿度[kg/kg(DA)] wRecord.SetData(WeatherRecord.RecordType.HumidityRatio, new WeatherData(mAir.HumidityRatio, WeatherData.DataSource.CalculatedValue, -1)); //風向 wData = new WeatherData(double.Parse(str.Substring(111, 3)), WeatherData.DataSource.MeasuredValue, -1); wRecord.SetData(WeatherRecord.RecordType.WindDirection, wData); //風速[m/s] wData = new WeatherData(double.Parse(str.Substring(114, 4)) / 10d, WeatherData.DataSource.MeasuredValue, -1); wRecord.SetData(WeatherRecord.RecordType.WindSpeed, wData); //雲量 double dbl = double.Parse(str.Substring(118, 2)); if (dbl == 99) wData = new WeatherData(double.Parse(str.Substring(118, 2)), WeatherData.DataSource.MissingValue, -1); else wData = new WeatherData(double.Parse(str.Substring(118, 2)), WeatherData.DataSource.MeasuredValue, -1); wRecord.SetData(WeatherRecord.RecordType.TotalSkyCover, wData); //雲量2 wData = new WeatherData(double.Parse(str.Substring(120, 2)), WeatherData.DataSource.MeasuredValue, -1); wRecord.SetData(WeatherRecord.RecordType.OpaqueSkyCover, wData); //欠測補充 wRecord.FillMissingData(); //気象レコード追加 wdTable.AddWeatherRecord(wRecord); } } success = true; return wdTable; }
private void InstallCurrWeather(WeatherData newData) { lock (latestWeather) { latestWeather = newData; } }
public static bool IsResponseOk(this WeatherData data) { return(data.Status == "200"); }
public override void ReadData(ESPReader reader, long dataEnd) { while (reader.BaseStream.Position < dataEnd) { string subTag = reader.PeekTag(); switch (subTag) { case "EDID": if (EditorID == null) { EditorID = new SimpleSubrecord <String>(); } EditorID.ReadBinary(reader); break; case "aIAD": if (ImageSpaceModifierSunrise == null) { ImageSpaceModifierSunrise = new RecordReference(); } ImageSpaceModifierSunrise.ReadBinary(reader); break; case "bIAD": if (ImageSpaceModifierDay == null) { ImageSpaceModifierDay = new RecordReference(); } ImageSpaceModifierDay.ReadBinary(reader); break; case "cIAD": if (ImageSpaceModifierSunset == null) { ImageSpaceModifierSunset = new RecordReference(); } ImageSpaceModifierSunset.ReadBinary(reader); break; case "dIAD": if (ImageSpaceModifierNight == null) { ImageSpaceModifierNight = new RecordReference(); } ImageSpaceModifierNight.ReadBinary(reader); break; case "eIAD": if (ImageSpaceModifierHighNoon == null) { ImageSpaceModifierHighNoon = new RecordReference(); } ImageSpaceModifierHighNoon.ReadBinary(reader); break; case "fIAD": if (ImageSpaceModifierMidnight == null) { ImageSpaceModifierMidnight = new RecordReference(); } ImageSpaceModifierMidnight.ReadBinary(reader); break; case "DNAM": if (CloudTextureLayer0 == null) { CloudTextureLayer0 = new SimpleSubrecord <String>(); } CloudTextureLayer0.ReadBinary(reader); break; case "CNAM": if (CloudTextureLayer1 == null) { CloudTextureLayer1 = new SimpleSubrecord <String>(); } CloudTextureLayer1.ReadBinary(reader); break; case "ANAM": if (CloudTextureLayer2 == null) { CloudTextureLayer2 = new SimpleSubrecord <String>(); } CloudTextureLayer2.ReadBinary(reader); break; case "BNAM": if (CloudTextureLayer3 == null) { CloudTextureLayer3 = new SimpleSubrecord <String>(); } CloudTextureLayer3.ReadBinary(reader); break; case "MODL": if (Model == null) { Model = new Model(); } Model.ReadBinary(reader); break; case "LNAM": if (Unknown == null) { Unknown = new SimpleSubrecord <Byte[]>(); } Unknown.ReadBinary(reader); break; case "ONAM": if (CloudLayerSpeed == null) { CloudLayerSpeed = new CloudLayerSpeed(); } CloudLayerSpeed.ReadBinary(reader); break; case "PNAM": if (CloudLayerColors == null) { CloudLayerColors = new CloudLayerColors(); } CloudLayerColors.ReadBinary(reader); break; case "NAM0": if (EnvironmentalColors == null) { EnvironmentalColors = new EnvironmentalColors(); } EnvironmentalColors.ReadBinary(reader); break; case "FNAM": if (WeatherFogDistance == null) { WeatherFogDistance = new WeatherFogDistance(); } WeatherFogDistance.ReadBinary(reader); break; case "INAM": if (Unused == null) { Unused = new SimpleSubrecord <Byte[]>(); } Unused.ReadBinary(reader); break; case "DATA": if (Data == null) { Data = new WeatherData(); } Data.ReadBinary(reader); break; case "SNAM": if (Sounds == null) { Sounds = new List <WeatherSound>(); } WeatherSound tempSNAM = new WeatherSound(); tempSNAM.ReadBinary(reader); Sounds.Add(tempSNAM); break; default: throw new Exception(); } } }
public WeatherForecastController(WeatherData context) { _context = context; }
/// <summary>ファイルを元にWeatherDataTableを構成する</summary> /// <param name="filePath">読み取りファイルのパス</param> /// <param name="success">読み取り成功の真偽</param> /// <returns>構成されたPWeatherDataオブジェクト</returns> public static WeatherDataTable ToPWeatherData(string filePath, out bool success) { success = false; //読み出しファイルの存在確認 if (File.Exists(filePath)) { WeatherDataTable wdTable = new WeatherDataTable(); using (StreamReader sReader = new StreamReader(filePath)) { string[] buff; DateTime dTime = new DateTime(); //第1行:地点情報 buff = sReader.ReadLine().Split(','); LocationInformation lInfo = new LocationInformation(); lInfo.ID = int.Parse(buff[0]); lInfo.Name = buff[1]; lInfo.EnglishName = buff[2]; lInfo.Latitude = double.Parse(buff[4]); lInfo.Longitude = double.Parse(buff[5]); lInfo.Elevation = double.Parse(buff[6]); for (int i = 0; i < 8760; i++) { WeatherRecord wRecord = new WeatherRecord(); WeatherData wData; //年月日特定 if (i == 0) { buff = sReader.ReadLine().Split(','); dTime = DateTime.ParseExact(buff[0], "MM/dd/yyyy", System.Globalization.DateTimeFormatInfo.InvariantInfo); } wRecord.DataDTime = dTime; //日射関連********************************** //大気圏外水平面日射 wData = new WeatherData(double.Parse(buff[2]) / 3600d, WeatherData.DataSource.CalculatedValue, -1); wRecord.SetData(WeatherRecord.RecordType.ExtraterrestrialHorizontalRadiation, wData); //大気圏外法線面日射 wData = new WeatherData(double.Parse(buff[3]) / 3600d, WeatherData.DataSource.CalculatedValue, -1); wRecord.SetData(WeatherRecord.RecordType.ExtraterrestrialDirectNormalRadiation, wData); //水平面全天日射 wData = new WeatherData(double.Parse(buff[4]) / 3600d, WeatherData.DataSource.Unknown, double.Parse(buff[6]) / 100d); wRecord.SetData(WeatherRecord.RecordType.GlobalHorizontalRadiation, wData); //直達日射 wData = new WeatherData(double.Parse(buff[7]) / 3600d, WeatherData.DataSource.Unknown, double.Parse(buff[9]) / 100d); wRecord.SetData(WeatherRecord.RecordType.DirectNormalRadiation, wData); //水平面天空日射 wData = new WeatherData(double.Parse(buff[10]) / 3600d, WeatherData.DataSource.Unknown, double.Parse(buff[12]) / 100d); wRecord.SetData(WeatherRecord.RecordType.DiffuseHorizontalRadiation, wData); //日照関連********************************** //水平面全天照度 wData = new WeatherData(double.Parse(buff[13]), WeatherData.DataSource.Unknown, double.Parse(buff[15]) / 100d); wRecord.SetData(WeatherRecord.RecordType.GlobalHorizontalIlluminance, wData); //法線面直射日射照度 wData = new WeatherData(double.Parse(buff[16]), WeatherData.DataSource.Unknown, double.Parse(buff[18]) / 100d); wRecord.SetData(WeatherRecord.RecordType.DirectNormalIlluminance, wData); //水平面天空照度 wData = new WeatherData(double.Parse(buff[19]), WeatherData.DataSource.Unknown, double.Parse(buff[21]) / 100d); wRecord.SetData(WeatherRecord.RecordType.DiffuseHorizontalIlluminance, wData); //天頂輝度 wData = new WeatherData(double.Parse(buff[22]), WeatherData.DataSource.Unknown, double.Parse(buff[24]) / 100d); wRecord.SetData(WeatherRecord.RecordType.ZenithLuminance, wData); //雲量 wData = new WeatherData(double.Parse(buff[25]), getDSource(buff[26]), double.Parse(buff[27]) / 100d); wRecord.SetData(WeatherRecord.RecordType.TotalSkyCover, wData); //雲量2 wData = new WeatherData(double.Parse(buff[28]), getDSource(buff[29]), double.Parse(buff[30]) / 100d); wRecord.SetData(WeatherRecord.RecordType.OpaqueSkyCover, wData); //空気状態関連********************************** //乾球温度 wData = new WeatherData(double.Parse(buff[31]), getDSource(buff[32]), double.Parse(buff[33]) / 100d); wRecord.SetData(WeatherRecord.RecordType.DryBulbTemperature, wData); //露点温度 wData = new WeatherData(double.Parse(buff[34]), getDSource(buff[35]), double.Parse(buff[36]) / 100d); wRecord.SetData(WeatherRecord.RecordType.DewPointTemperature, wData); //相対湿度 wData = new WeatherData(double.Parse(buff[37]), getDSource(buff[38]), double.Parse(buff[39]) / 100d); wRecord.SetData(WeatherRecord.RecordType.RelativeHumidity, wData); //気圧 wData = new WeatherData(double.Parse(buff[40]) / 10d, getDSource(buff[41]), double.Parse(buff[42]) / 100d); wRecord.SetData(WeatherRecord.RecordType.AtmosphericPressure, wData); //その他********************************** //風向 wData = new WeatherData(double.Parse(buff[43]) - 180d, getDSource(buff[44]), double.Parse(buff[45]) / 100d); wRecord.SetData(WeatherRecord.RecordType.WindDirection, wData); //風速 wData = new WeatherData(double.Parse(buff[46]), getDSource(buff[47]), double.Parse(buff[48]) / 100d); wRecord.SetData(WeatherRecord.RecordType.WindSpeed, wData); //視認距離 wData = new WeatherData(double.Parse(buff[49]), getDSource(buff[50]), double.Parse(buff[51]) / 100d); wRecord.SetData(WeatherRecord.RecordType.Visibility, wData); //雲高さ wData = new WeatherData(double.Parse(buff[52]), getDSource(buff[53]), double.Parse(buff[54]) / 100d); wRecord.SetData(WeatherRecord.RecordType.CeilingHeight, wData); //可降水量 wData = new WeatherData(double.Parse(buff[55]), getDSource(buff[56]), double.Parse(buff[57]) / 100d); wRecord.SetData(WeatherRecord.RecordType.PrecipitableWater, wData); //大気混濁度 wData = new WeatherData(double.Parse(buff[58]), getDSource(buff[59]), double.Parse(buff[60]) / 100d); wRecord.SetData(WeatherRecord.RecordType.AerosolOpticalDepth, wData); //アルベド wData = new WeatherData(double.Parse(buff[61]), getDSource(buff[62]), double.Parse(buff[63]) / 100d); wRecord.SetData(WeatherRecord.RecordType.Albedo, wData); //降水量 wData = new WeatherData(double.Parse(buff[64]), getDSource(buff[66]), double.Parse(buff[67]) / 100d); wRecord.SetData(WeatherRecord.RecordType.PrecipitationLevel, wData); //降水量計測時間はとりあえず無視 //気象データ追加 wdTable.AddWeatherRecord(wRecord); //時刻更新 dTime = dTime.AddHours(1); } } success = true; return wdTable; } else return null; }
private void GetWeather(object state) { string requestUri = null; try { requestUri = String.Format("{0}weather?mode=xml&units=metric&appid={1}&lat={2}&lon={3}", OpenWeatherMapUrl, appId, lattitude, longitude); XmlDocument xmlDoc = new XmlDocument(); XmlReader xmlReader = XmlReader.Create(requestUri); xmlDoc.Load(xmlReader); WeatherData curWeatherData = new WeatherData(); // get sun stuff XmlElement xmlSun = (XmlElement) xmlDoc.GetElementsByTagName("sun")[0]; curWeatherData.SunriseTime = DateTime.Parse(xmlSun.GetAttribute("rise")); curWeatherData.SunsetTime = DateTime.Parse(xmlSun.GetAttribute("set")); // get temperature stuff XmlElement xmlTemp = (XmlElement)xmlDoc.GetElementsByTagName("temperature")[0]; string units = xmlTemp.GetAttribute("unit"); if (!units.Equals("celsius")) throw new Exception("Unexpected units in temperature data: " + units); curWeatherData.CurTemp_C = double.Parse(xmlTemp.GetAttribute("value")); curWeatherData.MinTemp_C = double.Parse(xmlTemp.GetAttribute("min")); curWeatherData.MaxTemp_C = double.Parse(xmlTemp.GetAttribute("max")); // get cloud stuff XmlElement xmlClouds = (XmlElement)xmlDoc.GetElementsByTagName("clouds")[0]; curWeatherData.CloudsName = xmlClouds.GetAttribute("name"); // get precipitation stuff XmlElement xmlPrecipitation = (XmlElement)xmlDoc.GetElementsByTagName("precipitation")[0]; curWeatherData.PrecipitationMode = xmlPrecipitation.GetAttribute("mode"); // get precipitation stuff XmlElement xmlWeather = (XmlElement)xmlDoc.GetElementsByTagName("weather")[0]; curWeatherData.WeatherValue = xmlWeather.GetAttribute("value"); // get the update time XmlElement xmlLastUpdate = (XmlElement)xmlDoc.GetElementsByTagName("lastupdate")[0]; curWeatherData.LastUpdateTime = DateTime.Parse(xmlLastUpdate.GetAttribute("value")); xmlReader.Close(); InstallCurrWeather(curWeatherData); } catch (Exception e) { logger.Log("Exception while fetching and parsing weather using URI {0}: {1}", requestUri, e.ToString()); } }
public ForecastDisplay(WeatherData weatherData) { this.weatherData = weatherData; weatherData.registerObserver(this); }
protected virtual void RaiseOnWeatherUpdate(WeatherData e) { OnWeatherUpdate?.Invoke(this, e); }
public bool doQuery(PropertyGrid grid) { data = (WeatherData)grid.SelectedObject; ; data.Weather = glw.GetWeather(data.Town, data.Country); grid.SelectedObject = this.data; return (this.data.Weather != null); }
/// <summary> /// Add to WeatherData object the content from the xml file with Linq. /// </summary> /// <param name="weatherXml">string - weather xml as string</param> /// <returns>WeatherData object</returns> private WeatherData FillWeatherData(string weatherXml) { WeatherData wd = new WeatherData(); XDocument ob = XDocument.Parse(weatherXml); try { wd = (from x in ob.Descendants("current") select new WeatherData { City = (from city in x.Descendants("city") select new City { ID = city.Attribute("id")?.Value ?? "", Name = city.Attribute("name")?.Value ?? "", Lon = Convert.ToDouble(city.Element("coord")?.Attribute("lon")?.Value ?? "-1"), Lat = Convert.ToDouble(city.Element("coord")?.Attribute("lat")?.Value ?? "-1"), Country = city.Element("country")?.Value ?? "", SunSet = Convert.ToDateTime(city.Element("sun")?.Attribute("set")?.Value ?? "-1"), SunRise = Convert.ToDateTime(city.Element("sun")?.Attribute("rise")?.Value ?? "-1") }).ToArray()[0], Temperature = (from temperature in x.Descendants("temperature") select new Temperature { Value = Convert.ToDouble(temperature.Attribute("value")?.Value ?? "-1"), Min = Convert.ToDouble(temperature.Attribute("min")?.Value ?? "-1"), Max = Convert.ToDouble(temperature.Attribute("max")?.Value ?? "-1"), Unit = temperature.Attribute("unit")?.Value ?? "" }).ToArray()[0], Humidity = (from humidity in x.Descendants("humidity") select new Humidity { Value = Convert.ToDouble(humidity.Attribute("value")?.Value ?? "-1"), Unit = humidity.Attribute("unit")?.Value ?? "" }).ToArray()[0], Pressure = (from pressure in x.Descendants("pressure") select new Pressure { Value = Convert.ToDouble(pressure.Attribute("value")?.Value ?? "-1"), Unit = pressure.Attribute("unit")?.Value ?? "" }).ToArray()[0], Wind = (from wind in x.Descendants("wind") select new Wind { Speed = Convert.ToDouble(wind.Element("speed")?.Attribute("value")?.Value ?? "-1"), Gusts = Convert.ToDouble(wind.Element("gusts")?.Attribute("value")?.Value ?? "-1"), DirectionValue = Convert.ToDouble(wind.Element("direction")?.Attribute("value")?.Value ?? "-1"), DirectionName = wind.Element("direction")?.Attribute("name")?.Value ?? "", DirectionCode = wind.Element("direction")?.Attribute("code")?.Value ?? "" }).ToArray()[0], Clouds = (from clouds in x.Descendants("clouds") select new Clouds { Value = Convert.ToDouble(clouds.Attribute("value")?.Value ?? "-1"), Name = clouds.Attribute("name")?.Value ?? "" }).ToArray()[0], Precipitation = x.Element("precipitation")?.Attribute("mode")?.Value ?? "", Weather = (from w in x.Descendants("weather") select new Weather { Number = Convert.ToDouble(w.Attribute("number")?.Value ?? "-1"), Value = w.Attribute("value")?.Value ?? "", Icon = w.Attribute("icon")?.Value ?? "" }).ToArray()[0], LastUpdate = Convert.ToDateTime(x.Element("lastupdate")?.Attribute("value")?.Value ?? "") }).ToArray()[0]; } catch (Exception e2) { throw new WeatherDataServiceException(e2.Message); } return(wd); }
private async Task GetWeatherCurrentData(CancellationToken cancellationToken) { var weatherData = await GetData(WeatherDataPropertyName, UwOpenDataApi.GetWeatherData, cancellationToken); if (weatherData != null) { WeatherData = weatherData.data; } }
/// <summary> /// Initializes a new instance of the <see cref="CurrentConditionsReport"/> class. /// </summary> /// <param name="weatherData"> /// Observable object /// </param> public CurrentConditionsReport(WeatherData weatherData) { this.weatherData = weatherData; weatherData.Register(this); }
public static WeatherData XmlAnalytical(string xmlString) { XmlDocument document = new XmlDocument( ); document.CreateElement("Employees"); // XmlRootAttribute Root = new XmlRootAttribute(); // Root.ElementName = "weatherDatas"; XmlSerializer sr = new XmlSerializer(typeof(WeatherData)); ///StringReader strReader = new StringReader(xmlString); //System.Xml.XmlReader r = new System.Xml(); //weatherData = (WeatherData)sr.Deserialize(r); //return weatherData; DataContractSerializer obj = new DataContractSerializer(typeof(WeatherData)); weatherData = (WeatherData)obj.ReadObject(new MemoryStream(Encoding.UTF8.GetBytes(xmlString))); return weatherData; }
public override void ReadDataXML(XElement ele, ElderScrollsPlugin master) { XElement subEle; if (ele.TryPathTo("EditorID", false, out subEle)) { if (EditorID == null) { EditorID = new SimpleSubrecord <String>(); } EditorID.ReadXML(subEle, master); } if (ele.TryPathTo("ImageSpaceModifier/Sunrise", false, out subEle)) { if (ImageSpaceModifierSunrise == null) { ImageSpaceModifierSunrise = new RecordReference(); } ImageSpaceModifierSunrise.ReadXML(subEle, master); } if (ele.TryPathTo("ImageSpaceModifier/Day", false, out subEle)) { if (ImageSpaceModifierDay == null) { ImageSpaceModifierDay = new RecordReference(); } ImageSpaceModifierDay.ReadXML(subEle, master); } if (ele.TryPathTo("ImageSpaceModifier/Sunset", false, out subEle)) { if (ImageSpaceModifierSunset == null) { ImageSpaceModifierSunset = new RecordReference(); } ImageSpaceModifierSunset.ReadXML(subEle, master); } if (ele.TryPathTo("ImageSpaceModifier/Night", false, out subEle)) { if (ImageSpaceModifierNight == null) { ImageSpaceModifierNight = new RecordReference(); } ImageSpaceModifierNight.ReadXML(subEle, master); } if (ele.TryPathTo("ImageSpaceModifier/HighNoon", false, out subEle)) { if (ImageSpaceModifierHighNoon == null) { ImageSpaceModifierHighNoon = new RecordReference(); } ImageSpaceModifierHighNoon.ReadXML(subEle, master); } if (ele.TryPathTo("ImageSpaceModifier/Midnight", false, out subEle)) { if (ImageSpaceModifierMidnight == null) { ImageSpaceModifierMidnight = new RecordReference(); } ImageSpaceModifierMidnight.ReadXML(subEle, master); } if (ele.TryPathTo("CloudTexture/Layer0", false, out subEle)) { if (CloudTextureLayer0 == null) { CloudTextureLayer0 = new SimpleSubrecord <String>(); } CloudTextureLayer0.ReadXML(subEle, master); } if (ele.TryPathTo("CloudTexture/Layer1", false, out subEle)) { if (CloudTextureLayer1 == null) { CloudTextureLayer1 = new SimpleSubrecord <String>(); } CloudTextureLayer1.ReadXML(subEle, master); } if (ele.TryPathTo("CloudTexture/Layer2", false, out subEle)) { if (CloudTextureLayer2 == null) { CloudTextureLayer2 = new SimpleSubrecord <String>(); } CloudTextureLayer2.ReadXML(subEle, master); } if (ele.TryPathTo("CloudTexture/Layer3", false, out subEle)) { if (CloudTextureLayer3 == null) { CloudTextureLayer3 = new SimpleSubrecord <String>(); } CloudTextureLayer3.ReadXML(subEle, master); } if (ele.TryPathTo("Model", false, out subEle)) { if (Model == null) { Model = new Model(); } Model.ReadXML(subEle, master); } if (ele.TryPathTo("Unknown", false, out subEle)) { if (Unknown == null) { Unknown = new SimpleSubrecord <Byte[]>(); } Unknown.ReadXML(subEle, master); } if (ele.TryPathTo("CloudLayerSpeed", false, out subEle)) { if (CloudLayerSpeed == null) { CloudLayerSpeed = new CloudLayerSpeed(); } CloudLayerSpeed.ReadXML(subEle, master); } if (ele.TryPathTo("CloudLayerColors", false, out subEle)) { if (CloudLayerColors == null) { CloudLayerColors = new CloudLayerColors(); } CloudLayerColors.ReadXML(subEle, master); } if (ele.TryPathTo("EnvironmentalColors", false, out subEle)) { if (EnvironmentalColors == null) { EnvironmentalColors = new EnvironmentalColors(); } EnvironmentalColors.ReadXML(subEle, master); } if (ele.TryPathTo("WeatherFogDistance", false, out subEle)) { if (WeatherFogDistance == null) { WeatherFogDistance = new WeatherFogDistance(); } WeatherFogDistance.ReadXML(subEle, master); } if (ele.TryPathTo("Unused", false, out subEle)) { if (Unused == null) { Unused = new SimpleSubrecord <Byte[]>(); } Unused.ReadXML(subEle, master); } if (ele.TryPathTo("Data", false, out subEle)) { if (Data == null) { Data = new WeatherData(); } Data.ReadXML(subEle, master); } if (ele.TryPathTo("Sounds", false, out subEle)) { if (Sounds == null) { Sounds = new List <WeatherSound>(); } foreach (XElement e in subEle.Elements()) { WeatherSound tempSNAM = new WeatherSound(); tempSNAM.ReadXML(e, master); Sounds.Add(tempSNAM); } } }
async public void Show(string cityName) { string Address = "http://api.map.baidu.com/telematics/v3/weather?location=" + cityName + "&output=json&ak=Gi27P5bmIinr86htrjU4ESnY"; try { //var strinfo = await httpClient.GetStringAsync(Address); var strinfo = await httpClient.GetStringAsync(Address); //json解析 weatherData = JsonAnalytical(strinfo); //xml解析 //weatherData = XmlAnalytical(strinfo); } catch (Exception ex) { Debug.WriteLine("网络请求失败!" + ex.Message.ToString()); } listIndex.Visibility = Windows.UI.Xaml.Visibility.Collapsed; listWeather.Visibility = Windows.UI.Xaml.Visibility.Visible; listWeather.ItemsSource = weatherData.results[0].weather_data; //listIndex.ItemsSource = weatherData.results[0].index; textPmName.Text = "PM2.5"; dayPicture.Source = (new BitmapImage(new Uri(weatherData.results[0].weather_data[0].dayPictureUrl.ToString()))); nightPicture.Source = (new BitmapImage(new Uri(weatherData.results[0].weather_data[0].nightPictureUrl.ToString()))); date.Text = weatherData.results[0].weather_data[0].date; weather.Text = weatherData.results[0].weather_data[0].weather; wind.Text = weatherData.results[0].weather_data[0].wind; temperature.Text = weatherData.results[0].weather_data[0].temperature; textCity.Text = weatherData.results[0].currentCity; textPm.Text = weatherData.results[0].pm25; showCity.Text = cityName; bt = new Btn(); bt.zero = "天气情况"; bt.one = "穿衣指数"; bt.two = "洗车指数"; bt.three = "旅游指数"; bt.four = "感冒指数"; bt.five = "运动指数"; bt.six = "紫外线强度指数"; btn.Add(bt); listbtn.ItemsSource = btn; }
private void OnWeatherReceived(WeatherData weather) => WeatherReceived?.Invoke(this, new DataReceivedEventArgs <WeatherData>(weather));
public static WeatherData JsonAnalytical(string jsonString) { DataContractJsonSerializer obj = new DataContractJsonSerializer(typeof(WeatherData)); weatherData = (WeatherData )obj.ReadObject(new MemoryStream(Encoding.UTF8.GetBytes(jsonString))); return weatherData; }
/// <summary> /// Registers a subscriber. /// </summary> /// <param name="observer">Observer for subscribing.</param> public void Register(WeatherData weather) { weather.NewMail += Update; }
public Forecast(WeatherData data) { }
public static string ConvertToJSON(WeatherData data) { return(JsonConvert.SerializeObject(data)); }
/// <summary>ファイルを元にWeatherDataTableを構成する</summary> /// <param name="filePath">読み取りファイルのパス</param> /// <param name="success">読み取り成功の真偽</param> /// <returns>構成されたPWeatherDataオブジェクト</returns> public static WeatherDataTable ToPWeatherData(string filePath, out bool success) { success = false; //読み出しファイルの存在確認 if (File.Exists(filePath)) { WeatherDataTable wdTable = new WeatherDataTable(); using (StreamReader sReader = new StreamReader(filePath)) { string buff; DateTime dTime; //第1行 sReader.ReadLine(); for (int i = 0; i < 365; i++) { WeatherRecord[] wRecords = new WeatherRecord[24]; //年月日特定 buff = sReader.ReadLine(); int year = int.Parse(buff.Substring(72, 2)); int month = int.Parse(buff.Substring(74, 2)); int day = int.Parse(buff.Substring(76, 2)); if (year < 50) year += 2000; else year += 1900; dTime = new DateTime(year, month, day, 0, 0, 0); for (int j = 0; j < 24; j++) { wRecords[j] = new WeatherRecord(); wRecords[j].DataDTime = dTime; dTime = dTime.AddHours(1); } //乾球温度 for (int j = 0; j < 24; j++) { string bf = buff.Substring(j * 3, 3); WeatherData wData = new WeatherData(); wData.Source = WeatherData.DataSource.CalculatedValue; wData.Value = (double.Parse(bf) - 500d) / 10d; wRecords[j].SetData(WeatherRecord.RecordType.DryBulbTemperature, wData); } //絶対湿度 buff = sReader.ReadLine(); for (int j = 0; j < 24; j++) { string bf = buff.Substring(j * 3, 3); WeatherData wData = new WeatherData(); wData.Source = WeatherData.DataSource.CalculatedValue; wData.Value = double.Parse(bf) / 10000d; wRecords[j].SetData(WeatherRecord.RecordType.HumidityRatio, wData); } //法線面直達日射[kcal/m2-h] buff = sReader.ReadLine(); for (int j = 0; j < 24; j++) { string bf = buff.Substring(j * 3, 3); WeatherData wData = new WeatherData(); wData.Source = WeatherData.DataSource.CalculatedValue; wData.Value = double.Parse(bf) * 1.163; // [W/m2]に変換 wRecords[j].SetData(WeatherRecord.RecordType.DirectNormalRadiation, wData); } //水平面天空日射[kcal/m2-h] buff = sReader.ReadLine(); for (int j = 0; j < 24; j++) { string bf = buff.Substring(j * 3, 3); WeatherData wData = new WeatherData(); wData.Source = WeatherData.DataSource.CalculatedValue; wData.Value = double.Parse(bf) * 1.163; // [W/m2]に変換 wRecords[j].SetData(WeatherRecord.RecordType.DiffuseHorizontalRadiation, wData); } //雲量[-] (10分比) buff = sReader.ReadLine(); for (int j = 0; j < 24; j++) { string bf = buff.Substring(j * 3, 3); WeatherData wData = new WeatherData(); wData.Source = WeatherData.DataSource.CalculatedValue; wData.Value = int.Parse(bf); wRecords[j].SetData(WeatherRecord.RecordType.TotalSkyCover, wData); } //風向[-] (16分比) buff = sReader.ReadLine(); for (int j = 0; j < 24; j++) { string bf = buff.Substring(j * 3, 3); WeatherData wData = new WeatherData(); wData.Source = WeatherData.DataSource.CalculatedValue; wData.Value = convertFromWindDirectionCode(int.Parse(bf)); wRecords[j].SetData(WeatherRecord.RecordType.WindDirection, wData); } //風速[m/s] buff = sReader.ReadLine(); for (int j = 0; j < 24; j++) { string bf = buff.Substring(j * 3, 3); WeatherData wData = new WeatherData(); wData.Source = WeatherData.DataSource.CalculatedValue; wData.Value = double.Parse(bf) / 10d; wRecords[j].SetData(WeatherRecord.RecordType.WindSpeed, wData); } wdTable.AddWeatherRecord(wRecords); } } success = true; return wdTable; } else return null; }
public async Task SendDataAsync(WeatherData data) { EventData eventData = CreateEventData(data); await _eventHubClient.SendAsync(eventData); }
public void Unregister(WeatherData data) { data.WeatherChanged -= Message; }
public void Register(WeatherData data) { data.WeatherChanged += Message; }
public void Add(WeatherData weatherData) { _collection.InsertOne(weatherData); }
public async Task Execute(IJobExecutionContext context) { logger.LogInformation("Schedule.Weather :: starting"); WeatherData weatherData = null; try { using (var client = new WebClient()) { using (Stream data = await client.OpenReadTaskAsync(configuration["Weather:DataUrl"])) { XmlSerializer serializer = new XmlSerializer(typeof(WeatherData)); weatherData = (WeatherData)serializer.Deserialize(data); } } } catch (Exception ex) { logger.LogError(ex, $"Failed to fetch weather and sun information."); } if (weatherData == null) { return; } // insert sun rise and set event data try { sunDataService.Add(weatherData.Sun.Rise.Date, weatherData.Sun.Rise, weatherData.Sun.Set); } catch (Exception ex) { logger.LogError(ex, $"Failed to store sun information in database."); } // import weather forecast try { logger.LogInformation("Schedule.Weather :: updating weather"); DateTime date = weatherData.Forecast.Tabular.Time.OrderBy(t => t.From).Select(t => t.From.Date).FirstOrDefault(); var previousForecast = this.context.WeatherForecast.OrderBy(wf => wf.Date).ThenBy(wf => wf.Period).Where(wf => wf.Date >= date).ToList(); foreach (var item in weatherData.Forecast.Tabular.Time) { WeatherForecast forecast = previousForecast.FirstOrDefault(f => f.Date == item.From.Date && (int)f.Period == item.Period); if (forecast == null) { forecast = new WeatherForecast(); this.context.Add(forecast); } forecast.Date = item.From.Date; forecast.Period = (WeatherForecastPeriod)item.Period; forecast.SymbolID = item.Symbol.Var; forecast.Temperature = item.Temperature.Value; forecast.WindSpeed = item.WindSpeed.Mps; forecast.WindDirection = item.WindDirection.Code; forecast.Rain = item.Precipitation.Value; } this.context.SaveChanges(); } catch (Exception ex) { logger.LogError(ex, $"Failed to store weather information in database."); } }
public StatisticsDisplay(WeatherData weatherData) { this.weatherData = weatherData; weatherData.RegisterObserver(this); }
public CurrentConditions(WeatherData weatherData) { weatherData.RegisterObject(this); }
public void Update(WeatherData weatherData) { _weatherData = weatherData; Display(); }
private void HandleResponse(WeatherForecast weatherForecast) { WeatherReport weatherReport; switch (currentDayType) { case DayType.Today: weatherReport = weatherForecast.today; break; case DayType.Tomorrow: weatherReport = weatherForecast.tomorrow; break; case DayType.DayAfterTomorrow: weatherReport = weatherForecast.dayAfterTomorrow; break; default: weatherReport = null; break; } // bug by DarkSky // location //SetLocation(weatherReport.location); // day type SetDayTypeLabel(currentDayType); foreach (DayTime dayTime in weatherReport.data.Keys) { WeatherData weatherData = weatherReport.data[dayTime]; string temperatureComponentName = null; string phenomenaComponentName = null; switch (dayTime) { case DayTime.MORNING: temperatureComponentName = "MorningTemperature"; phenomenaComponentName = "MorningPhenomena"; break; case DayTime.NOON: temperatureComponentName = "NoonTemperature"; phenomenaComponentName = "NoonPhenomena"; break; case DayTime.EVENING: temperatureComponentName = "EveningTemperature"; phenomenaComponentName = "EveningPhenomena"; break; case DayTime.NIGHT: temperatureComponentName = "NightTemperature"; phenomenaComponentName = "NightPhenomena"; break; } // temperature SetTemperature(weatherData.temperature, temperatureComponentName); // weather phenomena Material material = WeatherPhenomenaMapper.GetWeatherMaterial(weatherData.phenomena); Transform phenomenaComponent = currentWeatherContainer.transform.Find(phenomenaComponentName); phenomenaComponent.GetComponent <MeshRenderer>().material = material; } }
private void OnWeatherAlarmTriggered(WeatherData weather, AlarmObject alarm, ulong guildId) { WeatherAlarmTriggered?.Invoke(this, new AlarmEventTriggeredEventArgs <WeatherData>(weather, alarm, guildId)); }
async void OnItemSelected(object sender, EventArgs e) { ListView listView = (ListView)sender; StationData stationData = (StationData)listView.SelectedItem; if (listView.SelectedItem != null && howManyDays != "0" && stationData != null) { // TODO: Show user waiting bool isAdded = false; int tempDayCounter = 0; int howMany3HoursinGivenDay = Int32.Parse(howManyDays) * 8; WeatherData weatherData = await _weatherService.GetWeatherDataAsync(GenerateRequestUri(Constants.OpenWeatherMapEndpoint, stationData.Geometry.Coordinates[1], stationData.Geometry.Coordinates[0], howMany3HoursinGivenDay.ToString())); TidalEventsData[] tidalEventsData = await _tidalService.GetTidalEventsDataAsync(GenerateRequestUriForTidalEventsData(Constants.UKTidalEndpoind, stationData.Properties.Id, howManyDays)); if (weatherData != null && tidalEventsData != null) { string currentDate = DateTime.Now.ToString().Substring(3, 2); List <TidalAndWeather> tidalAndWeathers = new List <TidalAndWeather>(); for (int i = 0; i < weatherData.Count; i++) { if (currentDate == weatherData.WeatherList[i].DtTxt.Substring(8, 2) && isAdded != false) { var obj = tidalAndWeathers.FirstOrDefault(x => x.Date.Substring(8, 2) == currentDate); if (obj != null) { if (obj.MinTemperature > weatherData.WeatherList[i].Main.MinTemperature && weatherData.WeatherList[i].Main.MinTemperature < obj.Temperature) { obj.MinTemperature = weatherData.WeatherList[i].Main.MinTemperature; } if (obj.MaxTemperature < weatherData.WeatherList[i].Main.MaxTemperature && weatherData.WeatherList[i].Main.MaxTemperature > obj.Temperature) { obj.MaxTemperature = weatherData.WeatherList[i].Main.MaxTemperature; } } } else { if (tempDayCounter + 1 > Int32.Parse(howManyDays) * 4) { break; } if (tidalEventsData.ElementAtOrDefault(tempDayCounter + 3) != null && tidalEventsData[tempDayCounter + 3].DateTime.Substring(8, 2) == currentDate) { tidalAndWeathers.Add(new TidalAndWeather() { City = stationData.Properties.Name, Icon = weatherData.WeatherList[i].Weather[0].Icon, Date = weatherData.WeatherList[i].DtTxt.Substring(0, 10), Description = weatherData.WeatherList[i].Weather[0].Description, Temperature = weatherData.WeatherList[i].Main.Temperature, MinTemperature = weatherData.WeatherList[i].Main.MinTemperature, MaxTemperature = weatherData.WeatherList[i].Main.MaxTemperature, WindSpeed = weatherData.WeatherList[i].Wind.WindSpeed, Humidity = weatherData.WeatherList[i].Main.Humidity, FirstWater = tidalEventsData[tempDayCounter].getTypeAndHeight(), FirstWaterHeight = tidalEventsData[tempDayCounter].Height.ToString("0.##"), SecondWater = tidalEventsData[tempDayCounter + 1].getTypeAndHeight(), SecondWaterHeight = tidalEventsData[tempDayCounter + 1].Height.ToString("0.##"), ThirdWater = tidalEventsData[tempDayCounter + 2].getTypeAndHeight(), ThirdWaterHeight = tidalEventsData[tempDayCounter + 2].Height.ToString("0.##"), FourthWater = tidalEventsData[tempDayCounter + 3].getTypeAndHeight(), FourthWaterHeight = tidalEventsData[tempDayCounter + 3].Height.ToString("0.##") }); tempDayCounter = tempDayCounter + 4; } else if (tidalEventsData.ElementAtOrDefault(tempDayCounter + 2) != null && tidalEventsData[tempDayCounter + 2].DateTime.Substring(8, 2) == currentDate) { tidalAndWeathers.Add(new TidalAndWeather() { City = stationData.Properties.Name, Icon = weatherData.WeatherList[i].Weather[0].Icon, Date = weatherData.WeatherList[i].DtTxt.Substring(0, 10), Description = weatherData.WeatherList[i].Weather[0].Description, Temperature = weatherData.WeatherList[i].Main.Temperature, MinTemperature = weatherData.WeatherList[i].Main.MinTemperature, MaxTemperature = weatherData.WeatherList[i].Main.MaxTemperature, WindSpeed = weatherData.WeatherList[i].Wind.WindSpeed, Humidity = weatherData.WeatherList[i].Main.Humidity, FirstWater = tidalEventsData[tempDayCounter].getTypeAndHeight(), FirstWaterHeight = tidalEventsData[tempDayCounter].Height.ToString("0.##"), SecondWater = tidalEventsData[tempDayCounter + 1].getTypeAndHeight(), SecondWaterHeight = tidalEventsData[tempDayCounter + 1].Height.ToString("0.##"), ThirdWater = tidalEventsData[tempDayCounter + 2].getTypeAndHeight(), ThirdWaterHeight = tidalEventsData[tempDayCounter + 2].Height.ToString("0.##"), }); tempDayCounter = tempDayCounter + 3; } else if (tidalEventsData.ElementAtOrDefault(tempDayCounter + 1) != null && tidalEventsData[tempDayCounter + 1].DateTime.Substring(8, 2) == currentDate) { tidalAndWeathers.Add(new TidalAndWeather() { City = stationData.Properties.Name, Icon = weatherData.WeatherList[i].Weather[0].Icon, Date = weatherData.WeatherList[i].DtTxt.Substring(0, 10), Description = weatherData.WeatherList[i].Weather[0].Description, Temperature = weatherData.WeatherList[i].Main.Temperature, MinTemperature = weatherData.WeatherList[i].Main.MinTemperature, MaxTemperature = weatherData.WeatherList[i].Main.MaxTemperature, WindSpeed = weatherData.WeatherList[i].Wind.WindSpeed, Humidity = weatherData.WeatherList[i].Main.Humidity, FirstWater = tidalEventsData[tempDayCounter].getTypeAndHeight(), FirstWaterHeight = tidalEventsData[tempDayCounter].Height.ToString("0.##"), SecondWater = tidalEventsData[tempDayCounter + 1].getTypeAndHeight(), SecondWaterHeight = tidalEventsData[tempDayCounter + 1].Height.ToString("0.##"), }); tempDayCounter = tempDayCounter + 2; } else if (tidalEventsData.ElementAtOrDefault(tempDayCounter) != null && tidalEventsData[tempDayCounter].DateTime.Substring(8, 2) == currentDate) { tidalAndWeathers.Add(new TidalAndWeather() { City = stationData.Properties.Name, Icon = weatherData.WeatherList[i].Weather[0].Icon, Date = weatherData.WeatherList[i].DtTxt.Substring(0, 10), Description = weatherData.WeatherList[i].Weather[0].Description, Temperature = weatherData.WeatherList[i].Main.Temperature, MinTemperature = weatherData.WeatherList[i].Main.MinTemperature, MaxTemperature = weatherData.WeatherList[i].Main.MaxTemperature, WindSpeed = weatherData.WeatherList[i].Wind.WindSpeed, Humidity = weatherData.WeatherList[i].Main.Humidity, FirstWater = tidalEventsData[tempDayCounter].getTypeAndHeight(), FirstWaterHeight = tidalEventsData[tempDayCounter].Height.ToString("0.##"), }); tempDayCounter = tempDayCounter + 1; } if (isAdded != false) { int tempDate = Int32.Parse(currentDate) + 1; if (tempDate.ToString().Length == 1) { currentDate = $"0{tempDate.ToString()}"; } else { currentDate = tempDate.ToString(); } } isAdded = true; } } await Navigation.PushAsync(new TidalDetailPage(tidalAndWeathers)); } else { await DisplayAlert("Alert", "There is no tidal data for given location.", "OK"); } } else if (howManyDays == "0") { await DisplayAlert("Alert", "You must choose how many days you want to see!", "OK"); } }