예제 #1
0
        private static void UpdateTravelTimeInDB(RouteStop routeStop)
        {
            var dbRouteStop = (from rs in db.RouteStops
                               where rs.ID == routeStop.ID
                               select rs).FirstOrDefault();

            if (dbRouteStop == null)
            {
                return;
            }
            dbRouteStop.AverageTravelTimeToNextStop = routeStop.AverageTravelTimeToNextStop;
            db.SaveChanges();
        }
        public IHttpActionResult PostLocation(int id, LocationUpdate locationUpdate)
        {
            if (AppSettingsInterface.UseSyncromatics)
            {
                return(Ok());                                       // Disregard beacon if using Syncromatics
            }
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            using (var db = new TrolleyTracker.Models.TrolleyTrackerContext())
            {
                var trolley = (from Trolley t in db.Trolleys
                               where t.Number == id
                               select t).FirstOrDefault <Trolley>();
                if (trolley == null)
                {
                    return(NotFound());
                }

                if ((locationUpdate.Lat < -90.0) || (locationUpdate.Lat > 90))
                {
                    return(BadRequest("Invalid latitude"));
                }
                if ((locationUpdate.Lon < -180.0) || (locationUpdate.Lon > 180))
                {
                    return(BadRequest("Invalid longitude"));
                }

                trolley.CurrentLat     = locationUpdate.Lat;
                trolley.CurrentLon     = locationUpdate.Lon;
                trolley.LastBeaconTime = UTCToLocalTime.LocalTimeFromUTC(DateTime.UtcNow);
                if (lastTrolleyWriteTime.ContainsKey(trolley.Number))
                {
                    if ((DateTime.Now - lastTrolleyWriteTime[trolley.Number]).TotalSeconds > 30.0)
                    {
                        db.SaveChanges();
                        lastTrolleyWriteTime[trolley.Number] = DateTime.Now;
                    }
                }
                else
                {
                    lastTrolleyWriteTime.Add(trolley.Number, DateTime.Now);
                }
                TrolleyCache.UpdateTrolley(trolley);
                StopArrivalTime.UpdateTrolleyStopArrivalTime(trolley);

                return(Ok());
            }
        }
        const double MinStopProximity = 20.0; // Meters

        #endregion Fields

        #region Methods

        /// <summary>
        /// Recalculate which routes the stops belong to, and the order.
        /// Call after any change to route or stops
        /// </summary>
        /// <param name="routeID">Route being recalculated</param>
        /// <param name="shapePoints"></param>
        /// <param name="stopPoints"></param>
        public void UpdateRouteStops(TrolleyTrackerContext db, int routeID, List<Coordinate> shapePoints, List<Stop> stops)
        {
            RemovePreviousRouteStops(db, routeID);

            var route = (from Route in db.Routes
                         where Route.ID == routeID
                         select Route).FirstOrDefault<Route>();

            // A stop is considered to belong to a route if it's within MinStopProximity meters of the route path
            var routeStopList = new List<Stop>();

            if (route.FlagStopsOnly)
            {
                // No stops to generate
                return;
            }

            for (int i=1; i< shapePoints.Count; i++)
            {
                for (int s=0; s< stops.Count; s++)
                {
                    var stop = stops[s];
                    var stopPosition = new Coordinate(0, stop.Lat, stop.Lon, null);
                    Coordinate closest = null;
                    var distance = FindDistanceToSegment(stopPosition, shapePoints[i], shapePoints[i - 1], out closest);
                    if (distance < MinStopProximity)
                    {
                        if (!routeStopList.Contains(stop))
                        {
                            routeStopList.Add(stop);
                        }
                        //break;   //  Bug? How to handle case of ordering multiple stops in a long straight segment
                    }
                }
            }

            for (int i=0; i < routeStopList.Count; i++)
            {
                var newRouteStop = db.RouteStops.Create();
                newRouteStop.RouteID = routeID;
                newRouteStop.StopID = routeStopList[i].ID;
                newRouteStop.StopSequence = i;
                db.RouteStops.Add(newRouteStop);
            }
            db.SaveChanges();
        }
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                Coordinate lastCoordinate = null;

                var strRouteID = collection.Get("RouteID");

                // Parse Geo-JSON formatted route coordinates
                var jsonShapes = collection.Get("JSONText");
                if (jsonShapes != null && strRouteID != null)
                {
                    int routeID = Convert.ToInt32(strRouteID);

                    using (var db = new TrolleyTracker.Models.TrolleyTrackerContext())
                    {
                        RemoveOldShape(routeID, db);

                        JavaScriptSerializer jss = new JavaScriptSerializer();
                        jss.RegisterConverters(new JavaScriptConverter[] { new DynamicJsonConverter() });

                        dynamic shapeData = jss.Deserialize(jsonShapes, typeof(object)) as dynamic;

                        var features = shapeData.features;
                        var geometryBlock = features[0];
                        var geometry = geometryBlock["geometry"];
                        var geoJSONtype = geometry["type"];
                        var coordinates = geometry["coordinates"];

                        int segmentCount = coordinates.Count;
                        if (geoJSONtype == "LineString") segmentCount = 1;
                        int sequence = 0;
                        double totalDistance = 0.0;
                        for (int seg = 0; seg < segmentCount; seg++)
                        {
                            var coordArray = coordinates[seg];
                            if (geoJSONtype == "LineString") coordArray = coordinates;
                            int nodeCount = coordArray.Count;
                            for (int i = 0; i < nodeCount; i++)
                            {
                                var node = coordArray[i];
                                var strLon = node[0];
                                var strLat = node[1];
                                var lon = Convert.ToDouble(strLon);
                                var lat = Convert.ToDouble(strLat);

                                var thisCoordinate = new Coordinate(0, lat, lon, null);
                                double distance = 0.0;
                                if (lastCoordinate != null)
                                {
                                    distance = thisCoordinate.GreatCircleDistance(lastCoordinate);
                                }
                                lastCoordinate = thisCoordinate;
                                totalDistance += distance;

                                var dbShape = new TrolleyTracker.Models.Shape();
                                dbShape.Lat = lat;
                                dbShape.Lon = lon;
                                dbShape.RouteID = routeID;
                                dbShape.Sequence = sequence;
                                dbShape.DistanceTraveled = totalDistance;
                                sequence++;
                                db.Shapes.Add(dbShape);
                            }

                        }
                        db.SaveChanges();

                        var assignStops = new AssignStopsToRoutes();
                        assignStops.UpdateStopsForRoute(db, routeID);
                    }

                }

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                Coordinate lastCoordinate = null;

                var strRouteID = collection.Get("RouteID");


                // Parse Geo-JSON formatted route coordinates
                var jsonShapes = collection.Get("JSONText");
                if (jsonShapes != null && strRouteID != null)
                {
                    int routeID = Convert.ToInt32(strRouteID);

                    using (var db = new TrolleyTracker.Models.TrolleyTrackerContext())
                    {
                        RemoveOldShape(routeID, db);

                        JavaScriptSerializer jss = new JavaScriptSerializer();
                        jss.RegisterConverters(new JavaScriptConverter[] { new DynamicJsonConverter() });

                        dynamic shapeData = jss.Deserialize(jsonShapes, typeof(object)) as dynamic;

                        var features      = shapeData.features;
                        var geometryBlock = features[0];
                        var geometry      = geometryBlock["geometry"];
                        var geoJSONtype   = geometry["type"];
                        var coordinates   = geometry["coordinates"];

                        int segmentCount = coordinates.Count;
                        if (geoJSONtype == "LineString")
                        {
                            segmentCount = 1;
                        }
                        int    sequence      = 0;
                        double totalDistance = 0.0;
                        for (int seg = 0; seg < segmentCount; seg++)
                        {
                            var coordArray = coordinates[seg];
                            if (geoJSONtype == "LineString")
                            {
                                coordArray = coordinates;
                            }
                            int nodeCount = coordArray.Count;
                            for (int i = 0; i < nodeCount; i++)
                            {
                                var node   = coordArray[i];
                                var strLon = node[0];
                                var strLat = node[1];
                                var lon    = Convert.ToDouble(strLon);
                                var lat    = Convert.ToDouble(strLat);

                                var    thisCoordinate = new Coordinate(lat, lon);
                                double distance       = 0.0;
                                if (lastCoordinate != null)
                                {
                                    distance = thisCoordinate.GreatCircleDistance(lastCoordinate);
                                }
                                lastCoordinate = thisCoordinate;
                                totalDistance += distance;

                                var dbShape = new TrolleyTracker.Models.Shape();
                                dbShape.Lat              = lat;
                                dbShape.Lon              = lon;
                                dbShape.RouteID          = routeID;
                                dbShape.Sequence         = sequence;
                                dbShape.DistanceTraveled = totalDistance;
                                sequence++;
                                db.Shapes.Add(dbShape);
                            }
                        }
                        db.SaveChanges();

                        var assignStops = new AssignStopsToRoutes();
                        assignStops.UpdateStopsForRoute(db, routeID);

                        var route = db.Routes.Find(routeID);
                        logger.Info($"Modified route shape of '{route.Description}' - '{route.LongName}'");
                    }
                }

                return(RedirectToAction("Index"));
            }
            catch (Exception ex)
            {
                ViewBag.Message = "Shape save exception";

                logger.Error(ex, "Exception saving route shape");
                ViewBag.RouteID = new SelectList(db.Routes, "ID", "ShortName");
                return(View());
            }
        }
        private void RemovePreviousRouteStops(TrolleyTrackerContext db, int routeID)
        {
            var routeStops = from RouteStop rs in db.RouteStops
                              where rs.RouteID == routeID
                              select rs;

            foreach (var rs in routeStops)
            {
                db.RouteStops.Remove(rs);
            }
            db.SaveChanges();
        }