コード例 #1
0
        public override Task <RoutingResponse> EnqueueControlMessage(ControlMessage request, ServerCallContext context)
        {
            RoutingResponse response;

            using (this.m_duration.NewTimer()) {
                this.m_logger.LogDebug("Received egress routing request for sensor {sensorId}.", request.SensorID);

                try {
                    var dto = ControlMessageProtobufConverter.Convert(request);

                    this.m_requests.Inc();
                    this.m_queue.Add(dto);

                    response = new RoutingResponse {
                        Count      = 1,
                        Message    = "Messages queued.",
                        ResponseID = ByteString.CopyFrom(Guid.NewGuid().ToByteArray())
                    };
                } catch (FormatException ex) {
                    this.m_logger.LogWarning("Received messages from an invalid sensor. Exception: {exception}", ex);

                    response = new RoutingResponse {
                        Count      = 0,
                        Message    = "Messages not queued. Invalid sensor ID.",
                        ResponseID = ByteString.CopyFrom(Guid.NewGuid().ToByteArray())
                    };
                }
            }

            return(Task.FromResult(response));
        }
コード例 #2
0
ファイル: OSMRoute.cs プロジェクト: jabr212/Catchem-PoGo
        public static RoutingResponse GetRoute(GeoCoordinate start, GeoCoordinate dest, ISession session)
        {
            try
            {
                Logger.Write("Requesting routing info to http://openls.geog.uni-heidelberg.de", LogLevel.Debug);

                //var responseFromServer = PostXmlData("http://openls.geog.uni-heidelberg.de/route", PrepareRequest(start, dest), session.Proxy);
                var responseFromServer = PostXmlData("http://openls.geog.uni-heidelberg.de/testing2015/routing", PrepareRequest(start, dest), session.Proxy);
                Logger.Write(
                    responseFromServer != null
                        ? "Got response from http://openls.geog.uni-heidelberg.de"
                        : "Wrong response from http://openls.geog.uni-heidelberg.de, we doomed", LogLevel.Debug);

                var responseParsed = HandleResponse(responseFromServer);

                return(responseParsed);
            }
            catch (Exception ex)
            {
                Logger.Write("Routing error: " + ex.Message, LogLevel.Debug);
            }
            RoutingResponse emptyResponse = new RoutingResponse();

            return(emptyResponse);
        }
コード例 #3
0
ファイル: OSMRoute.cs プロジェクト: jabr212/Catchem-PoGo
        private static RoutingResponse HandleResponse(string responseFromServer)
        {
            var resp   = new RoutingResponse();
            var xmldoc = new XmlDocument();

            xmldoc.LoadXml(responseFromServer);
            var xmlnsManager = new XmlNamespaceManager(xmldoc.NameTable);

            xmlnsManager.AddNamespace("xls", "http://www.opengis.net/xls");
            xmlnsManager.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
            xmlnsManager.AddNamespace("gml", "http://www.opengis.net/gml");

            try
            {
                var coordNodes = xmldoc.SelectNodes("/xls:XLS/xls:Response/xls:DetermineRouteResponse/xls:RouteGeometry/gml:LineString/gml:pos", xmlnsManager);
                var points     = new List <List <double> >();
                if (coordNodes != null && coordNodes.Count > 0)
                {
                    var rnd = new Random();
                    points.AddRange(from XmlNode node in coordNodes select node.InnerText into coordinate where coordinate != string.Empty select coordinate.Split(' ') into xy where xy.Length == 3 let lat = double.Parse(xy[1], CultureInfo.InvariantCulture) let lng = double.Parse(xy[0], CultureInfo.InvariantCulture) let alt = double.Parse(xy[2], CultureInfo.InvariantCulture) + 0.7 + rnd.NextInRange(0.1, 0.3) select new List <double> {
                        lng, lat, alt
                    });
                    resp.Coordinates = points;
                }
            }
            catch
            {
                //ignore
            }

            return(resp);
        }
コード例 #4
0
        public override Task <RoutingResponse> EnqueueBulkMessages(TextMessageData request, ServerCallContext context)
        {
            RoutingResponse response;

            using (this.m_duration.NewTimer()) {
                this.m_logger.LogDebug("Bulk ingress request with {count} messages.", request.Messages.Count);

                try {
                    var dto = new List <Message>();

                    foreach (var raw in request.Messages)
                    {
                        var message = MessageProtobufConverter.Convert(raw);

                        if (MessageValidator.Validate(message))
                        {
                            dto.Add(message);
                        }
                    }

                    this.m_queue.AddRange(dto);
                    this.m_messageRequests.Inc();

                    response = new RoutingResponse {
                        Count      = dto.Count,
                        Message    = "Messages queued.",
                        ResponseID = ByteString.CopyFrom(Guid.NewGuid().ToByteArray())
                    };
                } catch (FormatException ex) {
                    this.m_logger.LogWarning("Received messages from an invalid sensor. Exception: {exception}", ex);

                    response = new RoutingResponse {
                        Count      = 0,
                        Message    = "Messages not queued. Invalid sensor ID.",
                        ResponseID = ByteString.CopyFrom(Guid.NewGuid().ToByteArray())
                    };
                }
            }

            return(Task.FromResult(response));
        }
コード例 #5
0
        public override Task <RoutingResponse> EnqueueMeasurement(Platform.Router.Contracts.DTO.Measurement request, ServerCallContext context)
        {
            RoutingResponse response;

            using (this.m_duration.NewTimer()) {
                this.m_logger.LogDebug("Received measurement routing request from sensor {sensorId}.",
                                       request.SensorID);

                try {
                    var count = 0;
                    var dto   = MeasurementProtobufConverter.Convert(request);

                    if (MeasurementValidator.Validate(dto))
                    {
                        this.m_queue.Add(dto);
                        this.m_measurementRequests.Inc();

                        count += 1;
                    }

                    response = new RoutingResponse {
                        Count      = count,
                        Message    = "Measurements queued.",
                        ResponseID = ByteString.CopyFrom(Guid.NewGuid().ToByteArray())
                    };
                } catch (FormatException) {
                    this.m_logger.LogWarning("Received messages from an invalid sensor (ID): {sensorID}",
                                             request.SensorID);

                    response = new RoutingResponse {
                        Count      = 0,
                        Message    = "Measurements not queued. Invalid sensor ID.",
                        ResponseID = ByteString.CopyFrom(Guid.NewGuid().ToByteArray())
                    };
                }
            }

            return(Task.FromResult(response));
        }
コード例 #6
0
        private async void BuildTheRoute_Click(object sender, RoutedEventArgs e)
        {
            if (_mapPoints.Count < 2)
            {
                return;
            }
            CheckRouteServicePreffer();
            if (_mapPoints.Count > 47 && !_manualRoute)
            {
                MessageBox.Show(
                    "Too many waypoints, try to reduce them to 47, or wait for next releases, where that limit will be increased!",
                    "Routing Error", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }
            BuildingProgressBar.Value = 0;
            BotWindowData bot;
            var           route = GetWorkingRouting(out bot);

            if (route == "error" && !_manualRoute)
            {
                MessageBox.Show(
                    "You have to enter Google Direction API or Mapzen Valhalla API to any of your bots, before creating a route",
                    "API Key Error", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }

            var start = _mapPoints.FirstOrDefault(x => x.IsStart) ?? _mapPoints.First();

            BuildingProgressBar.Value = 10;

            RoutingResponse response = null;
            var             cycleWp  = _mapPoints.Where(x => !x.IsStart).Select(x => x.Location).ToList();

            cycleWp.Add(start.Location);
            List <GeoCoordinate> routePoints;

            if (!_manualRoute)
            {
                if (route == "google")
                {
                    response = GoogleRouting.GetRoute(start.Location, null, bot.Session, cycleWp, true);
                }
                else if (route == "mapzen")
                {
                    response = MapzenRouting.GetRoute(start.Location, null, bot.Session, cycleWp, true);
                }
                if (response?.Coordinates == null || response.Coordinates.Count == 0)
                {
                    return;
                }
                routePoints = response.Coordinates.Select(wp => new GeoCoordinate(wp[0], wp[1])).ToList();
            }
            else
            {
                cycleWp.Insert(0, start.Location);
                routePoints = new List <GeoCoordinate>(cycleWp);
            }
            BuildingProgressBar.Value = 60;
            _currentRoute?.Points?.Clear();
            if (_currentRoute == null)
            {
                _currentRoute = new GMapRoute(new List <PointLatLng>());
                RouteCreatorMap.Markers.Add(_currentRoute);
            }
            BuildingProgressBar.Value = 70;
            _buildedRoute             = new List <GeoCoordinate>(routePoints);

            foreach (var item in routePoints)
            {
                _currentRoute.Points?.Add(new PointLatLng(item.Latitude, item.Longitude));
            }

            _currentRoute?.RegenerateShape(RouteCreatorMap);
            var path = _currentRoute?.Shape as Path;

            if (path != null)
            {
                path.Stroke = new SolidColorBrush(Color.FromRgb(255, 0, 0));
            }


            bot = MainWindow.BotsCollection.FirstOrDefault(
                x => !string.IsNullOrEmpty(x.GlobalSettings.LocationSettings.MapzenApiElevationKey));
            if (bot != null)
            {
                await bot.Session.MapzenApi.FillAltitude(_buildedRoute.ToList());
            }
            BuildingProgressBar.Value = 100;
            _builded = true;
        }
コード例 #7
0
        private async Task BuildTheRouteTask(CancellationToken token)
        {
            try
            {
                token.ThrowIfCancellationRequested();
                if (_mapPoints.Count < 2)
                {
                    return;
                }
                await Dispatcher.BeginInvoke(new ThreadStart(CheckRouteServicePrefer));

                if (_mapPoints.Count > 47 && !_manualRoute)
                {
                    Dispatcher.Invoke(new ThreadStart(delegate
                    {
                        MessageBox.Show(
                            TranslationEngine.GetDynamicTranslationString("%TOO_MANY_ROUTE_POINTS%",
                                                                          "Too many waypoints, try to reduce them to 47, or wait for next releases, where that limit will be increased!"),
                            "Routing Error", MessageBoxButton.OK, MessageBoxImage.Information);
                    }));
                    return;
                }
                UpdateProgress(TranslationEngine.GetDynamicTranslationString("%ROUTE_PROGRESS_2%", "Started!..."), 0);
                BotWindowData bot;
                var           route = GetWorkingRouting(out bot);
                if (route == "error" && !_manualRoute)
                {
                    MessageBox.Show(
                        TranslationEngine.GetDynamicTranslationString("%NO_ROUTE_API_FOUND%",
                                                                      "You have to enter Google Direction API or Mapzen Valhalla API to any of your bots, before creating a route"),
                        "API Key Error", MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }

                var start = _mapPoints.FirstOrDefault(x => x.IsStart) ?? _mapPoints.First();
                UpdateProgress(TranslationEngine.GetDynamicTranslationString("%ROUTE_PROGRESS_3%", "Started!..."), 10);
                RoutingResponse response = null;
                var             cycleWp  = _mapPoints.Where(x => !x.IsStart).Select(x => x.Location).ToList();
                cycleWp.Add(start.Location);
                List <GeoCoordinate> routePoints;
                token.ThrowIfCancellationRequested();
                if (!_manualRoute)
                {
                    if (route == "google")
                    {
                        response = GoogleRouting.GetRoute(start.Location, null, bot.Session, cycleWp, true);
                    }
                    else if (route == "mapzen")
                    {
                        response = MapzenRouting.GetRoute(start.Location, null, bot.Session, cycleWp, true);
                    }
                    if (response?.Coordinates == null || response.Coordinates.Count == 0)
                    {
                        return;
                    }
                    routePoints = response.Coordinates.Select(wp => new GeoCoordinate(wp[0], wp[1])).ToList();
                }
                else
                {
                    cycleWp.Insert(0, start.Location);
                    routePoints = new List <GeoCoordinate>(cycleWp);
                }
                token.ThrowIfCancellationRequested();
                UpdateProgress(
                    TranslationEngine.GetDynamicTranslationString("%ROUTE_PROGRESS_4%", "Handling result..."), 60);
                _currentRoute?.Points?.Clear();
                if (_currentRoute == null)
                {
                    _currentRoute = new GMapRoute(new List <PointLatLng>());
                }

                await RouteCreatorMap.Dispatcher.BeginInvoke(new ThreadStart(delegate
                {
                    RouteCreatorMap.Markers.Add(_currentRoute);
                }));

                token.ThrowIfCancellationRequested();
                UpdateProgress(
                    TranslationEngine.GetDynamicTranslationString("%ROUTE_PROGRESS_5%", "Requesting altitude..."), 70);
                _buildedRoute = new List <GeoCoordinate>(routePoints);
                token.ThrowIfCancellationRequested();
                foreach (var item in routePoints)
                {
                    _currentRoute.Points?.Add(new PointLatLng(item.Latitude, item.Longitude));
                }
                await Dispatcher.BeginInvoke(new ThreadStart(delegate
                {
                    try
                    {
                        _currentRoute.RegenerateShape(RouteCreatorMap);
                    }
                    catch (Exception)
                    {
                        //ignore
                    }
                }));

                var path = _currentRoute?.Shape as Path;
                await Dispatcher.BeginInvoke(new ThreadStart(delegate
                {
                    if (path != null)
                    {
                        path.Stroke = new SolidColorBrush(Color.FromRgb(255, 0, 0));
                    }
                }));


                bot = MainWindow.BotsCollection.FirstOrDefault(
                    x => !string.IsNullOrEmpty(x.GlobalSettings.LocationSettings.MapzenApiKey));
                if (bot != null)
                {
                    await bot.Session.MapzenApi.FillAltitude(_buildedRoute.ToList(), token : token);
                }
                UpdateProgress(TranslationEngine.GetDynamicTranslationString("%ROUTE_PROGRESS_6%", "Done!"), 100);
                _builded = true;
            }
            catch (OperationCanceledException)
            {
                //ignore
            }
        }
コード例 #8
0
ファイル: ResponseWrapper.cs プロジェクト: dkearney1/Default
 public ResponseWrapper(RoutingRequest request, RoutingResponse rawResponse)
 {
     // TODO: Complete member initialization
     this.request = request;
     this.rawResponse = rawResponse;
 }
コード例 #9
0
ファイル: MapzenRouting.cs プロジェクト: leeleonis/Cpko
        public static RoutingResponse GetRoute(GeoCoordinate start, GeoCoordinate dest, ISession session, List <GeoCoordinate> waypoints, bool silent = false)
        {
            string apiKey = session.LogicSettings.MapzenValhallaApiKey;

            if (string.IsNullOrEmpty(apiKey))
            {
                if (!silent)
                {
                    session.EventDispatcher.Send(new WarnEvent
                    {
                        Message = "Mapzen Valhalla API Key is Empty!"
                    });
                }
                return(new RoutingResponse());
            }

            if (waypoints == null || waypoints.Count == 0)
            {
                waypoints = new List <GeoCoordinate> {
                    dest
                };
            }
            waypoints.Insert(0, start);

            string waypointsRequest = "";

            if (waypoints.Count > 0)
            {
                waypointsRequest = "\"locations\":[";
                var wpList = new List <string>();
                foreach (var wp in waypoints)
                {
                    wpList.Add($"{{\"lat\":{wp.Latitude.ToString(CultureInfo.InvariantCulture)},\"lon\":{wp.Longitude.ToString(CultureInfo.InvariantCulture)},\"type\":\"break\"}}");
                }
                waypointsRequest += wpList.Aggregate((x, v) => x + "," + v);
                waypointsRequest += "],";
            }
            try
            {
                Logger.Write("Requesting routing info to Mapzen Valhalla Routing API", LogLevel.Debug);

                var request = WebRequest.Create(
                    "https://valhalla.mapzen.com/route?json={" + waypointsRequest +
                    "\"costing\":\"pedestrian\",\"costing_options\":{\"pedestrian\":{\"alley_factor\":1.0, \"driveway_factor\":1.0, \"step_penalty\":1.0}}}" +
                    $"&api_key={apiKey}");
                request.Credentials       = CredentialCache.DefaultCredentials;
                request.Proxy             = WebRequest.DefaultWebProxy;
                request.Proxy.Credentials = CredentialCache.DefaultCredentials;

                var responseFromServer = "";
                request.Timeout = 20000;
                using (var response = request.GetResponse())
                {
                    Logger.Write("Got response from MapzenValhalla", LogLevel.Debug);
                    //Console.WriteLine(((HttpWebResponse)response).StatusDescription);
                    using (var dataStream = response.GetResponseStream())
                        using (var reader = new StreamReader(dataStream))
                        {
                            responseFromServer = reader.ReadToEnd();
                        }
                }

                var valhallaResponse = JsonConvert.DeserializeObject <ValhallaResponse>(responseFromServer);

                var responseParsed = new RoutingResponse();
                var route          = valhallaResponse.trip;
                if (route != null)
                {
                    responseParsed.Coordinates = route.GetRoute();
                }
                return(responseParsed);
            }
            catch (Exception ex)
            {
                Logger.Write("Routing error: " + ex.Message, LogLevel.Debug);
            }
            RoutingResponse emptyResponse = new RoutingResponse();

            return(emptyResponse);
        }