예제 #1
0
        /// <summary>
        /// Using the vehicle name in the Tconnect, this function returns the latest known location and time of the vehicle.
        /// </summary>
        /// <param name="tConnect">tconnect containing the vehicle to monitor/check on.</param>
        /// <param name="currentLocTime">returns Time when the latest location was recorded.</param>
        /// <param name="currentLoc">returns latest location of vehicle on record.</param>
        //private void GetLatestVehicleLocation(TConnect tConnect, out DateTime currentLocTime, out GeoCoordinate currentLoc)
        //{
        //    IAzureTable<ProbeSnapshotEntry> probeTable = WorkerRole.Kernel.Get<IAzureTable<ProbeSnapshotEntry>>();
        //    ProbeSnapshotEntry probe = GetLatestLocationFromTable(tConnect.InboundVehicle, probeTable);
        //    //DateTimes in VS by default are 4 hours behind the Date we pull from Azure Tables.
        //    //When we load a snapshot to the Azure table, it is converted to UTC time
        //    //currentLocTime = probe.PositionTimestamp.ToLocalTime();
        //    currentLocTime = probe.PositionTimestamp;
        //    currentLoc = new GeoCoordinate(probe.Latitude, probe.Longitude);
        //}
        /// <summary>
        /// Retrieves the latest ProbeSnapshotEntry for the given inboundVehicle name from the provided AzureTable
        /// </summary>
        /// <param name="inboundVehicle">name of vehicle</param>
        /// <param name="probeTable">Azure Table to check for records.</param>
        /// <returns></returns>
        //protected ProbeSnapshotEntry GetLatestLocationFromTable(string inboundVehicle, IAzureTable<ProbeSnapshotEntry> probeTable)
        //{
        //    //CloudStorageAccount storageAccount = CloudStorageAccount.FromConfigurationSetting("StorageConnectionString");
        //    //IAzureTable<ProbeSnapshotEntry> probeTable = new AzureTable<ProbeSnapshotEntry>(storageAccount);
        //    try
        //    {
        //        List<ProbeSnapshotEntry> tripProbes = probeTable.Query.Where(p => p.PartitionKey == inboundVehicle).ToList();
        //        return tripProbes.OrderBy(p => p.PositionTimestamp).Last();
        //    }
        //    catch(Exception ex)
        //    {
        //        throw new Exception("No ProbeSnapshotEntries found in Azure Table for " + inboundVehicle + ". Exception: " + ex.Message);
        //    }
        //}
        /// <summary>
        /// Based on the location and time at Point A, this function calculates the Estimated Time of Arrival
        /// at another Point, B, based on a fixed rate of 20 mph.
        /// </summary>
        /// <param name="PointB">destination position</param>
        /// <param name="TimeAtPointA">time at current position</param>
        /// <param name="PointA">current position</param>
        /// <returns></returns>
        protected static DateTime CalcPointBEtaFromPointA(GeoCoordinate PointB, DateTime TimeAtPointA, GeoCoordinate PointA)
        {
            RestClient client = new RestClient
            {
                BaseUrl = BaseUrl
            };
            OpenTripPlannerAdapter otpa = new OpenTripPlannerAdapter(client);

            DateTime eta = new DateTime();

            var trip = otpa.PlanTrip((float)PointA.Latitude, (float)PointA.Longitude, (float)PointB.Latitude, (float)PointB.Longitude, "CAR", DateTime.Now);

            if (trip.plan != null)
            {
                var itinerary = trip.plan.itineraries.FirstOrDefault();
                eta = TimeAtPointA.AddMilliseconds(itinerary.duration);
            }
            //else we don't have an eta to return
            return(eta);

            //Calculate distance between the two points.
            //double distanceMeters = PointB.GetDistanceTo(PointA);//The distance between the two coordinates, in meters.

            //Loosely Estimate an arrival based on an assumed speed. r*t=distance
            //20 mph = 8.9mps
            //15 Miles per Hour = 6.7056 Meters per Second
            //double seconds = distanceMeters / 6.7;
            //DateTime ETA = TimeAtPointA.AddSeconds(seconds);
            //return eta;
        }
예제 #2
0
        /// <summary>
        /// Gets the stops near point.
        /// </summary>
        /// <param name="latitude">The latitude.</param>
        /// <param name="longitude">The longitude.</param>
        /// <param name="radius">The radius.</param>
        /// <returns></returns>
        public Itinerary GetEta(float startLatitude, float startLongitude, float endLatitude, float endLongitude)
        {
            RestClient client = new RestClient
            {
                BaseUrl = BaseUrl
            };

            OpenTripPlannerAdapter otpa = new OpenTripPlannerAdapter(client);

            return(otpa.PlanTrip(startLatitude, startLongitude, endLatitude, endLongitude, "CAR", DateTime.Now).plan.itineraries.FirstOrDefault());
        }
예제 #3
0
        /// <summary>
        /// Gets the stop times.
        /// </summary>
        /// <param name="stopId">The stop identifier.</param>
        /// <param name="startTime">The start time.</param>
        /// <param name="endTime">The end time.</param>
        /// <returns></returns>
        public StopTimesList GetStopTimes(string agency, string stopId, long startTime, long endTime)
        {
            RestClient client = new RestClient
            {
                BaseUrl = BaseUrl
            };

            OpenTripPlannerAdapter otpa = new OpenTripPlannerAdapter(client);

            return(otpa.FindStopTimes(agency, stopId, startTime, endTime));
        }
예제 #4
0
        /// <summary>
        /// Gets the stops near point.
        /// </summary>
        /// <param name="latitude">The latitude.</param>
        /// <param name="longitude">The longitude.</param>
        /// <param name="radius">The radius.</param>
        /// <returns></returns>
        public StopList GetStopsNearPoint(float latitude, float longitude, int radius)
        {
            RestClient client = new RestClient
            {
                BaseUrl = BaseUrl
            };

            OpenTripPlannerAdapter otpa = new OpenTripPlannerAdapter(client);

            return(otpa.FindStopsNearPoint(latitude, longitude, radius));
        }
예제 #5
0
        public void GetStopTimes_Passes()
        {
            //Arrange
            RestResponse <StopTimesList> response = new RestResponse <StopTimesList>();

            response.Data = new StopTimesList();
            StopTime sampleDepartureStopTime = new StopTime
            {
                phase = "departure",
                time  = 1386078245,
                trip  = new Trip()
                {
                    tripShortName = "Trips Short Name",
                    tripHeadsign  = "10E EAST BROAD TO MC NAUGHTEN AND MOUNT CARMEL HOSPITAL",
                    id            = new Id()
                    {
                        agencyId = "COTA", id = "466817"
                    }
                }
            };

            response.Data.stopTimes.Add(sampleDepartureStopTime);

            StopTime sampleArrivalStopTime = new StopTime
            {
                phase = "arrival",
                time  = 1386078245,
                trip  = new Trip()
                {
                    tripShortName = "Trips Short Name",
                    tripHeadsign  = "10E EAST BROAD TO MC NAUGHTEN AND MOUNT CARMEL HOSPITAL",
                    id            = new Id()
                    {
                        agencyId = "COTA", id = "466817"
                    }
                }
            };

            response.Data.stopTimes.Add(sampleArrivalStopTime);

            var mock = new Mock <IRestClient>();

            mock.Setup(foo => foo.Execute <StopTimesList>(It.IsAny <IRestRequest>())).Returns(response);

            //Act
            OpenTripPlannerAdapter cut = new OpenTripPlannerAdapter(mock.Object);

            var results = cut.FindStopTimes("COTA", "2501", DateTime.UtcNow.AddHours(-5), DateTime.UtcNow);

            Assert.AreEqual(1, results.stopTimes.Count);
            Assert.AreEqual("departure", results.stopTimes.First().phase);
        }
예제 #6
0
        public void GetStopsNearPoint_Passes()
        {
            //Arrange
            RestResponse <StopList> response = new RestResponse <StopList>();

            Stop sampleStop1 = new Stop
            {
                stopCode = "BROROBE",
                stopName = "E BROAD ST & ROBINWOOD AVE",
                stopLat  = 39.973759,
                stopLon  = -82.89616,
                id       = new Id()
                {
                    agencyId = "COTA", id = "2501"
                }
            };

            Stop sampleStop2 = new Stop
            {
                stopCode = "BROBEETE",
                stopName = "E BROAD ST & BEECHTREE RD",
                stopLat  = 39.973919,
                stopLon  = -82.894701,
                id       = new Id()
                {
                    agencyId = "COTA", id = "2502"
                }
            };

            response.Data = new StopList();
            response.Data.stops.Add(sampleStop1);
            response.Data.stops.Add(sampleStop2);

            var mock = new Mock <IRestClient>();

            mock.Setup(foo => foo.Execute <StopList>(It.IsAny <IRestRequest>())).Returns(response);

            //Act
            OpenTripPlannerAdapter cut = new OpenTripPlannerAdapter(mock.Object);

            var results = cut.FindStopsNearPoint(39.974639f, -82.894460f, 500);

            Assert.AreEqual(2, results.stops.Count);
        }
예제 #7
0
        public void GetServersVersion_Passes()
        {
            //Arrange
            RestResponse <ServerInfo> response = new RestResponse <ServerInfo>();

            response.Data = new ServerInfo();
            response.Data.serverVersion.version = "0.9.1-SNAPSHOT";

            var mock = new Mock <IRestClient>();

            mock.Setup(foo => foo.Execute <ServerInfo>(It.IsAny <IRestRequest>())).Returns(response);

            //Act
            OpenTripPlannerAdapter cut = new OpenTripPlannerAdapter(mock.Object);

            var results = cut.GetServerInfo();

            Assert.AreEqual("0.9.1-SNAPSHOT", results.serverVersion.version);
        }
예제 #8
0
        public IHttpActionResult GetTrip(float startLatitude, float startLongitude, string startLocation,
                                         float endLatitude, float endLongitude, string endLocation,
                                         bool searchByArriveByTime, DateTime time, bool needWheelchairAccess, float maxWalkMeters)
        {
            System.Net.Http.HttpRequestMessage currentRequest = this.Request;

            DateTime           dtStart            = DateTime.UtcNow;
            WebApiGetTripUsage webApiGetTripUsage = new WebApiGetTripUsage();

            webApiGetTripUsage.FromPlace     = startLocation;
            webApiGetTripUsage.ToPlace       = endLocation;
            webApiGetTripUsage.CreatedDate   = dtStart;
            webApiGetTripUsage.MaxWalkMeters = maxWalkMeters;
            webApiGetTripUsage.SearchDate    = time;
            webApiGetTripUsage.Platform      = System.Web.HttpContext.Current.Request.UserAgent;


            string     json   = "";
            RestClient client = new RestClient
            {
                BaseUrl = BaseUrl
            };

            RestClient zimrideclient = new RestClient
            {
                BaseUrl = ZimRideBaseUrl
            };

            //Validate that the caller gave either the lat/long or the string for each endpoint.
            if (String.IsNullOrEmpty(startLocation))
            {
                //string not provided, so lat/long had better be valid or it is an error.
                if (startLatitude == 0 || startLongitude == 0)
                {
                    HttpResponseMessage responseMessage = Request.CreateErrorResponse(HttpStatusCode.BadRequest,
                                                                                      "Lat/Long must be specified for start location if address option not specified. ");
                    throw new HttpResponseException(responseMessage);
                }
            }
            if (String.IsNullOrEmpty(endLocation))
            {
                //string not provided, so lat/long had better be valid or it is an error.
                if (endLatitude == 0 || endLongitude == 0)
                {
                    HttpResponseMessage responseMessage = Request.CreateErrorResponse(HttpStatusCode.BadRequest,
                                                                                      "Lat/Long must be specified for end location if address option not specified. ");
                    throw new HttpResponseException(responseMessage);
                }
            }

            //Create trip start and end lat/long pairs
            if (String.IsNullOrWhiteSpace(startLocation))
            {
                //HttpResponseMessage responseMessage = Request.CreateErrorResponse(HttpStatusCode.BadRequest,
                //       "Start Location empty cannot obtain trip start lat/long.");
                // throw new HttpResponseException(responseMessage);
            }
            else
            {
                GeoLocation.GeolookupResult geoLocResult = new GeoLocation.GeolookupResult();
                GeoLocation geoLoc = new GeoLocation();
                geoLocResult = geoLoc.GetLatLongForAddress(startLocation);
                if (geoLocResult.APIReturnStatus == "OK")
                {
                    startLatitude  = geoLocResult.position[0];
                    startLongitude = geoLocResult.position[1];
                }
                else
                {
                    HttpResponseMessage responseMessage = Request.CreateErrorResponse(HttpStatusCode.BadRequest,
                                                                                      "Invalid trip starting location - geocode return value: " + geoLocResult.APIReturnStatus);
                    throw new HttpResponseException(responseMessage);
                }
            }

            if (String.IsNullOrWhiteSpace(endLocation))
            {
                //HttpResponseMessage responseMessage = Request.CreateErrorResponse(HttpStatusCode.BadRequest,
                //       "End Location empty cannot obtain trip end lat/long.");
                //throw new HttpResponseException(responseMessage);
            }
            else
            {
                GeoLocation.GeolookupResult geoLocResult = new GeoLocation.GeolookupResult();
                GeoLocation geoLoc = new GeoLocation();
                geoLocResult = geoLoc.GetLatLongForAddress(endLocation);
                if (geoLocResult.APIReturnStatus == "OK")
                {
                    endLatitude  = geoLocResult.position[0];
                    endLongitude = geoLocResult.position[1];
                }
                else
                {
                    HttpResponseMessage responseMessage = Request.CreateErrorResponse(HttpStatusCode.BadRequest,
                                                                                      "Invalid trip ending location - geocode return value: " + geoLocResult.APIReturnStatus);
                    throw new HttpResponseException(responseMessage);
                }
            }


            OpenTripPlannerAdapter otpa = new OpenTripPlannerAdapter(client);
            ZimrideAdapter         zra  = new ZimrideAdapter(zimrideclient);

            //TODO: add more of the parameters.
            //Query trip
            // json = otpa.PlanTrip(startLatitude, startLongitude, endLatitude, endLongitude, "TRANSIT,WALK", time).ToString();

            //return json
            //return JsonConvert.SerializeObject(json, Formatting.Indented);

            webApiGetTripUsage.FromLatitude  = startLatitude;
            webApiGetTripUsage.FromLongitude = startLongitude;
            webApiGetTripUsage.ToLatitude    = endLatitude;
            webApiGetTripUsage.ToLongitude   = endLongitude;

            var response = otpa.PlanAdvancedTrip(startLatitude, startLongitude, endLatitude, endLongitude, "TRANSIT,WALK", time, searchByArriveByTime, needWheelchairAccess, maxWalkMeters);

            if (response == null || response.plan == null)
            {
                return(NotFound());
            }

            var zimrides = zra.PlanAdvancedTrip(startLatitude, startLongitude, endLatitude, endLongitude, "ZIMRIDE", time, searchByArriveByTime, needWheelchairAccess, maxWalkMeters, 174);


            List <Itinerary> itList = new List <Itinerary>(response.plan.itineraries);

            foreach (var itinerary in itList)
            {
                DateTime dtUCTNow  = DateTime.UtcNow;
                DateTime tripStart = itinerary.startTime.ToDateTimeUTC();
                if (tripStart <= dtUCTNow)
                {
                    //trip starts in past remove from list
                    response.plan.itineraries.Remove(itinerary);
                }
            }

            response.plan.itineraries.AddRange(zimrides.plan.itineraries);

            itList = new List <Itinerary>(response.plan.itineraries);
            foreach (var itinerary in itList)
            {
                foreach (var leg in itinerary.legs)
                {
                    if (String.IsNullOrEmpty(leg.from.stopCode))
                    {
                        if (leg.from.stopId != null)
                        {
                            leg.from.stopCode = leg.from.stopId.id;
                        }
                    }

                    if (String.IsNullOrEmpty(leg.to.stopCode))
                    {
                        if (leg.to.stopId != null)
                        {
                            leg.to.stopCode = leg.to.stopId.id;
                        }
                    }

                    if (leg != null && leg.from != null && leg.from.name != null && leg.from.name.StartsWith("way"))
                    {
                        leg.from.name = "Unnamed Road";
                    }

                    if (leg != null && leg.to != null && leg.to.name != null && leg.to.name.StartsWith("way"))
                    {
                        leg.to.name = "Unnamed Road";
                    }
                }
            }

            try
            {
                DateTime dtEnd           = DateTime.UtcNow;
                TimeSpan tsExecutionTime = dtEnd - dtStart;

                webApiGetTripUsage.NumberOfResults      = response.plan.itineraries.Count;
                webApiGetTripUsage.ExecutionTimeSeconds = Convert.ToInt32(tsExecutionTime.TotalSeconds);

                Uow.Repository <WebApiGetTripUsage>().Insert(webApiGetTripUsage);
                Uow.Save();
            }
            catch (Exception ex) { }

            return(Ok(response.plan));
        }