Exemple #1
0
        private SectionConfigurationModel GetSectionByIP(string iPAddressPointA, string iPAddressPointB, DateTime eventsAfter)
        {
            AtPointService cpds = new AtPointService();

            FilterModel filterSourceA = new FilterModel
            {
                Operation    = Operation.Equals,
                PropertyName = "ListenerSource",
                Value        = iPAddressPointA
            };

            FilterModel filterEvent = new FilterModel
            {
                Operation    = Operation.GreaterThan,
                PropertyName = "EventDateTime",
                Value        = eventsAfter
            };

            IList <FilterModel> filters = new List <FilterModel>
            {
                filterEvent,
                filterSourceA
            };

            PaginationListModel <AtPointModel> itemsPointA = cpds.GetPaginatedList(filters, FilterJoin.And, true, "ListenerSource", 0, 1);

            FilterModel filterSourceB = new FilterModel
            {
                Operation    = Operation.Equals,
                PropertyName = "ListenerSource",
                Value        = iPAddressPointB
            };

            filters = new List <FilterModel>
            {
                filterEvent,
                filterSourceB
            };

            PaginationListModel <AtPointModel> itemsPointB = cpds.GetPaginatedList(filters, FilterJoin.And, true, "ListenerSource", 0, 1);

            if (itemsPointA.TotalCount > 0 && itemsPointB.TotalCount > 0)
            {
                AtPointModel sectionCodeAtPointA = itemsPointA.Models.FirstOrDefault();
                AtPointModel sectionCodeAtPointB = itemsPointB.Models.FirstOrDefault();

                if (sectionCodeAtPointA != null && sectionCodeAtPointB != null)
                {
                    SectionConfigurationModel section = GetSectionByCode(sectionCodeAtPointA.SectionPointCode, sectionCodeAtPointB.SectionPointCode);
                    return(section);
                }
            }

            return(null);
        }
Exemple #2
0
        public void Create(AtPointModel model)
        {
            var request = new RestRequest("api/AtPoint", Method.POST);

            request.AddJsonBody(model);

            var response = RestClient.Execute(request);

            if (response.StatusCode != HttpStatusCode.OK)
            {
                throw CreateException(response);
            }
        }
Exemple #3
0
        public IHttpActionResult GetPaginatedList([FromBody] IList <FilterModel> filters, Kapsch.Gateway.Models.Shared.Enums.FilterJoin filterJoin, bool asc, string orderPropertyName, int pageIndex, int pageSize)
        {
            using (var dbContext = new Kapsch.RTE.Data.DataContext())
            {
                var totalCount = 0;
                var filter     = filters.Select(f => FilterConverter.Convert(f)).ToList();
                var func       = ExpressionBuilder.GetExpression <CameraPointData>(filter, (Core.Filters.FilterJoin)filterJoin);
                var query      = dbContext
                                 .CameraPointsData
                                 .AsNoTracking();
                if (func != null)
                {
                    query = query.Where(func);
                }

                var orderedQuery =
                    asc ?
                    query.OrderByMember(PropertyHelper.GetSortingValue <CameraPointData>(orderPropertyName)) :
                    query.OrderByMemberDescending(PropertyHelper.GetSortingValue <CameraPointData>(orderPropertyName));

                var resultsToSkip = (pageIndex - 1) * pageSize;
                var pageResults   = orderedQuery
                                    .Skip(resultsToSkip)
                                    .Take(pageSize)
                                    .GroupBy(f => new { Total = query.Count() })
                                    .FirstOrDefault();

                var entities = new List <CameraPointData>();

                if (pageResults != null)
                {
                    totalCount = pageResults.Key.Total;
                    entities   = pageResults.ToList();
                }

                var totalPages = Math.Ceiling(totalCount / (float)pageSize);

                var paginationList = new PaginationListModel <AtPointModel>();

                foreach (CameraPointData cameraPointData in entities)
                {
                    AtPointModel model = JsonConvert.DeserializeObject <AtPointModel>(cameraPointData.Json);
                    paginationList.Models.Add(model);
                }

                paginationList.TotalCount = totalCount;

                return(Ok(paginationList));
            }
        }
Exemple #4
0
        /// <summary>
        /// Check if the point in the bag of point expires. The idea is that if the point has remained in the bag for longer than the time
        /// it could take to travel the entire section, the point is expired and could no longer be an infringement irrespective of when the infringements occur.
        /// </summary>
        /// <param name="point"></param>
        /// <returns></returns>
        private bool Expires(AtPointModel point)
        {
            if (point.CreateDate == null)
            {
                point.CreateDate = DateTime.Now;
            }

            double timeH = _sectionDistance / 1000 / point.Classification.Zone;

            DateTime maxTa = point.CreateDate.Value.AddHours(2 * timeH);
            DateTime minTa = point.CreateDate.Value.AddHours(-2 * timeH);

            if (DateTime.Now < minTa || DateTime.Now > maxTa)
            {
                return(true);
            }

            return(false);
        }
Exemple #5
0
        public IHttpActionResult Post([FromBody] AtPointModel model)
        {
            PushSignalR(model);

            using (var dbContext = new RTE.Data.DataContext())
            {
                var pointData =
                    new CameraPointData
                {
                    Json      = JsonConvert.SerializeObject(model),
                    TimeStamp = DateTime.Now
                };

                dbContext.CameraPointsData.Add(pointData);
                dbContext.SaveChanges();

                return(Ok(true));
            }
        }
Exemple #6
0
        private static void PushSignalR(AtPointModel model)
        {
            string json = JsonConvert.SerializeObject(model);

            using (var hubConnection = new HubConnection(SignalRHubUrl))
            {
                var hubProxy = hubConnection.CreateHubProxy("AtPointNotificationHub");

                hubConnection.Start().Wait();

                if (model.IsOffence)
                {
                    hubProxy.Invoke("SendAtPointInfringement", model.SectionPointCode, json).Wait();
                }
                else
                {
                    hubProxy.Invoke("SendAtPointData", model.SectionPointCode, json).Wait();
                }
            }
        }
Exemple #7
0
        public AtPointModel Translate()
        {
            if (TextLine == null)
            {
                throw new Exception("You did not provide a SourceTextLine to translate!");
            }

            AtPointModel model = new AtPointModel
            {
                AnprAccuracy     = Confidence,
                Image            = null,
                MachineId        = MachineId,
                SectionPointCode = LocationCode,
                SerialNumber     = SerialNumber,
                Speed            = null,
                SourceTextLine   = TextLine.ToString(),
                Vln                           = Vln,
                VosiReason                    = VosiReason,
                EventDateTime                 = CreatedOn,
                ImageName                     = EncFileName,
                ImagePhysicalFileAndPath      = EncFileAndPathRaw,
                PlateImageName                = "",
                PlateImagePhysicalFileAndPath = "",
                ShotDistance                  = Distance,
                SectionPointDescription       = ""
            };

            if (Classification.ToUpper() == "L")
            {
                model.Classification = new ClassificationZoneModel
                {
                    Classification = VehicleClassificationEnum.Light
                };
            }

            if (Classification.ToUpper() == "H")
            {
                model.Classification = new ClassificationZoneModel
                {
                    Classification = VehicleClassificationEnum.Heavy
                };
            }

            if (Classification.ToUpper() == "PT")
            {
                model.Classification = new ClassificationZoneModel
                {
                    Classification = VehicleClassificationEnum.PublicTransport
                };
            }

            model.Classification.Zone  = Zone ?? 0;
            model.Classification.Grace = Threshold ?? 0;

            if (Direction == "TOWARDS")
            {
                model.ShotDirection = DirectionEnum.Towards;
            }

            if (Direction == "AWAY")
            {
                model.ShotDirection = DirectionEnum.Away;
            }

            model.PointLocation = new LocationModel
            {
                GpsLatitude  = Latitude,
                GpsLongitude = Longitude
            };

            return(model);
        }
        public SectionCalculationResult(int levensteinMatchDistance, double distanceInMeterInMeter, string sectionDescription, string sectionCode, AtPointModel start, AtPointModel end)
        {
            DateFormat = "dd/MM/yyyy HH:mm:ss";

            SectionDistanceInMeter   = distanceInMeterInMeter;
            AtPointStart             = (AtPointModel)start.Clone();
            AtPointEnd               = (AtPointModel)end.Clone();;
            SectionDescription       = sectionDescription;
            SectionCode              = sectionCode;
            _levensteinMatchDistance = levensteinMatchDistance;
        }
Exemple #9
0
        private static void ThreadLoop(object callback)
        {
            Logger.Info("Reading config settings...");
            Logger.Info("Starting New Distance Over Time Adapter for Service Type {0} - DO NOT CLOSE!!", _defaults.Listener);

            BaseCameraListener cameraListenerA = ListenerFactory.GetListener(_defaults, ListenerFactory.PointDefinition.PointA);

            cameraListenerA.Connect();

            BaseCameraListener cameraListenerB = ListenerFactory.GetListener(_defaults, ListenerFactory.PointDefinition.PointB);

            cameraListenerB.Connect();

            List <AtPointModel> pointsA = new List <AtPointModel>();
            List <AtPointModel> pointsB = new List <AtPointModel>();

            ConfigurationDotService configurationDotService = new ConfigurationDotService();
            AtPointService          atPointService          = new AtPointService();
            OverSectionService      overSectionService      = new OverSectionService();

            DateTime timeout = DateTime.Now.AddMinutes(1);

            Logger.Info("Reading config settings.This can take some time as the service connects to the listener...");

            SectionConfigurationModel sectionConfigurationModel = null;
            AtPointModel a = null;
            AtPointModel b = null;

            int retryCounter    = 0;
            int maxRetryCounter = 3;

            while (true)
            {
                if (DateTime.Now > timeout)
                {
                    Logger.Error("Cannot connect to the listener or no data received. Stopping adapter service after timeout of 1 minute.");
                    return;
                }

                try
                {
                    if (cameraListenerA.DataPoints.Count > 0 && cameraListenerB.DataPoints.Count > 0)
                    {
                        if (a == null)
                        {
                            cameraListenerA.DataPoints.TryTake(out a);
                            atPointService.Create(a);
                        }

                        if (b == null)
                        {
                            cameraListenerB.DataPoints.TryTake(out b);
                            atPointService.Create(b);
                        }

                        if (a != null && b != null)
                        {
                            sectionConfigurationModel = configurationDotService.GetSectionConfiguration(a.SectionPointCode, b.SectionPointCode);
                            break;
                        }
                    }
                }
                catch (Exception ex)
                {
                    retryCounter++;
                    Logger.Error(ex);
                }

                if (retryCounter > maxRetryCounter)
                {
                    Logger.Error("After trying {0} times, the service cannot register this adapter - the REST service might be down! Stopping adapter service!", maxRetryCounter);
                    return;
                }
            }

            if (!configurationDotService.RegisterAdapter(sectionConfigurationModel, _defaults.Listener, Helper.HeartbeatSeconds))
            {
                Logger.Error("Cannot register this adapter - there is a similar adapter configured already! Stopping adapter service!");
                return;
            }

            int listenerCounterTimeoutThreshold = Helper.ListenerCounterTimeout;
            int listenerCounterTimeout          = 0;

            retryCounter = 0;

            DateTime?nextHeartBeat = null;

            while (true)
            {
                nextHeartBeat = SendHeartBeat(nextHeartBeat, configurationDotService, sectionConfigurationModel);

                //if (listenerCounterTimeout > listenerCounterTimeoutThreshold)
                //{
                //    Logger.Error("Warning!! After trying {0} times, it seems like the listener is not reading data! Check the Adapters!", listenerCounterTimeoutThreshold);
                //    listenerCounterTimeout = 0;
                //}

                if (retryCounter > maxRetryCounter)
                {
                    Logger.Error("After trying {0} times, the service cannot read / post data - the REST service might be down! Check the Service!", maxRetryCounter);
                    retryCounter = 0;
                }

                try
                {
                    while (cameraListenerA.DataPoints.Count > 0)
                    {
                        AtPointModel m;
                        if (cameraListenerA.DataPoints.TryTake(out m))
                        {
                            atPointService.Create(m);
                            pointsA.Add(m);
                        }
                    }

                    while (cameraListenerB.DataPoints.Count > 0)
                    {
                        AtPointModel m;
                        if (cameraListenerB.DataPoints.TryTake(out m))
                        {
                            atPointService.Create(m);
                            pointsB.Add(m);
                        }
                    }

                    nextHeartBeat = SendHeartBeat(nextHeartBeat, configurationDotService, sectionConfigurationModel);

                    pointsA = pointsA.OrderBy(c => c.EventDateTime).ToList();
                    pointsB = pointsB.OrderBy(c => c.EventDateTime).ToList();

                    if (pointsA.Count == 0 || pointsB.Count == 0)
                    {
                        listenerCounterTimeout++;
                        Thread.Sleep(1000);
                        continue;
                    }

                    listenerCounterTimeout = 0;

                    SectionCalculator sectionCalculator = new SectionCalculator(
                        sectionConfigurationModel.LevenshteinMatchDistance,
                        sectionConfigurationModel.SectionDistanceInMeter,
                        sectionConfigurationModel.SectionDescription,
                        sectionConfigurationModel.SectionCode,
                        pointsA,
                        pointsB);

                    List <SectionCalculationResult> offences = sectionCalculator.Calculate();

                    foreach (SectionCalculationResult sectionCalculationResult in offences)
                    {
                        nextHeartBeat = SendHeartBeat(nextHeartBeat, configurationDotService, sectionConfigurationModel);

                        OverSectionModel model = new OverSectionModel
                        {
                            AtPointA               = sectionCalculationResult.AtPointEnd,
                            AtPointB               = sectionCalculationResult.AtPointEnd,
                            Zone                   = sectionCalculationResult.Zone,
                            Vln                    = sectionCalculationResult.Vln,
                            MachineId              = sectionCalculationResult.MachineId,
                            DateFormat             = sectionCalculationResult.DateFormat,
                            SectionDescription     = sectionCalculationResult.SectionDescription,
                            SectionCode            = sectionCalculationResult.SectionCode,
                            AverageAnprAccuracy    = sectionCalculationResult.AverageAnprAccuracy,
                            AverageSpeed           = sectionCalculationResult.AverageSpeed,
                            GraceSpeed             = sectionCalculationResult.GraceSpeed,
                            SectionDistanceInMeter = sectionCalculationResult.SectionDistanceInMeter,
                            TravelDistance         = sectionCalculationResult.TravelDistance,
                            TripDuration           = sectionCalculationResult.TripDuration,
                            IsOffence              = sectionCalculationResult.IsOffence,
                            FileName               = sectionCalculationResult.FileName,
                            FrameNumber            = sectionCalculationResult.FrameNumber
                        };

                        if (sectionConfigurationModel.CreatePhysicalInfringement)
                        {
                            if (string.IsNullOrEmpty(Helper.PhysicalInfringementPath))
                            {
                                Logger.Error("WARNING!!! The Configuration is setup to create physical infringments but the application config file does not contain a valid path. Please stop this process and update the path!!");
                            }

                            PhysicalInfringement.Create(model, Helper.PhysicalInfringementPath);
                        }

                        string paths = Path.Combine(sectionCalculationResult.AtPointStart.ImagePhysicalFileAndPath, sectionCalculationResult.AtPointStart.ImageName);
                        model.AtPointA.Image = File.ReadAllBytes(paths);

                        string pathe = Path.Combine(sectionCalculationResult.AtPointEnd.ImagePhysicalFileAndPath, sectionCalculationResult.AtPointEnd.ImageName);
                        model.AtPointB.Image = File.ReadAllBytes(pathe);

                        overSectionService.PostData(model);
                        Logger.Info("Added Offence");
                    }
                }
                catch (Exception ex)
                {
                    retryCounter++;
                    Logger.Error(ex);
                }

                Thread.Sleep(500);
            }
        }
Exemple #10
0
        private void PollMock()
        {
            MockConfigurationModel mc = (MockConfigurationModel)Listener.Configuration;

            if (mc.Seed < 1000)
            {
                mc.Seed = 1000;
            }

            Random random = new Random(mc.Seed);

            string[] vlnListLight = { "CA370097", "CA404871", "CA502246", "CA636432", "CL32644" };
            string[] vlnListHeavy = { "BY38GZGP", "CA383630", "CA702912", "CA776761", "CA782572" };

            do
            {
                try
                {
                    AtPointModel model = new AtPointModel
                    {
                        AnprAccuracy                  = 95,
                        Image                         = null,
                        ImagePhysicalFileAndPath      = @"C:\Temp",
                        MachineId                     = "MachineId",
                        PlateImagePhysicalFileAndPath = @"C:\Temp",
                        PointLocation                 = new LocationModel
                        {
                            GpsLatitude  = "",
                            GpsLongitude = ""
                        },
                        SectionPointCode        = mc.LocationCode,
                        SerialNumber            = "SerialNumber",
                        SourceTextLine          = "",
                        VosiReason              = "",
                        SectionPointDescription = ""
                    };

                    if (random.Next(0, 10) % 2 == 0)
                    {
                        model.Classification = new ClassificationZoneModel
                        {
                            Classification = VehicleClassificationEnum.Heavy,
                            Zone           = 80,
                            Grace          = 10
                        };

                        model.Vln       = vlnListHeavy[random.Next(0, 5)];
                        model.ImageName = "Heavy_" + model.Vln + ".jpg";
                        model.Speed     = random.Next(70, 110);
                    }
                    else
                    {
                        model.Classification = new ClassificationZoneModel
                        {
                            Classification = VehicleClassificationEnum.Light,
                            Zone           = 120,
                            Grace          = 10
                        };

                        model.Vln       = vlnListLight[random.Next(0, 5)];
                        model.ImageName = "Light_" + model.Vln + ".jpg";
                        model.Speed     = random.Next(100, 160);
                    }

                    model.PlateImageName = model.Vln + ".jpg";

                    model.EventDateTime = DateTime.Now.AddSeconds(random.Next(mc.TimeOffsetSecondsStart, mc.TimeOffsetSecondsEnd));

                    if (random.Next(0, 10) % 2 == 0)
                    {
                        model.ShotDirection = DirectionEnum.Away;
                    }
                    else
                    {
                        model.ShotDirection = DirectionEnum.Towards;
                    }

                    model.ShotDistance = random.Next(45, 190);

                    model.HashVln = VlnHash.Hash(model.Vln);

                    Add(model);
                }
                catch (Exception ex)
                {
                    Logger.Trace("Poll Error" + ex.Message);
                }
                finally
                {
                    Thread.Sleep(Listener.Configuration.ListenEveryMilliseconds);
                }
            } while (_continiousRead);

            KillThread();
        }