Beispiel #1
0
 def __get(self, data):
     url = Utils.build_url(self._base_url, extra_params=data)
     response = requests.get(url, timeout=self._timeout)
     try:
         json_data = json.loads(response.content.decode('utf8'))
         if json_data.get('Response') != None:
             return GeocoderResponse.new_from_jsondict(json_data)
         else:
             raise HEREError(json_data.get('Details', 'Error occured on function ' + sys._getframe(1).f_code.co_name))
     except ValueError as err:
         raise HEREError('Error occured on function ' + sys._getframe(1).f_code.co_name + ' ' + str(err))
 def __get(self, data, path, json_node):
     url = Utils.build_url(self._base_url + path, extra_params=data)
     response = requests.get(url, timeout=self._timeout)
     json_data = json.loads(response.content.decode('utf8'))
     if json_node in json_data.get('Res', {}):
         return PublicTransitResponse.new_from_jsondict(json_data)
     elif 'text' in json_data.get('Res', {}).get('Message', {}):
         return HEREError(
             json_data['Res']['Message']['text'],
             'Error occured on ' + sys._getframe(1).f_code.co_name)
     else:
         return HEREError('Error occured on ' +
                          sys._getframe(1).f_code.co_name)
def error_from_ev_charging_service_error(json_data: dict):
    """Return the correct subclass for ev charging errors"""

    if "Type" in json_data:
        error_type = json_data["Type"]
        message = json_data["Message"]

        if error_type == "Unauthorized":
            return UnauthorizedError(message)
    elif "error" in json_data and "error_description" in json_data:
        return HEREError("Error occured: " + json_data["error"] +
                         ", description: " + json_data["error_description"])
    # pylint: disable=W0212
    return HEREError("Error occured on " + sys._getframe(1).f_code.co_name)
    def forecast_astronomy(self,
                           destination,
                           product=WeatherProductType.observation):
        """Request forecast for given destination.
        Args:
          destination (str):
            Destination name.
          product (str):
            A parameter identifying the type of report to obtain. Default value `observation`.
        Returns:
          DestinationWeatherResponse instance or HEREError
        """

        data = {
            'app_id': self._app_id,
            'app_code': self._app_code,
            'product': product.__str__(),
            'name': destination
        }
        url = Utils.build_url(self._base_url, extra_params=data)
        response = requests.get(url, timeout=self._timeout)
        json_data = json.loads(response.content.decode('utf8'))
        if json_data.get(self._product_node(product)) != None:
            return DestinationWeatherResponse.new_from_jsondict(
                json_data, param_defaults={self._product_node(product): None})
        else:
            return HEREError(
                json_data.get(
                    'Message',
                    'Error occured on ' + sys._getframe(1).f_code.co_name))
Beispiel #5
0
 def __get(
     self,
     base_url,
     data,
     key,
     response_cls,
     manipulation_key: str = None,
     keys_for_manipulation: List = None,
 ):
     url = Utils.build_url(base_url, extra_params=data)
     if manipulation_key and keys_for_manipulation:
         for k in keys_for_manipulation:
             url = url.replace(k, manipulation_key)
     response = requests.get(url, timeout=self._timeout)
     json_data = json.loads(response.content.decode("utf8"))
     if response.status_code == requests.codes.OK:
         if json_data.get(key) is not None:
             return response_cls.new_from_jsondict(json_data)
         else:
             raise error_from_routing_service_error(json_data)
     else:
         raise HEREError("Error occurred on routing_api __get " +
                         sys._getframe(1).f_code.co_name +
                         " response status code " +
                         str(response.status_code))
Beispiel #6
0
 def __get_categories(self, data):
     url = Utils.build_url(self._base_url + 'categories/places', extra_params=data)
     response = requests.get(url, timeout=self._timeout)
     json_data = json.loads(response.content.decode('utf8'))
     if json_data.get('items') != None:
         return PlaceCategoriesResponse.new_from_jsondict(json_data)
     else:
         raise HEREError(json_data.get('message', 'Error occured on ' + sys._getframe(1).f_code.co_name))
Beispiel #7
0
 def __get(self, data):
     url = Utils.build_url(self._base_url, extra_params=data)
     response = requests.get(url, timeout=self._timeout)
     try:
         json_data = json.loads(response.content.decode("utf8"))
         if json_data.get("TracePoints") != None:
             return RmeResponse.new_from_jsondict(json_data)
         else:
             raise HEREError(
                 json_data.get(
                     "Details",
                     "Error occurred on function " +
                     sys._getframe(1).f_code.co_name,
                 ))
     except ValueError as err:
         raise HEREError("Error occurred on function " +
                         sys._getframe(1).f_code.co_name + " " + str(err))
 def __get(self, data, path, json_node):
     url = Utils.build_url(self._base_url + path, extra_params=data)
     response = requests.get(url, timeout=self._timeout)
     json_data = json.loads(response.content.decode("utf8"))
     if json_node in json_data.get("Res", {}):
         return PublicTransitResponse.new_from_jsondict(json_data)
     elif "text" in json_data.get("Res", {}).get("Message", {}):
         raise HEREError(
             json_data["Res"]["Message"]["text"],
             "Error occurred on " + sys._getframe(1).f_code.co_name,
         )
     elif "error" in json_data:
         if json_data["error"] == "Unauthorized":
             raise UnauthorizedError(json_data["error_description"])
     else:
         raise HEREError("Error occurred on " +
                         sys._getframe(1).f_code.co_name)
Beispiel #9
0
 def __is_correct_response(self, response):
     status_code = response.status_code
     json_data = response.json()
     if json_data.get("matrix") is not None:
         return json_data
     elif json_data.get("status") is not None:
         print("Matrix {} calculation {}".format(json_data["matrixId"],
                                                 json_data["status"]))
         return False
     elif json_data.get("error") is not None and json_data.get(
             "error_description"):
         raise HEREError("Error occurred on __is_correct_response: " +
                         json_data["error"] + ", description: " +
                         json_data["error_description"])
     elif json_data.get("title") is not None and json_data.get("status"):
         raise HEREError("Error occurred on __is_correct_response: " +
                         json_data["title"] + ", status: " +
                         json_data["status"])
Beispiel #10
0
 def _get_error_from_response(self, json_data):
     error_type = json_data.get("Type")
     error_message = json_data.get(
         "Message", "Error occured on " + sys._getframe(1).f_code.co_name)
     if error_type == "Unauthorized":
         return UnauthorizedError(error_message)
     elif error_type == "Invalid Request":
         return InvalidRequestError(error_message)
     else:
         return HEREError(error_message)
Beispiel #11
0
 def __get(self, data):
     url = Utils.build_url(self._base_url, extra_params=data)
     response = requests.get(url, timeout=self._timeout)
     json_data = json.loads(response.content.decode('utf8'))
     if json_data.get('response') != None:
         return RoutingResponse.new_from_jsondict(json_data)
     else:
         return HEREError(
             json_data.get(
                 'details',
                 'Error occured on ' + sys._getframe(1).f_code.co_name))
Beispiel #12
0
 def __get(self, data):
     url = Utils.build_url(self._base_url, extra_params=data)
     response = requests.get(url, timeout=self._timeout)
     json_data = json.loads(response.content.decode('utf8'))
     if json_data.get('suggestions') != None:
         return GeocoderAutoCompleteResponse.new_from_jsondict(json_data)
     else:
         raise HEREError(
             json_data.get(
                 'error_description',
                 'Error occured on ' + sys._getframe(1).f_code.co_name))
Beispiel #13
0
 def __get(self, data):
     url = Utils.build_url(self._base_url, extra_params=data)
     response = requests.get(url, timeout=self._timeout)
     try:
         json_data = json.loads(response.content.decode("utf8"))
         if json_data.get("items") != None:
             return GeocoderReverseResponse.new_from_jsondict(json_data)
         elif "error" in json_data:
             if json_data["error"] == "Unauthorized":
                 raise UnauthorizedError(json_data["error_description"])
         else:
             raise HEREError(
                 json_data.get(
                     "Details",
                     "Error occurred on function " +
                     sys._getframe(1).f_code.co_name,
                 ))
     except ValueError as err:
         raise HEREError("Error occurred on function " +
                         sys._getframe(1).f_code.co_name + " " + str(err))
Beispiel #14
0
 def __get(self, data, path, headers=None):
     url = Utils.build_url(self._base_url + path, extra_params=data)
     if headers != None:
         response = requests.get(url, timeout=self._timeout, headers=headers)
     else:
         response = requests.get(url, timeout=self._timeout)
     json_data = json.loads(response.content.decode('utf8'))
     if json_data.get('results') != None:
         return PlacesResponse.new_from_jsondict(json_data)
     else:
         raise HEREError(json_data.get('message', 'Error occured on ' + sys._getframe(1).f_code.co_name))
Beispiel #15
0
def error_from_fleet_telematics_service_error(json_data: dict):
    """Return the correct subclass for sequence errors"""

    if "error" in json_data:
        error_type = json_data["error"]
        message = json_data["error_description"]

        if error_type == "Unauthorized":
            return UnauthorizedError(message)
    # pylint: disable=W0212
    return HEREError("Error occured on " + sys._getframe(1).f_code.co_name)
Beispiel #16
0
 def __get_error_from_response(self, json_data):
     if "error" in json_data:
         if json_data["error"] == "Unauthorized":
             return UnauthorizedError(json_data["error_description"])
     error_type = json_data.get("Type")
     error_message = json_data.get(
         "Message", "Error occurred on " + sys._getframe(1).f_code.co_name)
     if error_type == "Invalid Request":
         return InvalidRequestError(error_message)
     else:
         return HEREError(error_message)
    def reverse_direction_isoline(
        self,
        transport_mode: IsolineRoutingTransportMode,
        ranges: List[int],
        origin: Optional[List[float]] = None,
        destination: Optional[List[float]] = None,
    ):
        """Calculates an isoline in the reverse direction. To trigger calculation in reverse direction,
        use the destination parameter instead of origin.
        Args:
          transport_mode (IsolineRoutingTransportMode):
            Transport mode of routing.
          ranges (List):
            Range values for isoline routing.
          origin (List):
            List including latitude and longitude in order.
          destination (List):
            List including latitude and longitude in order.
        Returns:
          IsolineRoutingResponse
        Raises:
          HEREError"""

        string_ranges = [str(int) for int in ranges]
        if origin:
            data = {
                "transportMode": transport_mode.__str__(),
                "origin": str.format("{0},{1}", origin[0], origin[1]),
                "range[type]": IsolineRoutingRangeType.time.__str__(),
                "range[values]": ",".join(string_ranges),
                "apiKey": self._api_key,
            }
            return self.__get(self._base_url, data, "departure")
        elif destination:
            data = {
                "transportMode":
                transport_mode.__str__(),
                "destination":
                str.format("{0},{1}", destination[0], destination[1]),
                "range[type]":
                IsolineRoutingRangeType.time.__str__(),
                "range[values]":
                range,
                "apiKey":
                self._api_key,
            }
            return self.__get(self._base_url, data, "arrival")
        else:
            raise HEREError(
                "Please provide values for origin or destination parameter.")
Beispiel #18
0
 def __get(self, data):
     url = Utils.build_url(self._base_url, extra_params=data)
     response = requests.get(url, timeout=self._timeout)
     json_data = json.loads(response.content.decode("utf8"))
     if json_data.get("items") != None:
         return PlacesResponse.new_from_jsondict(json_data)
     elif "error" in json_data:
         if json_data["error"] == "Unauthorized":
             raise UnauthorizedError(json_data["error_description"])
     else:
         raise HEREError(
             json_data.get(
                 "message",
                 "Error occurred on " + sys._getframe(1).f_code.co_name))
    def multi_range_routing(
        self,
        transport_mode: IsolineRoutingTransportMode,
        ranges: List[int],
        origin: Optional[List[float]] = None,
        destination: Optional[List[float]] = None,
    ):
        """Isoline routing can be requested with multiple ranges which allows for the calculation
        of many isolines with the same start or destination.
        Args:
          transport_mode (IsolineRoutingTransportMode):
            Transport mode of routing.
          ranges (List):
            Range values for isoline routing.
          origin (List):
            List including latitude and longitude in order.
          destination (List):
            List including latitude and longitude in order.
        Returns:
          IsolineRoutingResponse
        Raises:
          HEREError"""

        string_ranges = [str(int) for int in ranges]
        if origin:
            data = {
                "transportMode": transport_mode.__str__(),
                "origin": str.format("{0},{1}", origin[0], origin[1]),
                "range[type]": IsolineRoutingRangeType.distance.__str__(),
                "range[values]": ",".join(string_ranges),
                "apiKey": self._api_key,
            }
            return self.__get(self._base_url, data, "departure")
        elif destination:
            data = {
                "transportMode":
                transport_mode.__str__(),
                "destination":
                str.format("{0},{1}", destination[0], destination[1]),
                "range[type]":
                IsolineRoutingRangeType.distance.__str__(),
                "range[values]":
                ",".join(string_ranges),
                "apiKey":
                self._api_key,
            }
            return self.__get(self._base_url, data, "arrival")
        else:
            raise HEREError(
                "Please provide values for origin or destination parameter.")
Beispiel #20
0
 def encode_parameters(parameters):
     """Return a string in key=value&key=value form.
     Values of None are not included in the output string.
     Args:
       parameters (dict):
         dictionary of query parameters to be converted.
     Returns:
       A URL-encoded string in "key=value&key=value" form
     """
     if parameters is None:
         return None
     if not isinstance(parameters, dict):
         raise HEREError("`parameters` must be a dict.")
     else:
         return urlencode(dict((k, v) for k, v in parameters.items() if v is not None))
Beispiel #21
0
    def _route(self,
               waypoint_a,
               waypoint_b,
               modes=None,
               departure=None,
               arrival=None):
        if isinstance(waypoint_a, str):
            waypoint_a = self._get_coordinates_for_location_name(waypoint_a)
        if isinstance(waypoint_b, str):
            waypoint_b = self._get_coordinates_for_location_name(waypoint_b)
        data = {
            "waypoint0": self.__list_to_waypoint(waypoint_a),
            "waypoint1": self.__list_to_waypoint(waypoint_b),
            "mode": self.__prepare_mode_values(modes),
            "apikey": self._api_key,
        }
        if departure is not None and arrival is not None:
            raise HEREError("Specify either departure or arrival, not both.")
        if departure is not None:
            departure = self._convert_datetime_to_isoformat(departure)
            data["departure"] = departure
        if arrival is not None:
            arrival = self._convert_datetime_to_isoformat(arrival)
            data["arrival"] = arrival
        response = self.__get(self.URL_CALCULATE_ROUTE, data, "response",
                              RoutingResponse)
        route = response.response["route"]
        maneuver = route[0]["leg"][0]["maneuver"]

        if any(mode in modes for mode in [RouteMode.car, RouteMode.truck]):
            # Get Route for Car and Truck
            response.route_short = self._get_route_from_vehicle_maneuver(
                maneuver)
        elif any(
                mode in modes for mode in
            [RouteMode.publicTransport, RouteMode.publicTransportTimeTable]):
            # Get Route for Public Transport
            public_transport_line = route[0]["publicTransportLine"]
            response.route_short = self._get_route_from_public_transport_line(
                public_transport_line)
        elif any(mode in modes
                 for mode in [RouteMode.pedestrian, RouteMode.bicycle]):
            # Get Route for Pedestrian and Biyclce
            response.route_short = self._get_route_from_non_vehicle_maneuver(
                maneuver)
        return response
Beispiel #22
0
def error_from_routing_service_error(json_data):
    """Return the correct subclass for routing errors"""
    if 'subtype' in json_data:
        subtype = json_data['subtype']
        details = json_data['details']

        if subtype == 'InvalidCredentials':
            return InvalidCredentialsError(details)
        if subtype == 'InvalidInputData':
            return InvalidInputDataError(details)
        if subtype == 'WaypointNotFound':
            return WaypointNotFoundError(details)
        if subtype == 'NoRouteFound':
            return NoRouteFoundError(details)
        if subtype == 'LinkIdNotFound':
            return LinkIdNotFoundError(details)
        if subtype == 'RouteNotReconstructed':
            return RouteNotReconstructedError(details)
    # pylint: disable=W0212
    return HEREError('Error occured on ' + sys._getframe(1).f_code.co_name)
Beispiel #23
0
def error_from_routing_service_error(json_data):
    """Return the correct subclass for routing errors"""

    if "error" in json_data:
        if json_data["error"] == "Unauthorized":
            return InvalidCredentialsError(json_data["error_description"])

    if "subtype" in json_data:
        subtype = json_data["subtype"]
        details = json_data["details"]

        if subtype == "InvalidInputData":
            return InvalidInputDataError(details)
        if subtype == "WaypointNotFound":
            return WaypointNotFoundError(details)
        if subtype == "NoRouteFound":
            return NoRouteFoundError(details)
        if subtype == "LinkIdNotFound":
            return LinkIdNotFoundError(details)
        if subtype == "RouteNotReconstructed":
            return RouteNotReconstructedError(details)
    # pylint: disable=W0212
    return HEREError("Error occurred on " + sys._getframe(1).f_code.co_name)
Beispiel #24
0
    def forecast_astronomy(self, destination):
        """Request forecast for given destination.
        Args:
          destination (str):
            Destination name.
        Returns:
          DestinationWeatherResponse instance or HEREError
        """

        data = {
            'app_id': self._app_id,
            'app_code': self._app_code,
            'product': destination
        }
        url = Utils.build_url(self._base_url, extra_params=data)
        response = requests.get(url, timeout=self._timeout)
        json_data = json.loads(response.content.decode('utf8'))
        if json_data.get('astronomy') != None:
            return DestinationWeatherResponse.new_from_jsondict(json_data)
        else:
            return HEREError(
                json_data.get(
                    'Message',
                    'Error occured on ' + sys._getframe(1).f_code.co_name))
Beispiel #25
0
    def sync_matrix(
        self,
        origins: Union[List[float], str],
        destinations: Union[List[float], str],
        matrix_type: MatrixRoutingType = MatrixRoutingType.world,
        center: Optional[List[float]] = None,
        radius: Optional[int] = None,
        profile: Optional[MatrixRoutingProfile] = None,
        departure: str = None,
        routing_mode: Optional[MatrixRoutingMode] = None,
        transport_mode: Optional[MatrixRoutingTransportMode] = None,
        avoid: Optional[Avoid] = None,
        truck: Optional[Truck] = None,
        matrix_attributes: Optional[List[MatrixSummaryAttribute]] = None,
    ) -> Optional[RoutingMatrixResponse]:
        """Sync request a matrix of route summaries between M starts and N destinations.
        Args:
          origins (List):
            List of lists of coordinates [lat,long] of start waypoints.
            or list of string with the location names.
          destinations (List):
            List of lists of coordinates [lat,long] of destination waypoints.
            or list of string with the location names.
          matrix_type (MatrixRoutingType):
            Routing type used in definition of a region in which the matrix will be calculated.
          center (Optional[List]):
            Center of region definition, latitude and longitude.
          radius (Optional[int]):
            Center  of region definition.
          profile (Optional[MatrixRoutingProfile]):
            A profile ID enables the calculation of matrices with routes of arbitrary length.
          departure (str):
            time when travel is expected to start, e.g.: '2013-07-04T17:00:00+02'
          routing_mode (Optional[MatrixRoutingMode]):
            Route mode used in optimization of route calculation.
          transport_mode (Optional[MatrixRoutingTransportMode]):
            Depending on the transport mode special constraints, speed attributes and weights
            are taken into account during route calculation.
          avoid (Optional[Avoid]):
            Avoid routes that violate these properties.
          truck (Optional[Truck]):
            Different truck options to use during route calculation when transportMode = truck.
          matrix_attributes (List):
            List of MatrixSummaryAttribute enums.
        Returns:
          RoutingMatrixResponse
        Raises:
          HEREError: If an error is received from the server.
        """

        query_params = {
            "apiKey": self._api_key,
            "async": "false",
        }

        request_body = self.__prepare_matrix_request_body(
            origins=origins,
            destinations=destinations,
            matrix_type=matrix_type,
            center=center,
            radius=radius,
            profile=profile,
            departure=departure,
            routing_mode=routing_mode,
            transport_mode=transport_mode,
            avoid=avoid,
            truck=truck,
            matrix_attributes=matrix_attributes,
        )

        url = Utils.build_url(self.URL_CALCULATE_MATRIX,
                              extra_params=query_params)
        headers = {"Content-Type": "application/json"}
        response = requests.post(url,
                                 json=request_body,
                                 headers=headers,
                                 timeout=self._timeout)
        json_data = json.loads(response.content.decode("utf8"))
        if response.status_code == requests.codes.OK:
            if json_data.get("matrix") is not None:
                return RoutingMatrixResponse.new_from_jsondict(json_data)
            else:
                raise HEREError("Error occurred on routing_api sync_matrix " +
                                sys._getframe(1).f_code.co_name +
                                " response status code " +
                                str(response.status_code))
        else:
            if "title" in json_data and "cause" in json_data:
                raise HEREError(
                    str.format(
                        "routing_api sync_matrix failed! title: {0}, cause: {1}",
                        json_data["title"],
                        json_data["cause"],
                    ))
            else:
                raise HEREError("Error occurred on routing_api sync_matrix " +
                                sys._getframe(1).f_code.co_name)
Beispiel #26
0
    def async_matrix(
        self,
        token: str,
        origins: Union[List[float], str],
        destinations: Union[List[float], str],
        matrix_type: MatrixRoutingType = MatrixRoutingType.world,
        center: Optional[List[float]] = None,
        radius: Optional[int] = None,
        profile: Optional[MatrixRoutingProfile] = None,
        departure: str = None,
        routing_mode: Optional[MatrixRoutingMode] = None,
        transport_mode: Optional[MatrixRoutingTransportMode] = None,
        avoid: Optional[Avoid] = None,
        truck: Optional[Truck] = None,
        matrix_attributes: Optional[List[MatrixSummaryAttribute]] = None,
    ) -> Optional[RoutingMatrixResponse]:
        """Async request a matrix of route summaries between M starts and N destinations.
        Args:
          token (str):
            Bearer token required for async calls. This is the only working solution for now.
            How to create a bearer token:
            https://developer.here.com/documentation/identity-access-management/dev_guide/topics/sdk.html#step-1-register-your-application
            https://developer.here.com/documentation/identity-access-management/dev_guide/topics/postman.html
          origins (List):
            List of lists of coordinates [lat,long] of start waypoints.
            or list of string with the location names.
          destinations (List):
            List of lists of coordinates [lat,long] of destination waypoints.
            or list of string with the location names.
          matrix_type (MatrixRoutingType):
            Routing type used in definition of a region in which the matrix will be calculated.
          center (Optional[List]):
            Center of region definition, latitude and longitude.
          radius (Optional[int]):
            Center  of region definition.
          profile (Optional[MatrixRoutingProfile]):
            A profile ID enables the calculation of matrices with routes of arbitrary length.
          departure (str):
            time when travel is expected to start, e.g.: '2013-07-04T17:00:00+02'
          routing_mode (Optional[MatrixRoutingMode]):
            Route mode used in optimization of route calculation.
          transport_mode (Optional[MatrixRoutingTransportMode]):
            Depending on the transport mode special constraints, speed attributes and weights
            are taken into account during route calculation.
          avoid (Optional[Avoid]):
            Avoid routes that violate these properties.
          truck (Optional[Truck]):
            Different truck options to use during route calculation when transportMode = truck.
          matrix_attributes (List):
            List of MatrixSummaryAttribute enums.
        Returns:
          RoutingMatrixResponse.
        Raises:
          HEREError: If an error is received from the server.
        """

        query_params = {}

        request_body = self.__prepare_matrix_request_body(
            origins=origins,
            destinations=destinations,
            matrix_type=matrix_type,
            center=center,
            radius=radius,
            profile=profile,
            departure=departure,
            routing_mode=routing_mode,
            transport_mode=transport_mode,
            avoid=avoid,
            truck=truck,
            matrix_attributes=matrix_attributes,
        )

        url = Utils.build_url(self.URL_CALCULATE_MATRIX,
                              extra_params=query_params)
        headers = {
            "Content-Type": "application/json",
            "Authorization": str.format("Bearer {0}", token),
        }
        json_data = json.dumps(request_body)
        response = requests.post(url,
                                 json=request_body,
                                 headers=headers,
                                 timeout=self._timeout)
        if response.status_code == requests.codes.ACCEPTED:
            json_data = response.json()
            print("Matrix {} calculation {}".format(json_data["matrixId"],
                                                    json_data["status"]))
            poll_url = json_data["statusUrl"]
            headers = {"Authorization": str.format("Bearer {0}", token)}
            print("Polling matrix calculation started!")
            result = polling.poll(
                lambda: requests.get(poll_url, headers=headers),
                check_success=self.__is_correct_response,
                step=5,
                poll_forever=True,
            )
            print("Polling matrix calculation completed!")
            poll_data = result.json()
            return RoutingMatrixResponse.new_from_jsondict(poll_data)
        else:
            json_data = response.json()
            if (json_data.get("error") is not None
                    and json_data.get("error_description") is not None):
                raise HEREError("Error occurred on async_matrix: " +
                                json_data["error"] + ", description: " +
                                json_data["error_description"])
            elif (json_data.get("title") is not None
                  and json_data.get("cause") is not None):
                raise HEREError("Error occurred on async_matrix: " +
                                json_data["title"] + ", cause: " +
                                json_data["cause"])
            else:
                raise HEREError("Error occurred on async_matrix " +
                                sys._getframe(1).f_code.co_name)
    def isoline_routing_at_specific_time(
        self,
        transport_mode: IsolineRoutingTransportMode,
        ranges: List[int],
        origin: Optional[List[float]] = None,
        departure_time: Optional[str] = None,
        destination: Optional[List[float]] = None,
        arrival_time: Optional[str] = None,
    ):
        """To calculate an isoline around an origin with a specific time, use departureTime.
        For a reverse isoline, that is, when using destination, you can use arrivalTime.
        If departureTime or arrivalTime are specified as "any", the isoline calculation will
        not take traffic flow and other time-dependent effects into account. This can be useful
        when it is not certain for what time of the day the isoline needs to be computed.
        Args:
          transport_mode (IsolineRoutingTransportMode):
            Transport mode of routing.
          ranges (List):
            List of range values for isoline (in meters).
          origin (List):
            List including latitude and longitude in order.
          departure_time (str):
            Departure time of the routing in format yyyy-MM-ddThh:mm:ss.
          destination (List):
            List including latitude and longitude in order.
          arrival_time (str):
            Arrival time of the planned routing in format yyyy-MM-ddThh:mm:ss.
        Returns:
          IsolineRoutingResponse
        Raises:
          HEREError"""

        string_ranges = [str(int) for int in ranges]
        if origin and departure_time:
            data = {
                "transportMode": transport_mode.__str__(),
                "origin": str.format("{0},{1}", origin[0], origin[1]),
                "departureTime": departure_time,
                "range[type]": IsolineRoutingRangeType.time.__str__(),
                "range[values]": ",".join(string_ranges),
                "apiKey": self._api_key,
            }
            return self.__get(self._base_url, data, "departure")
        elif destination and arrival_time:
            data = {
                "transportMode":
                transport_mode.__str__(),
                "destination":
                str.format("{0},{1}", destination[0], destination[1]),
                "arrivalTime":
                arrival_time,
                "range[type]":
                IsolineRoutingRangeType.time.__str__(),
                "range[values]":
                ",".join(string_ranges),
                "apiKey":
                self._api_key,
            }
            return self.__get(self._base_url, data, "arrival")
        else:
            raise HEREError(
                "Please provide either origin & departure_time or destination & arrival_time."
            )
 def __get_client_error_from_response(self, json_data):
     if "title" in json_data and "cause" in json_data:
         return HEREError("Error on client: " + json_data["title"] +
                          " cause: " + json_data["cause"])
     else:
         return HEREError("herepy got a 400 from isoline router API")
    def calculate_route(
        self,
        departure: List[float],
        arrival: List[float],
        time: str,
        max_connections: int = 3,
        changes: int = -1,
        lang: str = "en",
        include_modes: List[PublicTransitModeType] = None,
        exclude_modes: List[PublicTransitModeType] = None,
        units: str = "metric",
        max_walking_distance: int = 2000,
        walking_speed: int = 100,
        show_arrival_times: bool = True,
        graph: bool = False,
        routing_mode: PublicTransitRoutingMode = PublicTransitRoutingMode.
        schedule,
    ) -> Optional[PublicTransitResponse]:
        """Request a public transit route between any two places.
        Args:
          departure (List):
            List contains latitude and longitude in order.
          arrival (List):
            List contains latitude and longitude in order.
          time (str):
            time formatted in yyyy-mm-ddThh:mm:ss.
          max_connections (int):
            Specifies the number of following departure/arrivals the response should include.
            The possible values are: 1-6.
          changes (int):
            Specifies the maximum number of changes or transfers allowed in a route.
            0-6 or -1.
            The default is -1 (which disables the filter, or unlimited no of changes permitted).
          lang (str):
            Specifies the language of the response.
          include_modes (List[PublicTransitModeType]):
            Specifies the transit type filter used to determine which types of transit to include in the response.
          exclude_modes (List[PublicTransitModeType]):
            Specifies the transit type filter used to determine which types of transit to exclude in the response.
          units (str):
            Units of measurement used. metric oder imperial.
          max_walking_distance (int):
            Specifies a maximum walking distance in meters. Allowed values are 0-6000.
          walking_speed (int):
            Specifies the walking speed in percent of normal walking speed. Allowed values are 50-200.
          show_arrival_times (boolean):
            flag to indicate if response should show arrival times or departure times.
          graph (boolean):
            flag to indicate if response should contain coordinate pairs to allow the drawing of a polyline for the route.
          routing_type (PublicTransitRoutingType):
            type of routing. Default is time_tabled.
        Returns:
          PublicTransitResponse
        Raises:
          HEREError
        """

        data = {
            "dep": str.format("{0},{1}", departure[0], departure[1]),
            "arr": str.format("{0},{1}", arrival[0], arrival[1]),
            "max": max_connections,
            "time": time,
            "changes": changes,
            "lang": lang,
            "units": units,
            "walk": ",".join([str(max_walking_distance),
                              str(walking_speed)]),
            "arrival": 1 if show_arrival_times == True else 0,
            "apikey": self._api_key,
            "graph": 1 if graph == True else 0,
            "routingMode": routing_mode.__str__(),
        }

        modes = None
        if include_modes is not None and exclude_modes is not None:
            raise HEREError(
                "Specify either include_modes or exclude_modes, not both.")
        if include_modes is not None:
            modes = ",".join(mode.__str__() for mode in include_modes)
        if exclude_modes is not None:
            modes = ",".join("-" + mode.__str__() for mode in exclude_modes)
        if modes is not None:
            data["modes"] = modes

        response = self.__get(data, "route.json", "Connections")
        response_with_short_route = self._get_response_with_short_route(
            response)
        return response_with_short_route