Ejemplo n.º 1
0
 public static void Insert(WeatherEntry entry)
 {
     using (DAC dac = new DAC())
     {
         string statement = string.Format("INSERT INTO WeatherHistory (Latitude, Longitude, Temperature, Forecast, FetchedOn) VALUES ({0}, {1}, {2}, '{3}', '{4}');", entry.Latitude, entry.Longitude, entry.Temperature, entry.Forecast, entry.FetchedOn);
         dac.ExecuteCommand(statement);
     }
 }
Ejemplo n.º 2
0
        public HttpResponseMessage PostVal(long id, bool del)
        {
            WeatherEntry we = db.WeatherEntries.Find(id);

            db.WeatherValues.RemoveRange(we.WeatherValues);
            db.SaveChanges();
            db.WeatherEntries.Remove(we);
            db.SaveChanges();
            return(Request.CreateResponse(HttpStatusCode.OK, "deleted"));
        }
Ejemplo n.º 3
0
        public override void ExecuteCommand(ICharacter character, Identity target, string[] args)
        {
            Vector3 position = new Vector3();

            position.X = character.Coordinates().x;
            position.Y = character.Coordinates().y;
            position.Z = character.Coordinates().z;
            byte type = byte.Parse(args[1]);

            /*if (type == 2)
             * {
             *  // Set temperature
             *  WeatherControlMessageHandler.Default.Send(
             *      character,
             *      byte.Parse(args[1]),
             *      (byte)(sbyte.Parse(args[2])),
             *      byte.Parse(args[3]),
             *      byte.Parse(args[4]),
             *      byte.Parse(args[5]),
             *      byte.Parse(args[6]),
             *      byte.Parse(args[7]),
             *      byte.Parse(args[8]));
             * }
             * else*/
            {
                int ambientColor = Convert.ToInt32(args[13], 16);
                int fogColor     = Convert.ToInt32(args[14], 16);

                WeatherEntry newWeather = new WeatherEntry();
                newWeather.AmbientColor            = ambientColor;
                newWeather.FogColor                = fogColor;
                newWeather.Position                = position;
                newWeather.FadeIn                  = short.Parse(args[1]);
                newWeather.Duration                = int.Parse(args[2]);
                newWeather.FadeOut                 = short.Parse(args[3]);
                newWeather.Range                   = Single.Parse(args[4]);
                newWeather.WeatherType             = (WeatherType)byte.Parse(args[5]);
                newWeather.Intensity               = byte.Parse(args[6]);
                newWeather.Wind                    = byte.Parse(args[7]);
                newWeather.Clouds                  = byte.Parse(args[8]);
                newWeather.Thunderstrikes          = byte.Parse(args[9]);
                newWeather.Tremors                 = byte.Parse(args[10]);
                newWeather.ThunderstrikePercentage = byte.Parse(args[11]);
                newWeather.TremorPercentage        = byte.Parse(args[12]);
                newWeather.ZBufferVisibility       = byte.Parse(args[15]);
                newWeather.Playfield               = character.Playfield.Identity;

                WeatherSettings.Instance.Add(newWeather);

                WeatherControlMessageHandler.Default.Send(character, newWeather);
            }
        }
        public void Send(ICharacter character, WeatherEntry w, bool announceToPlayfield = false)
        {
            double secondsLate = (DateTime.UtcNow - w.StartTime).TotalMilliseconds;
            double fadeIn      = w.FadeIn / 6.0f;
            short  sFadeIn     = w.FadeIn;

            int duration = w.Duration;

            if (secondsLate > 0)
            {
                secondsLate -= fadeIn;

                fadeIn      = secondsLate < 0 ? -secondsLate : 1 / 6;
                secondsLate = secondsLate < 0 ? 0 : secondsLate;

                secondsLate -= duration * 1000;
                duration     = secondsLate < 0 ? Convert.ToInt32(-secondsLate / 1000) : 1;
                // secondsLate = secondsLate < 0 ? 0 : secondsLate;
                sFadeIn = Convert.ToInt16(fadeIn * 6);
            }

            Vector3 temp = w.Position;

            this.Send(
                character,
                w.Playfield,
                temp,
                sFadeIn,
                duration,
                w.FadeOut,
                w.Range,
                (byte)w.WeatherType,
                w.Intensity,
                w.Wind,
                w.Clouds,
                w.Thunderstrikes,
                w.Tremors,
                w.TremorPercentage,
                w.ThunderstrikePercentage,
                w.AmbientColor,
                w.FogColor,
                w.ZBufferVisibility,
                announceToPlayfield);
        }
Ejemplo n.º 5
0
        private static WeatherEntry Fetch(DbDataReader reader)
        {
            WeatherEntry entry = new WeatherEntry();

            try
            {
                if (!Convert.IsDBNull(reader["Latitude"]))
                {
                    entry.Latitude = (double)reader["Latitude"];
                }
                if (!Convert.IsDBNull(reader["Longitude"]))
                {
                    entry.Longitude = (double)reader["Longitude"];
                }
                if (!Convert.IsDBNull(reader["Temperature"]))
                {
                    entry.Temperature = (double)reader["Temperature"];
                }
                if (!Convert.IsDBNull(reader["Forecast"]))
                {
                    entry.Forecast = (string)reader["Forecast"];
                }
                if (!Convert.IsDBNull(reader["FetchedOn"]))
                {
                    entry.FetchedOn = Convert.ToDateTime((string)reader["FetchedOn"]);
                }

                if (double.IsInfinity(entry.Latitude))
                {
                    entry.Latitude = double.MaxValue;
                }
                if (double.IsInfinity(entry.Longitude))
                {
                    entry.Longitude = double.MaxValue;
                }
                if (double.IsInfinity(entry.Temperature))
                {
                    entry.Temperature = double.MaxValue;
                }
            }
            catch { }

            return(entry);
        }
Ejemplo n.º 6
0
 public IActionResult PostWeatherEntry(WeatherEntry entry)
 {
     using (ApplicationDbContext db = new ApplicationDbContext())
     {
         ClaimsPrincipal currentUser = User;
         if (currentUser.Identity.Name != null)
         {
             var currentUserID = currentUser.FindFirst(ClaimTypes.NameIdentifier).Value;
             entry.UserId = currentUserID;
         }
         if (ModelState.IsValid)
         {
             db.WeatherEntries.Add(entry);
             db.SaveChanges();
             return(StatusCode(200));
         }
         return(Content("Failed To Create"));
     }
 }
Ejemplo n.º 7
0
        public async static Task ReadWeather()
        {
            WeatherRead = false;

            //ignore if weather is read very recently
            if (CurrentWeather != null && DateTime.Now.Subtract(CurrentWeather.FetchedOn).TotalMinutes < Constants.WEATHER_READ_INTERVAL)
            {
                return;
            }

            try
            {
                if (LocationHelper.CurrentPosition == null)
                {
                    await LocationHelper.ReadLocation(false);
                }

                if (LocationHelper.CurrentPosition != null)
                {
                    WeatherEntry entry = new WeatherEntry();
                    entry.Latitude  = LocationHelper.CurrentPosition.Coordinate.Latitude;
                    entry.Longitude = LocationHelper.CurrentPosition.Coordinate.Longitude;

                    WeatherDetails weatherDetails = Wunderground.GetWeather(entry.Latitude, entry.Longitude);
                    if (weatherDetails != null)
                    {
                        entry.Temperature = Math.Round(weatherDetails.CurrentWeather.Temperature_C_Min, 2);
                    }

                    entry.Forecast  = Wunderground.GetForecast(entry.Latitude, entry.Longitude);
                    entry.FetchedOn = DateTime.Now;
                    CurrentWeather  = entry;
                    WeatherHistoryDAC.Insert(CurrentWeather);

                    WeatherRead = true;
                }
            }
            catch (Exception exception)
            {
                Log.Error(exception);
            }
        }
Ejemplo n.º 8
0
        public void TestWeatherEntryParse()
        {
            var demoData = Automatica.Core.Driver.Utility.Utils.StringToByteArray("40F95912010000002801000003000000370000000000000000002A40CDCCCCCCCCCC2540E8034EEFA9DA10400000000000000000CDCCCCCCCCCC0C4000000000000C9040");

            var weather = WeatherEntry.Parse(demoData);

            Assert.NotNull(weather);

            Assert.Equal(1027, weather.BarometicPressure);
            Assert.Equal(4.2, Math.Round(weather.DewPoint, 1));
            Assert.Equal(10.9, weather.PerceivedTemperature);

            Assert.Equal(0, weather.Precipitation);
            Assert.Equal(55, weather.RelativeHumidity);
            Assert.Equal(3, weather.SolarRadiation);
            Assert.Equal(13, weather.Temperature);
            Assert.Equal(307886400, weather.Timestamp);
            Assert.Equal(1, weather.WeatherType);

            Assert.Equal(296, weather.WindDirection);
            Assert.Equal(3.6, weather.WindSpeed);
        }
Ejemplo n.º 9
0
        public override void ExecuteCommand(ICharacter character, Identity target, string[] args)
        {
            Vector3 position = new Vector3();
            position.X = character.Coordinates().x;
            position.Y = character.Coordinates().y;
            position.Z = character.Coordinates().z;
            byte type = byte.Parse(args[1]);
            /*if (type == 2)
            {
                // Set temperature
                WeatherControlMessageHandler.Default.Send(
                    character,
                    byte.Parse(args[1]),
                    (byte)(sbyte.Parse(args[2])),
                    byte.Parse(args[3]),
                    byte.Parse(args[4]),
                    byte.Parse(args[5]),
                    byte.Parse(args[6]),
                    byte.Parse(args[7]),
                    byte.Parse(args[8]));
            }
            else*/
            {
                int ambientColor = Convert.ToInt32(args[13], 16);
                int fogColor = Convert.ToInt32(args[14], 16);

                WeatherEntry newWeather = new WeatherEntry();
                newWeather.AmbientColor = ambientColor;
                newWeather.FogColor = fogColor;
                newWeather.Position = position;
                newWeather.FadeIn = short.Parse(args[1]);
                newWeather.Duration = int.Parse(args[2]);
                newWeather.FadeOut = short.Parse(args[3]);
                newWeather.Range = Single.Parse(args[4]);
                newWeather.WeatherType = (WeatherType)byte.Parse(args[5]);
                newWeather.Intensity = byte.Parse(args[6]);
                newWeather.Wind = byte.Parse(args[7]);
                newWeather.Clouds = byte.Parse(args[8]);
                newWeather.Thunderstrikes = byte.Parse(args[9]);
                newWeather.Tremors = byte.Parse(args[10]);
                newWeather.ThunderstrikePercentage = byte.Parse(args[11]);
                newWeather.TremorPercentage = byte.Parse(args[12]);
                newWeather.ZBufferVisibility = byte.Parse(args[15]);
                newWeather.Playfield = character.Playfield.Identity;

                WeatherSettings.Instance.Add(newWeather);

                WeatherControlMessageHandler.Default.Send(character, newWeather);
            }
        }
Ejemplo n.º 10
0
        public HttpResponseMessage GetWeather()
        {
            // get forecast from AccuWeather and save in DB
            // this needs to get called hourly at about 5 past the hour (or 35 past if your time zone is a half hour off)

            using (WebClient client = new WebClient())
            {
                var             resp       = client.DownloadString("http://dataservice.accuweather.com/forecasts/v1/hourly/12hour/" + Resources.LocationId + "?apikey=" + Resources.ApiKey + "&metric=true&details=true");
                var             now        = DateTime.UtcNow;
                DateTime        thisTime   = DateTime.Now;
                string          tzId       = Resources.TimeZoneId;
                TimeZoneInfo    tst        = TimeZoneInfo.FindSystemTimeZoneById(tzId);
                bool            isDaylight = tst.IsDaylightSavingTime(thisTime);
                WeatherObject[] response   = null;
                try
                {
                    response = JsonConvert.DeserializeObject <WeatherObject[]>(resp);
                }
                catch (Exception ex)
                {
                    Trace.Write(ex);
                }
                var LindsayTime = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(now, tst.Id);

                List <WeatherValue> wvs = new List <WeatherValue>();
                for (var i = 0; i < response.Length; i++)
                {
                    var w = response[i];
                    //w.PokeWeather = new PgoWeather();
                    WeatherTranslation wt = db.WeatherTranslations.Find(w.WeatherIcon);
                    int weatherId;
                    if (wt.CanWindy == true && (w.Wind.Speed.Value > 29 || w.WindGust.Speed.Value > 31)) // (OR IS IT SUM OF THESE ? 55? This works for me, anyway)
                    {
                        w.PokeWeather = db.PgoWeathers.Find(6);
                        weatherId     = 6;
                    }
                    else
                    {
                        weatherId = wt.PgoWeather.Id;
                    }

                    WeatherValue wv = new WeatherValue()
                    {
                        DateTime    = w.DateTime,
                        WeatherIcon = w.WeatherIcon,
                        IconPhrase  = w.IconPhrase,
                        IsDaylight  = w.IsDaylight,
                        TempUnit    = w.Temperature.Unit,
                        TempValue   = w.Temperature.Value,
                        WindSpeed   = w.Wind.Speed.Value,
                        WindUnit    = w.Wind.Speed.Unit,
                        GustSpeed   = w.WindGust.Speed.Value,
                        GustUnit    = w.WindGust.Speed.Unit,
                        PrecipitationProbability = w.PrecipitationProbability,
                        RainProbability          = w.RainProbability,
                        RainAmt         = w.Rain.Value,
                        RainUnit        = w.Rain.Unit,
                        SnowProbability = w.SnowProbability,
                        SnowAmt         = w.Snow.Value,
                        SnowUnit        = w.Snow.Unit,
                        IceProbability  = w.IceProbability,
                        IceAmt          = w.Ice.Value,
                        IceUnit         = w.Ice.Unit,
                        CloudCover      = w.CloudCover,
                        PgoIconId       = weatherId,
                        DateAdded       = now
                    };
                    wvs.Add(wv);
                }
                WeatherEntry entry = new WeatherEntry()
                {
                    DateCreated   = LindsayTime,
                    Date          = LindsayTime,
                    Hour          = LindsayTime.Hour,
                    WeatherValues = wvs
                };
                db.WeatherEntries.Add(entry);
                db.SaveChanges();
                return(Request.CreateResponse(HttpStatusCode.OK, "got it"));
            }
        }
Ejemplo n.º 11
0
        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"));
        }
Ejemplo n.º 12
0
        /// <summary>
        /// var data = google.visualization.arrayToDataTable([
        ///['Time', 'Temperature', 'Humidity'],
        ///['2004',  1000,      400],
        ///['2005',  1170,      460],
        ///['2006',  660,       1120],
        /// ['2007',  1030,      540]
        /// ]);
        /// </summary>
        /// <param name="docs"></param>
        /// <param name="fields"></param>
        /// <returns></returns>
        private List <object> weatherChartData(List <BsonDocument> docs, DataPoint fields = DataPoint.all)
        {
            var weatherData = new List <WeatherEntry>();

            if (fields == DataPoint.all)
            {
                docs.ForEach(doc =>
                {
                    weatherData.Add(new WeatherEntry(this.GetTime(doc[DBDeets.TimeKey].ToString()))
                    {
                        TEMPERATURE = double.Parse(doc[DBDeets.TemperatureKey].ToString()),
                        Humidity    = double.Parse(doc[DBDeets.HumidityKey].ToString()),
                        Brightness  = double.Parse(doc[DBDeets.BrightnessKey].ToString()),
                        WindSpeed   = double.Parse(doc[DBDeets.WindSpeedKey].ToString()),
                        WindDir     = doc[DBDeets.WindDirectionKey].ToString()
                    });
                });
            }
            else
            {
                docs.ForEach(doc =>
                {
                    //ALWAYS add Time
                    var newWeatherEntry = new WeatherEntry(this.GetTime(doc[DBDeets.TimeKey].ToString(), "d"));

                    //Add Temperature
                    if (fields.HasFlag(DataPoint.temperature))
                    {
                        newWeatherEntry.TEMPERATURE = double.Parse(doc[DBDeets.TemperatureKey].ToString());
                    }

                    //Add Humidity
                    if (fields.HasFlag(DataPoint.humidity))
                    {
                        newWeatherEntry.Humidity = double.Parse(doc[DBDeets.HumidityKey].ToString());
                    }

                    //Add brightness
                    if (fields.HasFlag(DataPoint.brightness))
                    {
                        newWeatherEntry.Brightness = double.Parse(doc[DBDeets.BrightnessKey].ToString());
                    }

                    //Add Wind Speed
                    if (fields.HasFlag(DataPoint.windSpeed))
                    {
                        newWeatherEntry.WindSpeed = double.Parse(doc[DBDeets.WindSpeedKey].ToString());
                    }

                    // Add wind direction
                    if (fields.HasFlag(DataPoint.windDirection))
                    {
                        doc[DBDeets.WindDirectionKey].ToString();
                    }


                    weatherData.Add(newWeatherEntry);
                });
            }
            var chart = Weather_Chart.ToGChartsArray(weatherData, fields);

            return(chart);
        }
Ejemplo n.º 13
0
        public void TestWeatherEntryParseFail2()
        {
            var demoData = Automatica.Core.Driver.Utility.Utils.StringToByteArray("010000002801000003000000370000000000000000002A40CDCCCCCCCCCC2540E8034EEFA9DA10400000000000000000CDCCCCCCCCCC0C4000000000000C9040");

            Assert.Throws <ArgumentException>(() => WeatherEntry.Parse(demoData));
        }
 public void Add(WeatherEntry entry)
 {
     WeatherEntry alreadyWeatherEntry =
         this.WeatherList.FirstOrDefault(
             x =>
                 (x.Playfield.Instance == entry.Playfield.Instance) && (x.Playfield.Type == entry.Playfield.Type));
     if (alreadyWeatherEntry != null)
     {
         this.WeatherList.Remove(alreadyWeatherEntry);
     }
     entry.StartTime = DateTime.UtcNow;
     this.WeatherList.Add(entry);
 }