示例#1
0
        private void DeviceEventHandler(object model, BasicDeliverEventArgs eventArgs)
        {
            try
            {
                var body    = eventArgs.Body;
                var message = Encoding.UTF8.GetString(body.ToArray());

                WriteLog($"Message received: {message}");

                var weatherMessage = JsonConvert.DeserializeObject <WeatherMessage>(message);

                if (weatherMessage.Type == MessageType.Text)
                {
                    WriteLog(weatherMessage.Message);

                    return;
                }

                _database.StoreWeatherData(weatherMessage);

                if (_hubConnection == null)
                {
                    return;
                }

                var weatherUpdate = new WeatherUpdate(weatherMessage, _database);

                try
                {
                    if (_hubConnection.State == HubConnectionState.Disconnected)
                    {
                        _hubConnection.StartAsync().Wait();
                    }

                    var json = JsonConvert.SerializeObject(weatherUpdate);

                    _hubConnection.InvokeAsync("SendLatestReading", json).Wait();
                }
                catch (Exception exception)
                {
                    WriteLog($"Hub exception: {exception}");
                }
            }
            catch (Exception exception)
            {
                WriteLog($"Exception: {exception}");

                throw;
            }
        }
示例#2
0
        private async void FetchWeather()
        {
            JsonObject json = await new HttpHelper(BuildRequest()).TryGetJsonAsync();

            if (json == null)
            {
                return;
            }

            JsonObject mainJson    = json.GetNamedObject("main");
            JsonObject weatherJson = json.GetNamedArray("weather").GetObjectAt(0);
            string     description = weatherJson.GetNamedString("main") + " - " + weatherJson.GetNamedString("description");
            var        weather     = new WeatherModel(mainJson.GetNamedNumber("temp") - 273.15, mainJson.GetNamedNumber("humidity"),
                                                      mainJson.GetNamedNumber("pressure") / 10, description, String.Format("http://openweathermap.org/img/w/{0}.png", weatherJson.GetNamedString("icon")));

            WeatherUpdate?.Invoke(this, new WeatherUpdateEventArgs(weather));
        }
示例#3
0
        public async Task Initialize()
        {
            DateTime lastestStartupDate;

            DateTime.TryParseExact(await DataManager.Current.GetValueAsync("latestStartupDate"), "yyyy-MM-dd",
                                   null, System.Globalization.DateTimeStyles.None, out lastestStartupDate);
            BackgroundServiceRunArgs = new AppServiceRunArgs(this, lastestStartupDate);
            //Services start up
            Cleaner.Start(BackgroundServiceRunArgs);//Always Run First
            WeatherUpdate.Start(BackgroundServiceRunArgs);
            TaskNotification.Start(BackgroundServiceRunArgs);


            //Timer starts up
            DateTime now = DateTime.Now;
            await Task.Delay((int)checked (60000 - now.Ticks / 10000 % 60000));

            timer.Start();
            //TimeLoop(timer, new EventArgs());
        }
示例#4
0
        public bool WeatherUpdate(WeatherUpdateAPI weatherUpdate)
        {
            using (_context = new ApplicationDbContext())
            {
                //Get device that sent the request with the current APIKey
                if (!ModelState.IsValid)
                {
                    throw new HttpResponseException(HttpStatusCode.BadRequest);
                }

                WeatherDevice currentDevice = _context.WeatherDevices.First(wd => wd.APIKey == weatherUpdate.APIKey);

                //Check if the device is currently null
                if (currentDevice == null)
                {
                    return(false);
                }

                //Create a new weather update with the associated values sent to the server
                WeatherUpdate newWeatherUpdate = new WeatherUpdate
                {
                    ParentDeviceID  = currentDevice.Id,
                    Temperature     = weatherUpdate.Temperature,
                    Humidity        = weatherUpdate.Humidity,
                    HeatIndex       = weatherUpdate.HeatIndex,
                    LPG             = weatherUpdate.LPG,
                    CarbonEmissions = weatherUpdate.CarbonEmissions,
                    Smoke           = weatherUpdate.Smoke
                };
                newWeatherUpdate.CalculateDewPoint();
                currentDevice.LatestWeatherUpdate = DateTime.Now;


                //Add the new weather update to the Database and Save
                _context.WeatherUpdates.Add(newWeatherUpdate);
                _context.SaveChanges();

                return(true);
            }
        }
        public async Task <IActionResult> PostWeatherUpdate([FromBody] WeatherUpdate weatherUpdate)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (!_context.Device.Any(d => d.DeviceId == weatherUpdate.DeviceId))
            {
                return(BadRequest("Device does not exist"));
            }

            weatherUpdate.TimeStamp       = DateTime.UtcNow;
            weatherUpdate.WeatherUpdateId = Guid.NewGuid();
            weatherUpdate.Humidity        = double.IsNaN(weatherUpdate.Humidity) ? 0 : weatherUpdate.Humidity;
            weatherUpdate.TemperatureC    = double.IsNaN(weatherUpdate.TemperatureC) ? 0 : weatherUpdate.TemperatureC;
            weatherUpdate.Windspeed       = double.IsNaN(weatherUpdate.Windspeed) ? 0 : weatherUpdate.Windspeed;

            _context.WeatherUpdate.Add(weatherUpdate);
            await _context.SaveChangesAsync();

            return(CreatedAtAction("GetWeatherUpdate", new { id = weatherUpdate.WeatherUpdateId }, weatherUpdate));
        }
 // Use this for initialization
 void Start()
 {
     weather = WeatherScriptHolder.GetComponent<WeatherUpdate>();
 }
示例#7
0
        public async Task UpdateWeatherAsync()
        {
            var woEidList = await _dbContext.Locations.Select(l => Tuple.Create(l.LocationId, l.WoeId)).ToListAsync();

            var client = _httpClientFactory.CreateClient();

            foreach (Tuple <long, long> tuple in woEidList)
            {
                var result = await client.GetStringAsync("https://www.metaweather.com/api/location/" + tuple.Item2);

                var weatherUpdateDto = JsonConvert.DeserializeObject <WeatherUpdateResultDto>(result);

                foreach (var consolidatedWeather in weatherUpdateDto.consolidated_weather)
                {
                    WeatherUpdate weatherUpdate = new WeatherUpdate()
                    {
                        LocationId           = tuple.Item1,
                        ApplicableDate       = consolidatedWeather.applicable_date,
                        WeatherStateName     = consolidatedWeather.weather_state_name,
                        WeatherStateAbbr     = consolidatedWeather.weather_state_abbr,
                        WindSpeed            = consolidatedWeather.wind_speed,
                        WindDirection        = consolidatedWeather.wind_direction,
                        WindDirectionCompass = consolidatedWeather.wind_direction_compass,
                        MinTemp        = consolidatedWeather.min_temp,
                        MaxTemp        = consolidatedWeather.max_temp,
                        CurrentTemp    = consolidatedWeather.the_temp,
                        AirPressure    = consolidatedWeather.air_pressure,
                        Humidity       = consolidatedWeather.humidity,
                        Visibility     = consolidatedWeather.visibility,
                        Predictability = consolidatedWeather.predictability
                    };

                    _dbContext.WeatherUpdates.Add(weatherUpdate);
                }

                LatestUpdate latestWeatherToBeUpdated = await _dbContext.LatestUpdates.FirstOrDefaultAsync(lu => lu.LocationId == tuple.Item1);

                consolidated_weather latestUpdate = weatherUpdateDto.consolidated_weather.OrderBy(cw => cw.applicable_date).FirstOrDefault();
                if (latestUpdate != null)
                {
                    if (latestWeatherToBeUpdated != null)
                    {
                        _dbContext.Entry(latestWeatherToBeUpdated).State = EntityState.Modified;
                    }
                    else
                    {
                        latestWeatherToBeUpdated            = new LatestUpdate();
                        latestWeatherToBeUpdated.LocationId = tuple.Item1;
                        _dbContext.LatestUpdates.Add(latestWeatherToBeUpdated);
                    }

                    latestWeatherToBeUpdated.ApplicableDate       = latestUpdate.applicable_date;
                    latestWeatherToBeUpdated.WeatherStateName     = latestUpdate.weather_state_name;
                    latestWeatherToBeUpdated.WeatherStateAbbr     = latestUpdate.weather_state_abbr;
                    latestWeatherToBeUpdated.WindSpeed            = latestUpdate.wind_speed;
                    latestWeatherToBeUpdated.WindDirection        = latestUpdate.wind_direction;
                    latestWeatherToBeUpdated.WindDirectionCompass = latestUpdate.wind_direction_compass;
                    latestWeatherToBeUpdated.MinTemp        = latestUpdate.min_temp;
                    latestWeatherToBeUpdated.MaxTemp        = latestUpdate.max_temp;
                    latestWeatherToBeUpdated.CurrentTemp    = latestUpdate.the_temp;
                    latestWeatherToBeUpdated.AirPressure    = latestUpdate.air_pressure;
                    latestWeatherToBeUpdated.Humidity       = latestUpdate.humidity;
                    latestWeatherToBeUpdated.Visibility     = latestUpdate.visibility;
                    latestWeatherToBeUpdated.Predictability = latestUpdate.predictability;
                }
            }

            await _dbContext.SaveChangesAsync();
        }