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); }
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); }
public static RoutingResponse GetRoute(GeoCoordinate start, GeoCoordinate dest, ISession session) { string apiKey = session.LogicSettings.MobBotRoutingApiKey; if (string.IsNullOrEmpty(apiKey)) { session.EventDispatcher.Send(new WarnEvent { Message = "MobBotRouting API Key is Empty!" }); return(new RoutingResponse()); } try { Logger.Write("Requesting routing info from MobRouting.com", LogLevel.Debug); var request = WebRequest.Create( $"http://mobrouting.com" + $"/api/dev/gosmore.php?format=geojson&apikey={apiKey}&flat={start.Latitude.ToString(CultureInfo.InvariantCulture)}&flon={start.Longitude.ToString(CultureInfo.InvariantCulture)}&tlat={dest.Latitude.ToString(CultureInfo.InvariantCulture)}&tlon={dest.Longitude.ToString(CultureInfo.InvariantCulture)}&v=foot&fast=1&layer=mapnik"); 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 www.mobrouting.com", LogLevel.Debug); //Console.WriteLine(((HttpWebResponse)response).StatusDescription); using (var dataStream = response.GetResponseStream()) using (var reader = new StreamReader(dataStream)) { responseFromServer = reader.ReadToEnd(); } } //Console.WriteLine(responseFromServer); var responseParsed = JsonConvert.DeserializeObject <RoutingResponse>(responseFromServer); return(responseParsed); } catch (Exception ex) { Logger.Write("Routing error: " + ex.Message, LogLevel.Debug); } var emptyResponse = new RoutingResponse { Coordinates = new List <List <double> >() }; return(emptyResponse); }
public static RoutingResponse GetRoute(GeoCoordinate start, GeoCoordinate dest) { try { Logger.Write("Requesting routing info from MobRouting.com", LogLevel.Debug); WebRequest request = WebRequest.Create( $"http://mobrouting.com" + $"/api/dev/gosmore.php?format=geojson&flat={start.Latitude.ToString(CultureInfo.InvariantCulture)}&flon={start.Longitude.ToString(CultureInfo.InvariantCulture)}&tlat={dest.Latitude.ToString(CultureInfo.InvariantCulture)}&tlon={dest.Longitude.ToString(CultureInfo.InvariantCulture)}&v=foot&fast=1&layer=mapnik"); request.Credentials = CredentialCache.DefaultCredentials; string responseFromServer = ""; request.Timeout = 10000; using (WebResponse response = request.GetResponse()) { Logger.Write("Got response from www.mobrouting.com", LogLevel.Debug); //Console.WriteLine(((HttpWebResponse)response).StatusDescription); using (Stream dataStream = response.GetResponseStream()) using (StreamReader reader = new StreamReader(dataStream)) { responseFromServer = reader.ReadToEnd(); } } //Console.WriteLine(responseFromServer); RoutingResponse responseParsed = JsonConvert.DeserializeObject <RoutingResponse>(responseFromServer); return(responseParsed); } catch (Exception ex) { Logger.Write("Routing error: " + ex.Message, LogLevel.Debug); } var emptyResponse = new RoutingResponse { Coordinates = new List <List <double> >() }; return(emptyResponse); }
private static async Task <List <GeoCoordinate> > CreateHumanRoute(GeoCoordinate destination, CancellationToken cancellationToken, ISession session, bool direct, List <GeoCoordinate> waypointsToVisit, GeoCoordinate currentLocation) { var waypoints = new List <GeoCoordinate>(); if (!direct) { RoutingResponse routingResponse = null; try { switch (session.LogicSettings.RoutingService) { case RoutingService.OpenLs: routingResponse = OsmRouting.GetRoute(currentLocation, destination, session); break; case RoutingService.GoogleDirections: routingResponse = GoogleRouting.GetRoute(currentLocation, destination, session, waypointsToVisit); break; case RoutingService.MapzenValhalla: routingResponse = MapzenRouting.GetRoute(currentLocation, destination, session, waypointsToVisit); break; } } catch (NullReferenceException ex) { session.EventDispatcher.Send(new DebugEvent { Message = ex.ToString() }); routingResponse = new RoutingResponse(); } if (routingResponse?.Coordinates == null) { return(waypoints); } foreach (var item in routingResponse.Coordinates) { if (item == null) { continue; } //0 = lat, 1 = long (MAYBE NOT THO?) switch (session.LogicSettings.RoutingService) { case RoutingService.OpenLs: waypoints.Add(new GeoCoordinate(item.ToArray()[1], item.ToArray()[0], item.ToArray()[2])); break; case RoutingService.GoogleDirections: waypoints.Add(new GeoCoordinate(item[0], item[1])); break; case RoutingService.MapzenValhalla: waypoints.Add(new GeoCoordinate(item[0], item[1])); break; } } if ((session.LogicSettings.RoutingService == RoutingService.GoogleDirections || session.LogicSettings.RoutingService == RoutingService.MapzenValhalla) && session.LogicSettings.UseMapzenApiElevation) { return(await session.MapzenApi.FillAltitude(waypoints, token : cancellationToken)); } return(waypoints); } waypoints.Add(destination); return(waypoints); }
/// <summary> /// /// </summary> /// <param name="destination">Desired location to move</param> /// <param name="walkingSpeedMin">Minimal walking speed during the move</param> /// <param name="walkingSpeedMax">Maximal walking speed during the move</param> /// <param name="functionExecutedWhileWalking">Functions #1 to be exec while walking, like task or smth</param> /// <param name="functionExecutedWhileWalking2">Functions #1 to be exec while walking, like task or smth</param> /// <param name="cancellationToken">regular session cancelation token</param> /// <param name="session">ISession param of the bot, to detect which bot started it</param> /// <param name="direct">Directly move to the point, skip routing services</param> /// <param name="waypointsToVisit">Waypoints to visit during the move, required to redure Google Directions API usage</param> /// <param name="eggWalker"></param> /// <returns></returns> internal async Task <PlayerUpdateResponse> Move(GeoCoordinate destination, double walkingSpeedMin, double walkingSpeedMax, Func <Task <bool> > functionExecutedWhileWalking, Func <Task <bool> > functionExecutedWhileWalking2, CancellationToken cancellationToken, ISession session, bool direct = false, List <GeoCoordinate> waypointsToVisit = null, EggWalker eggWalker = null) { var currentLocation = new GeoCoordinate(_client.CurrentLatitude, _client.CurrentLongitude, _client.CurrentAltitude); var result = new PlayerUpdateResponse(); if (session.LogicSettings.UseHumanPathing) { var waypoints = new List <GeoCoordinate>(); if (!direct) { RoutingResponse routingResponse = null; try { switch (session.LogicSettings.RoutingService) { case RoutingService.MobBot: routingResponse = Routing.GetRoute(currentLocation, destination, session); break; case RoutingService.OpenLs: routingResponse = OsmRouting.GetRoute(currentLocation, destination, session); break; case RoutingService.GoogleDirections: routingResponse = GoogleRouting.GetRoute(currentLocation, destination, session, waypointsToVisit); break; case RoutingService.MapzenValhalla: routingResponse = MapzenRouting.GetRoute(currentLocation, destination, session, waypointsToVisit); break; } } catch (NullReferenceException ex) { session.EventDispatcher.Send(new DebugEvent { Message = ex.ToString() }); routingResponse = new RoutingResponse(); } if (routingResponse?.Coordinates != null) { foreach (var item in routingResponse.Coordinates) { if (item == null) { continue; } //0 = lat, 1 = long (MAYBE NOT THO?) switch (session.LogicSettings.RoutingService) { case RoutingService.MobBot: waypoints.Add(new GeoCoordinate(item[1], item[0])); break; case RoutingService.OpenLs: waypoints.Add(new GeoCoordinate(item.ToArray()[1], item.ToArray()[0], item.ToArray()[2])); break; case RoutingService.GoogleDirections: waypoints.Add(new GeoCoordinate(item[0], item[1])); break; case RoutingService.MapzenValhalla: waypoints.Add(new GeoCoordinate(item[0], item[1])); break; } } if ((session.LogicSettings.RoutingService == RoutingService.GoogleDirections || session.LogicSettings.RoutingService == RoutingService.MobBot || session.LogicSettings.RoutingService == RoutingService.MapzenValhalla) && session.LogicSettings.UseMapzenApiElevation) { waypoints = await session.MapzenApi.FillAltitude(waypoints); } } } if (waypoints.Count == 0) { waypoints.Add(destination); } else if (waypoints.Count > 1) { var nextPath = waypoints.Select(item => Tuple.Create(item.Latitude, item.Longitude)).ToList(); session.EventDispatcher.Send(new NextRouteEvent { Coords = nextPath }); destination = waypoints.Last(); } var navi = new Navigation(_client, UpdatePositionEvent); var waypointsArr = waypoints.ToArray(); long nextMaintenceStamp = 0; //MILD REWRITE TO USE HUMANPATHWALKING; foreach (var t in waypointsArr) { if (session.ForceMoveTo != null) { return(await ForceMoveTask.Execute(session, cancellationToken)); } // skip waypoints under 5 meters var sourceLocation = new GeoCoordinate(_client.CurrentLatitude, _client.CurrentLongitude); var distanceToTarget = LocationUtils.CalculateDistanceInMeters(sourceLocation, t); if (distanceToTarget <= 5) { continue; } var nextSpeed = RandomExtensions.NextInRange(session.Client.rnd, walkingSpeedMin, walkingSpeedMax) * session.Settings.MoveSpeedFactor; session.State = BotState.Walk; result = await navi.HumanPathWalking(session, t, nextSpeed, functionExecutedWhileWalking, functionExecutedWhileWalking2, cancellationToken); if (session.Runtime.BreakOutOfPathing) { return(result); } UpdatePositionEvent?.Invoke(t.Latitude, t.Longitude, t.Altitude); if (nextMaintenceStamp < DateTime.UtcNow.ToUnixTime()) { await MaintenanceTask.Execute(session, cancellationToken); nextMaintenceStamp = DateTime.UtcNow.AddMinutes(3).ToUnixTime(); } if (eggWalker != null) { await eggWalker.ApplyDistance(distanceToTarget, cancellationToken); } } session.State = BotState.Idle; var curcoord = new GeoCoordinate(session.Client.CurrentLatitude, session.Client.CurrentLongitude); if (LocationUtils.CalculateDistanceInMeters(curcoord, destination) > 40) { var nextSpeed = RandomExtensions.NextInRange(session.Client.rnd, walkingSpeedMin, walkingSpeedMax) * session.Settings.MoveSpeedFactor; result = await navi.HumanPathWalking(session, destination, nextSpeed, functionExecutedWhileWalking, functionExecutedWhileWalking2, cancellationToken); } await MaintenanceTask.Execute(session, cancellationToken); } else { if (destination.Latitude.Equals(session.Runtime.lastPokeStopCoordinate.Latitude) && destination.Longitude.Equals(session.Runtime.lastPokeStopCoordinate.Longitude)) { session.Runtime.BreakOutOfPathing = true; } if (session.Runtime.BreakOutOfPathing) { await MaintenanceTask.Execute(session, cancellationToken); return(result); } var navi = new Navigation(_client, UpdatePositionEvent); var curcoord = new GeoCoordinate(session.Client.CurrentLatitude, session.Client.CurrentLongitude); if (LocationUtils.CalculateDistanceInMeters(curcoord, destination) > 40) { var nextSpeed = RandomExtensions.NextInRange(session.Client.rnd, walkingSpeedMin, walkingSpeedMax) * session.Settings.MoveSpeedFactor; result = await navi.HumanPathWalking(session, destination, nextSpeed, functionExecutedWhileWalking, functionExecutedWhileWalking2, cancellationToken); } } session.State = BotState.Idle; await MaintenanceTask.Execute(session, cancellationToken); return(result); }
//Catchem project: https://github.com/Lunat1q/Catchem-PoGo - by Lunat1q public static RoutingResponse GetRoute(GeoCoordinate start, GeoCoordinate dest, ISession session, List <GeoCoordinate> waypoints, bool silent = false, bool via = true) { string apiKey = session.LogicSettings.GoogleDirectionsApiKey; if (string.IsNullOrEmpty(apiKey)) { if (!silent) { session.EventDispatcher.Send(new WarnEvent { Message = "Google API Key is Empty!" }); } return(new RoutingResponse()); } if (waypoints != null && waypoints.Count > 0) { dest = waypoints.Last(); waypoints.RemoveAt(waypoints.Count - 1); } string waypointsRequest = ""; if (waypoints != null && waypoints.Count > 0) { waypointsRequest = "&waypoints=optimize:true|"; var wpList = new List <string>(); foreach (var wp in waypoints) { wpList.Add($"{(via ? "via:" : "")}{wp.Latitude.ToString(CultureInfo.InvariantCulture)},{wp.Longitude.ToString(CultureInfo.InvariantCulture)}"); } waypointsRequest += wpList.Aggregate((x, v) => x + "|" + v); } try { Logger.Write("Requesting routing info to Google Directions API", LogLevel.Debug); var request = WebRequest.Create( "https://maps.googleapis.com/maps/api/directions/json?" + $"origin={start.Latitude.ToString(CultureInfo.InvariantCulture)},{start.Longitude.ToString(CultureInfo.InvariantCulture)}" + $"&destination={dest.Latitude.ToString(CultureInfo.InvariantCulture)},{dest.Longitude.ToString(CultureInfo.InvariantCulture)}" + waypointsRequest + "&mode=walking" + $"&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 Google", LogLevel.Debug); //Console.WriteLine(((HttpWebResponse)response).StatusDescription); using (var dataStream = response.GetResponseStream()) using (var reader = new StreamReader(dataStream)) { responseFromServer = reader.ReadToEnd(); } } var googleResponse = JsonConvert.DeserializeObject <GoogleResponse>(responseFromServer);;// HandleResponse(responseFromServer); var responseParsed = new RoutingResponse(); //var googleCoords = new List<List<double>>(); var route = googleResponse.routes.FirstOrDefault(); if (route != null) { //var wpOrder = route.waypoint_order; //var legs = googleResponse.routes.FirstOrDefault()?.legs; //if (legs != null) //{ // if (wpOrder != null && wpOrder.Count > 0) // { // var orderedLegs = new List<Leg>(); // foreach (int index in wpOrder) // { // orderedLegs.Add(legs[index]); // } // legs = orderedLegs; // } // foreach (var leg in legs) // { // foreach (var step in leg.steps) // { // googleCoords.Add(new List<double> {step.start_location.lat, step.start_location.lng}); // } // } //} var testCoords = route.overview_polyline.DecodeToList(); responseParsed.Coordinates = testCoords.ToList(); // googleCoords; // } return(responseParsed); } catch (Exception ex) { Logger.Write("Routing error: " + ex.Message, LogLevel.Debug); } RoutingResponse emptyResponse = new RoutingResponse(); return(emptyResponse); }
public async Task <PlayerUpdateResponse> Move(GeoCoordinate destination, double walkingSpeedMin, double walkingSpeedMax, Func <Task <bool> > functionExecutedWhileWalking, Func <Task <bool> > functionExecutedWhileWalking2, CancellationToken cancellationToken, ISession session, bool direct = false) { var currentLocation = new GeoCoordinate(_client.CurrentLatitude, _client.CurrentLongitude, _client.CurrentAltitude); var result = new PlayerUpdateResponse(); if (session.LogicSettings.UseHumanPathing) { ////initial coordinate generaton ////prepare the result object for further manipulation + return ////initial time //var requestSendDateTime = DateTime.Now; //var distanceToDest = LocationUtils.CalculateDistanceInMeters(currentLocation, destination); //double metersPerInterval = 0.5; //approximate meters for each interval/waypoint to be spaced from the last. //////get distance ofc //////create segments //var segments = Math.Floor(distanceToDest / metersPerInterval); List <GeoCoordinate> waypoints = new List <GeoCoordinate>(); ////get differences in lat / long //var latDiff = Math.Abs(currentLocation.Latitude - destination.Latitude); //var lonDiff = Math.Abs(currentLocation.Longitude - destination.Longitude); //var latAdd = latDiff / segments; //var lonAdd = latDiff / segments; //var lastLat = currentLocation.Latitude; //var lastLon = currentLocation.Longitude; ////generate waypoints old code -goes in straight line basically //for (int i = 0; i < segments; i++) //{ // //TODO: add altitude calculations into everything // lastLat += latAdd; // lastLon += lonAdd; // waypoints.Add(new GeoCoordinate(lastLat, lastLon, currentLocation.Altitude)); //} //TODO: refactor the generation of waypoint code to break the waypoints given to us by the routing information down into segements like above. //generate waypoints new code if (!direct) { //var routingResponse = OsmRouting.GetRoute(currentLocation, destination, session); //waypoints = routingResponse.Coordinates; RoutingResponse routingResponse; try { routingResponse = !session.LogicSettings.UseOpenLsRouting ? Routing.GetRoute(currentLocation, destination) : OsmRouting.GetRoute(currentLocation, destination, session); } catch (NullReferenceException ex) { session.EventDispatcher.Send(new DebugEvent { Message = ex.ToString() }); routingResponse = new RoutingResponse(); } if (routingResponse?.Coordinates != null) { foreach (var item in routingResponse.Coordinates) { if (item == null) { continue; } //0 = lat, 1 = long (MAYBE NOT THO?) waypoints.Add(!session.LogicSettings.UseOpenLsRouting ? new GeoCoordinate(item.ToArray()[1], item.ToArray()[0], session.LogicSettings.UseMapzenApiElevation ? session.MapzenApi.GetAltitude(item.ToArray()[1], item.ToArray()[0]) : 0) : new GeoCoordinate(item.ToArray()[1], item.ToArray()[0], item.ToArray()[2])); } } } if (waypoints.Count == 0) { waypoints.Add(destination); } else if (waypoints.Count > 1) { var nextPath = waypoints.Select(item => Tuple.Create(item.Latitude, item.Longitude)).ToList(); session.EventDispatcher.Send(new NextRouteEvent { Coords = nextPath }); } //var timeSinceMoveStart = DateTime.Now.Ticks; //double curAcceleration = 1.66; //Lets assume we accelerate at 1.66 m/s ish. TODO: Fuzz this a bit //double curWalkingSpeed = 0; //double maxWalkingSpeed = (session.LogicSettings.WalkingSpeedInKilometerPerHour / 3.6); //Get movement speed in meters ////TODO: Maybe update SensorInfo to replicate/mimic movement, or is it fine as is? //bool StopWalking = false; //double TimeToAccelerate = GetAccelerationTime(curWalkingSpeed, maxWalkingSpeed, curAcceleration); ////double InitialMove = getDistanceTraveledAccelerating(TimeToAccelerate, curAcceleration, curWalkingSpeed); //double MoveLeft = curWalkingSpeed; //bool NeedMoreMove = false; //bool StopMove = false; //int UpdateInterval = 1; // in seconds - any more than this breaks the calculations for distance and such. It all relys on taking ~1 second to perform the actions needed, pretty much. //makes you appear to move slower if you're catching pokemon, hitting stops, etc. //This feels like more human behavior. Dunnomateee Navigation navi = new Navigation(_client, UpdatePositionEvent); var waypointsArr = waypoints.ToArray(); //MILD REWRITE TO USE HUMANPATHWALKING; foreach (var t in waypointsArr) { if (session.ForceMoveTo != null) { return(await ForceMoveTask.Execute(session, cancellationToken)); } // skip waypoints under 5 meters var sourceLocation = new GeoCoordinate(_client.CurrentLatitude, _client.CurrentLongitude); var distanceToTarget = LocationUtils.CalculateDistanceInMeters(sourceLocation, t); if (distanceToTarget <= 5) { continue; } var nextSpeed = session.Client.rnd.NextInRange(walkingSpeedMin, walkingSpeedMax) * session.Settings.MoveSpeedFactor; result = await navi.HumanPathWalking(t, nextSpeed, functionExecutedWhileWalking, functionExecutedWhileWalking2, cancellationToken); if (RuntimeSettings.BreakOutOfPathing) { return(result); } UpdatePositionEvent?.Invoke(t.Latitude, t.Longitude, t.Altitude); //Console.WriteLine("Hit waypoint " + x); } var curcoord = new GeoCoordinate(session.Client.CurrentLatitude, session.Client.CurrentLongitude); if (LocationUtils.CalculateDistanceInMeters(curcoord, destination) > 40) { var nextSpeed = session.Client.rnd.NextInRange(walkingSpeedMin, walkingSpeedMax) * session.Settings.MoveSpeedFactor; result = await navi.HumanPathWalking(destination, nextSpeed, functionExecutedWhileWalking, functionExecutedWhileWalking2, cancellationToken); } } else { if (destination.Latitude.Equals(RuntimeSettings.lastPokeStopCoordinate.Latitude) && destination.Longitude.Equals(RuntimeSettings.lastPokeStopCoordinate.Longitude)) { RuntimeSettings.BreakOutOfPathing = true; } if (RuntimeSettings.BreakOutOfPathing) { await MaintenanceTask.Execute(session, cancellationToken); return(result); } var navi = new Navigation(_client, UpdatePositionEvent); var curcoord = new GeoCoordinate(session.Client.CurrentLatitude, session.Client.CurrentLongitude); if (LocationUtils.CalculateDistanceInMeters(curcoord, destination) > 40) { var nextSpeed = session.Client.rnd.NextInRange(walkingSpeedMin, walkingSpeedMax) * session.Settings.MoveSpeedFactor; result = await navi.HumanPathWalking(destination, nextSpeed, functionExecutedWhileWalking, functionExecutedWhileWalking2, cancellationToken); } } await MaintenanceTask.Execute(session, cancellationToken); return(result); }