def update(self): """Get the latest data from Google.""" options_copy = self._config_entry.options.copy() dtime = options_copy.get(CONF_DEPARTURE_TIME) atime = options_copy.get(CONF_ARRIVAL_TIME) if dtime is not None and ":" in dtime: options_copy[CONF_DEPARTURE_TIME] = convert_time_to_utc(dtime) elif dtime is not None: options_copy[CONF_DEPARTURE_TIME] = dtime elif atime is None: options_copy[CONF_DEPARTURE_TIME] = "now" if atime is not None and ":" in atime: options_copy[CONF_ARRIVAL_TIME] = convert_time_to_utc(atime) elif atime is not None: options_copy[CONF_ARRIVAL_TIME] = atime self._resolved_origin = find_coordinates(self.hass, self._origin) self._resolved_destination = find_coordinates(self.hass, self._destination) _LOGGER.debug( "Getting update for origin: %s destination: %s", self._resolved_origin, self._resolved_destination, ) if self._resolved_destination is not None and self._resolved_origin is not None: self._matrix = distance_matrix( self._client, self._resolved_origin, self._resolved_destination, **options_copy, )
def update(self): """Fetch new state data for the sensor.""" _LOGGER.debug("Fetching Route for %s", self._attr_name) self._waze_data.origin = find_coordinates(self.hass, self._origin) self._waze_data.destination = find_coordinates(self.hass, self._destination) self._waze_data.update()
def update(self): """Get the latest data from Google.""" options_copy = self._config_entry.options.copy() dtime = options_copy.get(CONF_DEPARTURE_TIME) atime = options_copy.get(CONF_ARRIVAL_TIME) if dtime is not None and ":" in dtime: options_copy[CONF_DEPARTURE_TIME] = convert_time_to_utc(dtime) elif dtime is not None: options_copy[CONF_DEPARTURE_TIME] = dtime elif atime is None: options_copy[CONF_DEPARTURE_TIME] = "now" if atime is not None and ":" in atime: options_copy[CONF_ARRIVAL_TIME] = convert_time_to_utc(atime) elif atime is not None: options_copy[CONF_ARRIVAL_TIME] = atime # Convert device_trackers to google friendly location if hasattr(self, "_origin_entity_id"): self._origin = find_coordinates(self.hass, self._origin_entity_id) if hasattr(self, "_destination_entity_id"): self._destination = find_coordinates(self.hass, self._destination_entity_id) if self._destination is not None and self._origin is not None: self._matrix = distance_matrix( self._client, self._origin, self._destination, **options_copy )
def is_valid_config_entry(hass, origin, destination, region): """Return whether the config entry data is valid.""" origin = find_coordinates(hass, origin) destination = find_coordinates(hass, destination) try: WazeRouteCalculator(origin, destination, region).calc_all_routes_info() except WRCError: return False return True
def is_valid_config_entry(hass, api_key, origin, destination): """Return whether the config entry data is valid.""" origin = find_coordinates(hass, origin) destination = find_coordinates(hass, destination) client = Client(api_key, timeout=10) try: distance_matrix(client, origin, destination, mode="driving") except ApiError: return False return True
async def async_update(self) -> None: """Update Sensor Information.""" # Convert device_trackers to HERE friendly location if self._origin_entity_id is not None: self._here_data.origin = find_coordinates(self.hass, self._origin_entity_id) if self._destination_entity_id is not None: self._here_data.destination = find_coordinates( self.hass, self._destination_entity_id ) await self.hass.async_add_executor_job(self._here_data.update)
def update(self): """Fetch new state data for the sensor.""" _LOGGER.debug("Fetching Route for %s", self._attr_name) # Get origin latitude and longitude from entity_id. if self._origin_entity_id is not None: self._waze_data.origin = find_coordinates(self.hass, self._origin_entity_id) # Get destination latitude and longitude from entity_id. if self._destination_entity_id is not None: self._waze_data.destination = find_coordinates( self.hass, self._destination_entity_id ) self._waze_data.update()
async def test_coordinates_function_returns_state_if_no_coords(hass): """Test test_coordinates function.""" hass.states.async_set( "test.object", "abc", ) assert location.find_coordinates(hass, "test.object") == "abc"
async def test_coordinates_function_returns_none_if_invalid_coord(hass): """Test test_coordinates function.""" hass.states.async_set( "test.object", "abc", ) assert location.find_coordinates(hass, "test.object") is None
def test_coordinates_function_returns_none_on_recursion(hass): """Test coordinates function.""" hass.states.async_set( "test.first", "test.second", ) hass.states.async_set("test.second", "test.first") assert location.find_coordinates(hass, "test.first") is None
async def test_coordinates_function_as_attributes(hass): """Test coordinates function.""" hass.states.async_set("test.object", "happy", { "latitude": 32.87336, "longitude": -117.22943 }) assert location.find_coordinates(hass, "test.object") == "32.87336,-117.22943"
async def test_coordinates_function_zone_friendly_name(hass): """Test coordinates function.""" hass.states.async_set( "zone.home", "zoning", { "latitude": 32.87336, "longitude": -117.22943, ATTR_FRIENDLY_NAME: "my_home" }, ) hass.states.async_set( "test.object", "my_home", ) assert location.find_coordinates(hass, "test.object") == "32.87336,-117.22943" assert location.find_coordinates(hass, "my_home") == "32.87336,-117.22943"
async def test_coordinates_function_device_tracker_in_zone(hass): """Test coordinates function.""" hass.states.async_set( "zone.home", "zoning", {"latitude": 32.87336, "longitude": -117.22943}, ) hass.states.async_set("device_tracker.device", "home") assert ( location.find_coordinates(hass, "device_tracker.device") == "32.87336,-117.22943" )
async def test_coordinates_function_device_tracker_from_input_select(hass): """Test coordinates function.""" hass.states.async_set( "input_select.select", "device_tracker.device", {"options": "device_tracker.device"}, ) hass.states.async_set("device_tracker.device", "32.87336,-117.22943") assert (location.find_coordinates( hass, "input_select.select") == "32.87336,-117.22943")
def _prepare_parameters( self, ) -> tuple[list[str], list[str], str | None, str | None]: """Prepare parameters for the HERE api.""" if self.config.origin_entity_id is not None: origin = find_coordinates(self.hass, self.config.origin_entity_id) else: origin = self.config.origin if self.config.destination_entity_id is not None: destination = find_coordinates(self.hass, self.config.destination_entity_id) else: destination = self.config.destination if destination is None: raise InvalidCoordinatesException("Destination must be configured") try: here_formatted_destination = destination.split(",") vol.Schema(cv.gps(here_formatted_destination)) except (vol.Invalid) as ex: raise InvalidCoordinatesException( f"{destination} are not valid coordinates") from ex if origin is None: raise InvalidCoordinatesException("Origin must be configured") try: here_formatted_origin = origin.split(",") vol.Schema(cv.gps(here_formatted_origin)) except (AttributeError, vol.Invalid) as ex: raise InvalidCoordinatesException( f"{origin} are not valid coordinates") from ex arrival: str | None = None departure: str | None = None if self.config.arrival is not None: arrival = convert_time_to_isodate(self.config.arrival) if self.config.departure is not None: departure = convert_time_to_isodate(self.config.departure) if arrival is None and departure is None: departure = "now" return (here_formatted_origin, here_formatted_destination, arrival, departure)
def _from_entity_id(entity_id: str) -> list[str]: coordinates = find_coordinates(self.hass, entity_id) if coordinates is None: raise InvalidCoordinatesException( f"No coordinatnes found for {entity_id}") try: here_formatted_coordinates = coordinates.split(",") vol.Schema(cv.gps(here_formatted_coordinates)) except (AttributeError, vol.Invalid) as ex: raise InvalidCoordinatesException( f"{coordinates} are not valid coordinates") from ex return here_formatted_coordinates
def test_coordinates_function_returns_input_if_no_coords(hass): """Test test_coordinates function.""" assert location.find_coordinates(hass, "test.abc") == "test.abc" assert location.find_coordinates(hass, "abc") == "abc"
def _update(self) -> HERERoutingData | None: """Get the latest data from the HERE Routing API.""" if self.config.origin_entity_id is not None: origin = find_coordinates(self.hass, self.config.origin_entity_id) else: origin = self.config.origin if self.config.destination_entity_id is not None: destination = find_coordinates(self.hass, self.config.destination_entity_id) else: destination = self.config.destination if destination is not None and origin is not None: here_formatted_destination = destination.split(",") here_formatted_origin = origin.split(",") arrival: str | None = None departure: str | None = None if self.config.arrival is not None: arrival = convert_time_to_isodate(self.config.arrival) if self.config.departure is not None: departure = convert_time_to_isodate(self.config.departure) if arrival is None and departure is None: departure = "now" _LOGGER.debug( "Requesting route for origin: %s, destination: %s, route_mode: %s, mode: %s, traffic_mode: %s, arrival: %s, departure: %s", here_formatted_origin, here_formatted_destination, RouteMode[self.config.route_mode], RouteMode[self.config.travel_mode], RouteMode[TRAFFIC_MODE_ENABLED], arrival, departure, ) response: RoutingResponse = self._api.public_transport_timetable( here_formatted_origin, here_formatted_destination, True, [ RouteMode[self.config.route_mode], RouteMode[self.config.travel_mode], RouteMode[TRAFFIC_MODE_ENABLED], ], arrival=arrival, departure=departure, ) _LOGGER.debug( "Raw response is: %s", response.response # pylint: disable=no-member ) attribution: str | None = None if "sourceAttribution" in response.response: # pylint: disable=no-member attribution = build_hass_attribution( response.response.get("sourceAttribution")) # pylint: disable=no-member route: list = response.response["route"] # pylint: disable=no-member summary: dict = route[0]["summary"] waypoint: list = route[0]["waypoint"] distance: float = summary["distance"] traffic_time: float = summary["baseTime"] if self.config.travel_mode in TRAVEL_MODES_VEHICLE: traffic_time = summary["trafficTime"] if self.config.units == CONF_UNIT_SYSTEM_IMPERIAL: # Convert to miles. distance = distance / 1609.344 else: # Convert to kilometers distance = distance / 1000 return HERERoutingData({ ATTR_ATTRIBUTION: attribution, ATTR_DURATION: summary["baseTime"] / 60, # type: ignore[misc] ATTR_DURATION_IN_TRAFFIC: traffic_time / 60, ATTR_DISTANCE: distance, ATTR_ROUTE: response.route_short, ATTR_ORIGIN: ",".join(here_formatted_origin), ATTR_DESTINATION: ",".join(here_formatted_destination), ATTR_ORIGIN_NAME: waypoint[0]["mappedRoadName"], ATTR_DESTINATION_NAME: waypoint[1]["mappedRoadName"], }) return None
async def test_coordinates_function_as_state(hass): """Test coordinates function.""" hass.states.async_set("test.object", "32.87336,-117.22943") assert location.find_coordinates(hass, "test.object") == "32.87336,-117.22943"
def test_coordinates_function_returns_none_if_invalid_input(hass): """Test test_coordinates function.""" assert location.find_coordinates(hass, "test.abc") is None