def get_forecast(condition): """ Hits database API e.g. data point for forecast data Args: * condition (condition) """ try: action_forecast = self.cache.get_forecast( self.time, self.loc, condition.variable) except ForecastNotCachedException: conn = datapoint.connection(api_key=DATAPOINT_KEY) site = conn.get_nearest_site(latitude=self.loc.lat, longitude=self.loc.lon) forecast = conn.get_forecast_for_site( site.id, frequency=DP_FORECAST_FREQUENCY) timesteps = [ step for day in forecast.days for step in day.timesteps ] self.cache.cache_forecast(timesteps, self.loc) action_forecast = self.cache.get_forecast( self.time, self.loc, condition.variable) return action_forecast
def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Met Office weather platform.""" import datapoint as dp name = config.get(CONF_NAME) datapoint = dp.connection(api_key=config.get(CONF_API_KEY)) latitude = config.get(CONF_LATITUDE, hass.config.latitude) longitude = config.get(CONF_LONGITUDE, hass.config.longitude) if None in (latitude, longitude): _LOGGER.error("Latitude or longitude not set in Home Assistant config") return try: site = datapoint.get_nearest_site( latitude=latitude, longitude=longitude) except dp.exceptions.APIException as err: _LOGGER.error("Received error from Met Office Datapoint: %s", err) return if not site: _LOGGER.error("Unable to get nearest Met Office forecast site") return data = MetOfficeCurrentData(hass, datapoint, site) try: data.update() except (ValueError, dp.exceptions.APIException) as err: _LOGGER.error("Received error from Met Office Datapoint: %s", err) return add_entities([MetOfficeWeather(site, data, name)], True)
def setup_platform(hass, config, add_devices, discovery_info=None): """Set up the Metoffice sensor platform.""" import datapoint as dp datapoint = dp.connection(api_key=config.get(CONF_API_KEY)) latitude = config.get(CONF_LATITUDE, hass.config.latitude) longitude = config.get(CONF_LONGITUDE, hass.config.longitude) if None in (latitude, longitude): _LOGGER.error("Latitude or longitude not set in Home Assistant config") return False try: site = datapoint.get_nearest_site(latitude=latitude, longitude=longitude) except dp.exceptions.APIException as err: _LOGGER.error("Received error from Met Office Datapoint: %s", err) return False if not site: _LOGGER.error("Unable to get nearest Met Office forecast site") return False # Get data data = MetOfficeCurrentData(hass, datapoint, site) try: data.update() except (ValueError, dp.exceptions.APIException) as err: _LOGGER.error("Received error from Met Office Datapoint: %s", err) return False # Add add_devices([MetOfficeCurrentSensor(site, data, variable) for variable in config[CONF_MONITORED_CONDITIONS]]) return True
def setup_platform(hass, config, add_devices, discovery_info=None): """Set up the Met Office weather platform.""" import datapoint as dp name = config.get(CONF_NAME) datapoint = dp.connection(api_key=config.get(CONF_API_KEY)) latitude = config.get(CONF_LATITUDE, hass.config.latitude) longitude = config.get(CONF_LONGITUDE, hass.config.longitude) if None in (latitude, longitude): _LOGGER.error("Latitude or longitude not set in Home Assistant config") return try: site = datapoint.get_nearest_site(latitude=latitude, longitude=longitude) except dp.exceptions.APIException as err: _LOGGER.error("Received error from Met Office Datapoint: %s", err) return if not site: _LOGGER.error("Unable to get nearest Met Office forecast site") return data = MetOfficeCurrentData(hass, datapoint, site) try: data.update() except (ValueError, dp.exceptions.APIException) as err: _LOGGER.error("Received error from Met Office Datapoint: %s", err) return add_devices([MetOfficeWeather(site, data, name)], True)
def get_metoffice(): """Return the temperature from the metoffice""" # Get temperature from met office conn = datapoint.connection(api_key=config.DATAPOINT_API_KEY) # Use similar retry code to above. Again, could do with doing properly. max_retries = 10 con_error = None for i in range(max_retries): try: site = conn.get_nearest_forecast_site(*config.COORDS_DATAPOINT) forecast = conn.get_forecast_for_site(site.id, "3hourly") current_timestep = forecast.now() return current_timestep.temperature.value except datapoint.exceptions.APIException as con_error: t, v, tb = sys.exc_info() print('datapoint try ' + str(i) + ' failed') print('Error message:') print(sys.exc_info()) sleep(5) pass else: break else: #raise t, v, tb print(sys.exc_info())
def get_met_office_temp(): con = datapoint.connection(api_key=config.DATAPOINT_API_KEY) # MET_COORDS is a tuple, so unpack it in the argument location = con.get_nearest_forecast_site(*config.MET_COORDS) forecast = con.get_forecast_for_site(location.id, '3hourly') # Only get the next 24 hours of forecasts # A check of each timestamp against an end date seems easiest given the # structure of datapoint tomorrow = datetime.datetime.now( datetime.timezone.utc) + datetime.timedelta(days=1) now = datetime.datetime.now(datetime.timezone.utc) min_temp = forecast.days[0].timesteps[0].temperature.value # Date is stored as a datetime object not an 'element' min_temp_time = forecast.days[0].timesteps[0].date for day in forecast.days: for timestep in day.timesteps: if timestep.date < tomorrow and timestep.date > now: if timestep.temperature.value < min_temp: min_temp = timestep.temperature.value min_temp_time = timestep.date return min_temp, min_temp_time
def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Met Office sensor platform.""" api_key = config.get(CONF_API_KEY) latitude = config.get(CONF_LATITUDE, hass.config.latitude) longitude = config.get(CONF_LONGITUDE, hass.config.longitude) name = config.get(CONF_NAME) datapoint = dp.connection(api_key=api_key) if None in (latitude, longitude): _LOGGER.error("Latitude or longitude not set in Home Assistant config") return try: site = datapoint.get_nearest_site(latitude=latitude, longitude=longitude) except dp.exceptions.APIException as err: _LOGGER.error("Received error from Met Office Datapoint: %s", err) return if not site: _LOGGER.error("Unable to get nearest Met Office forecast site") return data = MetOfficeCurrentData(hass, datapoint, site) data.update() if data.data is None: return sensors = [] for variable in config[CONF_MONITORED_CONDITIONS]: sensors.append(MetOfficeCurrentSensor(site, data, variable, name)) add_entities(sensors, True)
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up a Met Office entry.""" latitude = entry.data[CONF_LATITUDE] longitude = entry.data[CONF_LONGITUDE] api_key = entry.data[CONF_API_KEY] site_name = entry.data[CONF_NAME] connection = datapoint.connection(api_key=api_key) site = await hass.async_add_executor_job(fetch_site, connection, latitude, longitude) if site is None: raise ConfigEntryNotReady() async def async_update_3hourly() -> MetOfficeData: return await hass.async_add_executor_job(fetch_data, connection, site, MODE_3HOURLY) async def async_update_daily() -> MetOfficeData: return await hass.async_add_executor_job(fetch_data, connection, site, MODE_DAILY) metoffice_hourly_coordinator = DataUpdateCoordinator( hass, _LOGGER, name=f"MetOffice Hourly Coordinator for {site_name}", update_method=async_update_3hourly, update_interval=DEFAULT_SCAN_INTERVAL, ) metoffice_daily_coordinator = DataUpdateCoordinator( hass, _LOGGER, name=f"MetOffice Daily Coordinator for {site_name}", update_method=async_update_daily, update_interval=DEFAULT_SCAN_INTERVAL, ) metoffice_hass_data = hass.data.setdefault(DOMAIN, {}) metoffice_hass_data[entry.entry_id] = { METOFFICE_HOURLY_COORDINATOR: metoffice_hourly_coordinator, METOFFICE_DAILY_COORDINATOR: metoffice_daily_coordinator, METOFFICE_NAME: site_name, METOFFICE_COORDINATES: f"{latitude}_{longitude}", } # Fetch initial data so we have data when entities subscribe await asyncio.gather( metoffice_hourly_coordinator.async_config_entry_first_refresh(), metoffice_daily_coordinator.async_config_entry_first_refresh(), ) await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS) return True
def main(request_dict): """ """ origin = request_dict['origin'] destination = request_dict['destination'] options = request_dict['options'] fcst_points = request_dict['fcst_points'] start_time = sort_time(request_dict['start_time']) google_req_url = google_dir_url.format(olat=origin["latitude"], olon=origin["longitude"], dlat=destination["latitude"], dlon=destination["longitude"], opts=options) directions_request = requests.get(google_req_url) directions_json = directions_request.json() # The directions_json is structured to hold multiple sets of directions for # multiple routes and legs. This module will only handle one route with one # leg. Check this and extract this leg, and call it the journey. journey_dict = get_journey(directions_json) journey_steps = create_steps(journey_dict) journey = Journey(journey_steps) # According to how many forecast points along the journey are required, # work out the distance between each point. travel_dist = journey.distance / (fcst_points - 1) # Open up datapoint connection conn = datapoint.connection(api_key=API_key) start_site = conn.get_nearest_site(journey.location.x, journey.location.y) start_forecast = get_forecast(conn, start_site, start_time) print start_time.isoformat() forecasts = [ create_forecast_dict(start_site.longitude, start_site.latitude, start_forecast, start_time.isoformat()) ] while journey.location != journey.destination: journey.travel_distance(travel_dist) time = start_time + \ datetime.timedelta(seconds=journey.duration_travelled) site = conn.get_nearest_site(journey.location.x, journey.location.y) forecast = get_forecast(conn, site, time) forecasts.append( create_forecast_dict(site.longitude, site.latitude, forecast, time.isoformat())) response_dict = convert_dict_to_json({"journey": forecasts}) print_response(response_dict)
def __init__(self, hass, api_key, latitude, longitude): """Initialize the data object.""" self._hass = hass self._datapoint = datapoint.connection(api_key=api_key) self._site = None # Public attributes self.latitude = latitude self.longitude = longitude # Holds the current data from the Met Office self.site_id = None self.site_name = None self.now = None
def setUp(self, mock_request): with open("{}/datapoint.json".format( pathlib.Path(__file__).parent.absolute())) as f: mock_json = json.load(f) self.all_sites = json.dumps(mock_json['all_sites']) self.wavertree_hourly = json.dumps(mock_json['wavertree_hourly']) self.wavertree_daily = json.dumps(mock_json['wavertree_daily']) self.kingslynn_hourly = json.dumps(mock_json['kingslynn_hourly']) self.conn = datapoint.connection( api_key="abcdefgh-acbd-abcd-abcd-abcdefghijkl") mock_request.get('/public/data/val/wxfcs/all/json/sitelist/', text=self.all_sites) self.wavertree = self.conn.get_nearest_forecast_site( 53.38374, -2.90929) self.kingslynn = self.conn.get_nearest_forecast_site(52.75556, 0.44231)
async def validate_input(hass: core.HomeAssistant, data): """Validate that the user input allows us to connect to DataPoint. Data has the keys from DATA_SCHEMA with values provided by the user. """ latitude = data[CONF_LATITUDE] longitude = data[CONF_LONGITUDE] api_key = data[CONF_API_KEY] connection = datapoint.connection(api_key=api_key) site = await hass.async_add_executor_job(fetch_site, connection, latitude, longitude) if site is None: raise CannotConnect() return {"site_name": site.name}
def __init__(self, home_coords, work_coords, api_key, in_time=8, out_time=17): self.home_coords = home_coords self.work_coords = work_coords self.in_time = np.round(in_time, 0).astype(int) self.out_time = np.round(out_time, 0).astype(int) self.conn = datapoint.connection(api_key=api_key) self.testing = True if self.testing: self.day_num = 1 else: self.day_num = 0 self._variable_initalise() self.results = {}
def get_forecast(condition): """ Hits database API e.g. data point for forecast data Args: * condition (condition) """ try: action_forecast = self.cache.get_forecast(self.time, self.loc, condition.variable) except ForecastNotCachedException: conn = datapoint.connection(api_key=DATAPOINT_KEY) site = conn.get_nearest_site(latitude=self.loc.lat, longitude=self.loc.lon) forecast = conn.get_forecast_for_site(site.id, frequency=DP_FORECAST_FREQUENCY) timesteps = [step for day in forecast.days for step in day.timesteps] self.cache.cache_forecast(timesteps, self.loc) action_forecast = self.cache.get_forecast(self.time, self.loc, condition.variable) return action_forecast
def setup_platform(hass, config, add_devices, discovery_info=None): """Set up the Met Office sensor platform.""" import datapoint as dp api_key = config.get(CONF_API_KEY) latitude = config.get(CONF_LATITUDE, hass.config.latitude) longitude = config.get(CONF_LONGITUDE, hass.config.longitude) name = config.get(CONF_NAME) datapoint = dp.connection(api_key=api_key) if None in (latitude, longitude): _LOGGER.error("Latitude or longitude not set in Home Assistant config") return try: site = datapoint.get_nearest_site( latitude=latitude, longitude=longitude) except dp.exceptions.APIException as err: _LOGGER.error("Received error from Met Office Datapoint: %s", err) return if not site: _LOGGER.error("Unable to get nearest Met Office forecast site") return data = MetOfficeCurrentData(hass, datapoint, site) data.update() if data.data is None: return sensors = [] for variable in config[CONF_MONITORED_CONDITIONS]: sensors.append(MetOfficeCurrentSensor(site, data, variable, name)) add_devices(sensors, True)
'20': '09d', # Sleet/hail showers '21': '09n', '25': '09n', '26': '09d', # Sleet/hail showers '18': '13d', '24': '13d', '25': '13n', '26': '13d', # Sleet/snow '27': '13d', # Sleet/snow '28': '11d', '29': '11d', '30': '11d' } # Thunder storm # Set up a datapoint connection conn = datapoint.connection(api_key=KEY) # Find the nearest forecast site location to my input lat/lon site = conn.get_nearest_forecast_site(lat, lon) print(site.name) # Retrieve the forecast forecast = conn.get_forecast_for_site(site.id, "3hourly") # Set up some blank arrays in which to hold the forecast data icons = [] # Weather symbols times = [] # Forecast validity times weathernames = [] # Met Office weather type names # Loop through dates/times of the forecast to fill arrays for day in forecast.days:
import datapoint # Create connection to DataPoint with your API key conn = datapoint.connection(api_key="4449caa3-1a0b-4351-bd68-6e1ce103ebae") # Get the nearest site for my longitude and latitude site = conn.get_nearest_site(-0.124626, 51.500728) # Get a forecast for my nearest site with 3 hourly timesteps forecast = conn.get_forecast_for_site(site.id, "3hourly") # Get the current timestep from the forecast current_timestep = forecast.now() # Print out the site and current weather print(site.name, "-", current_timestep.weather.text)
import datapoint from datetime import datetime, timedelta from postcodes import PostCoder conn = datapoint.connection(api_key='your-key-here') def get_forecast(lon, lat): site = conn.get_nearest_site(lon, lat) return conn.get_forecast_for_site(site.id, "3hourly") def check_rain(forecast, hours): now = datetime.now() stop = now + timedelta(hours=hours) rain = 0 for index, day in enumerate(forecast.days): for timestep in day.timesteps: minutes_to_add = (index * 24 * 60) + timestep.name today = datetime(now.year, now.month, now.day) timestep_datetime = today + timedelta(minutes=minutes_to_add) if timestep_datetime > now and timestep_datetime < stop: rain = max(rain, timestep.precipitation.value) return rain def get_location_from_postcode(post_code): pc = PostCoder()
import datapoint as dp import numpy as np import yaml import footfall_model as fm conn = dp.connection(api_key="a1e2dddc-6528-496b-89ba-39bdaca995cc") for site in conn.get_all_sites(): if site.name == "Durham": break forecast = conn.get_forecast_for_site(site.id, "3hourly") output = [] streets = [['ss', 'Silver Street'], ['eb', 'Elvet Bridge']] fake_streets = [['x', 'Street X'], ['y', 'Street Y'], ['z', 'Street Z']] for i, street in enumerate(streets): output.append({'name': street[1], 'id': street[0]}) output[i]['days'] = [] for j, day in enumerate(forecast.days): dayn = day.date.strftime("%A") day_number_in_year = int(day.date.strftime("%j")) output[i]['days'].append({'dayname': dayn}) output[i]['days'][j]['temp'] = float( day.timesteps[4].temperature.value) output[i]['days'][j]['desc'] = day.timesteps[4].weather.text if street[0] == 'ss': op = fm.footfall_model(fm.ss16, day_number_in_year) if street[0] == 'eb':