Beispiel #1
0
 private static void ViolationPercentage(List <string> latLongs, ParkingRegulation regulation,
                                         ParkingEvent parkingEvent)
 {
     foreach (var latLong in latLongs)
     {
         if (IsPointInPolygon4(new List <PointF>
         {
             new PointF(
                 float.Parse(regulation.Coodrinate1.Split(':')[0]),
                 float.Parse(regulation.Coodrinate1.Split(':')[1])),
             new PointF(
                 float.Parse(regulation.Coodrinate2.Split(':')[0]),
                 float.Parse(regulation.Coodrinate2.Split(':')[1])),
             new PointF(
                 float.Parse(regulation.Coodrinate3.Split(':')[0]),
                 float.Parse(regulation.Coodrinate3.Split(':')[1])),
             new PointF(
                 float.Parse(regulation.Coodrinate4.Split(':')[0]),
                 float.Parse(regulation.Coodrinate4.Split(':')[1]))
         }.ToArray(),
                               new PointF(float.Parse(latLong.Split(':')[0]),
                                          float.Parse(latLong.Split(':')[1]))))
         {
             parkingEvent.MatchRate += 25;
         }
     }
 }
Beispiel #2
0
        private static bool IsStreetSweeping(ParkingRegulation regulation, ParkingEvent parkingEvent,
                                             GeViolation geViolation, PredixContext context, Customer customer)
        {
            bool isVoilation = false;

            if (parkingEvent.EventType.Equals("PKOUT"))
            {
                using (var innerContext = new PredixContext())
                {
                    var inEvent = innerContext.GeViolations.FirstOrDefault(x =>
                                                                           x.ObjectUid == parkingEvent.Properties.ObjectUid &&
                                                                           x.LocationUid == parkingEvent.LocationUid);
                    if (inEvent?.ParkinTime != null)
                    {
                        inEvent.ParkoutTime      = parkingEvent.Timestamp.ToUtcDateTimeOrNull().ToTimeZone(customer.TimezoneId);
                        inEvent.EventOutDateTime =
                            parkingEvent.Timestamp.ToUtcDateTimeOrNull().ToTimeZone(customer.TimezoneId);
                        inEvent.ViolationDuration = (long)parkingEvent.Timestamp.ToUtcDateTimeOrNull().ToTimeZone(customer.TimezoneId)
                                                    .Subtract(inEvent.ParkinTime.Value).TotalMinutes;
                        inEvent.StreetSweeping   = true;
                        inEvent.ModifiedDateTime = parkingEvent.Timestamp.ToUtcDateTimeOrNull().ToTimeZone(customer.TimezoneId);
                        inEvent.IsException      = true;
                        inEvent.UserAction       = "Missed_Violation";
                        innerContext.SaveChanges();
                        return(true);
                    }
                }
                return(false);
            }
            if (parkingEvent.Timestamp.ToUtcDateTimeOrNull().ToTimeZone(customer.TimezoneId).TimeOfDay >= regulation.StartTime &&
                parkingEvent.Timestamp.ToUtcDateTimeOrNull().ToTimeZone(customer.TimezoneId).TimeOfDay <= regulation.EndTime)
            {
                Commentary.Print("*** StreetWeeping Violation");

                isVoilation = true;
                geViolation.StreetSweeping = true;
                geViolation.ObjectUid      = parkingEvent.Properties.ObjectUid;
                geViolation.LocationUid    = parkingEvent.LocationUid;
                if (parkingEvent.EventType.Equals("PKIN"))
                {
                    geViolation.EventInDateTime =
                        parkingEvent.Timestamp.ToUtcDateTimeOrNull().ToTimeZone(customer.TimezoneId);
                    geViolation.ParkinTime = parkingEvent.Timestamp.ToUtcDateTimeOrNull().ToTimeZone(customer.TimezoneId);
                }

                if (parkingEvent.EventType.Equals("PKOUT"))
                {
                    geViolation.EventOutDateTime =
                        parkingEvent.Timestamp.ToUtcDateTimeOrNull().ToTimeZone(customer.TimezoneId);
                    geViolation.ParkoutTime = parkingEvent.Timestamp.ToUtcDateTimeOrNull().ToTimeZone(customer.TimezoneId);
                }

                geViolation.RegulationId  = regulation.RegualationId;
                geViolation.ViolationType = regulation.ViolationType;

                context.GeViolations.Add(geViolation);
            }

            return(isVoilation);
        }
Beispiel #3
0
        private static void ForceMarkViolation(ParkingEvent parkingEvent, Customer customer)
        {
            Commentary.Print("Force Mark Violation");
            if (parkingEvent.EventType.Equals("PKOUT"))
            {
                using (var innerContext = new PredixContext())
                {
                    var inEvent = innerContext.GeViolations.FirstOrDefault(x =>
                                                                           x.ObjectUid == parkingEvent.Properties.ObjectUid &&
                                                                           x.LocationUid == parkingEvent.LocationUid);
                    if (inEvent?.ParkinTime != null)
                    {
                        inEvent.ParkoutTime      = parkingEvent.Timestamp.ToUtcDateTimeOrNull().ToTimeZone(customer.TimezoneId);
                        inEvent.EventOutDateTime =
                            parkingEvent.Timestamp.ToUtcDateTimeOrNull().ToTimeZone(customer.TimezoneId);
                        inEvent.ViolationDuration = (long)parkingEvent.Timestamp.ToUtcDateTimeOrNull().ToTimeZone(customer.TimezoneId)
                                                    .Subtract(inEvent.ParkinTime.Value).TotalMinutes;
                        //inEvent.NoParking = true;
                        inEvent.ModifiedDateTime = parkingEvent.Timestamp.ToUtcDateTimeOrNull().ToTimeZone(customer.TimezoneId);
                        inEvent.IsException      = true;
                        inEvent.UserAction       = "Missed_Violation";
                        innerContext.SaveChanges();
                    }
                }

                return;
            }

            GeViolation geViolation = new GeViolation
            {
                NoParking   = true,
                ObjectUid   = parkingEvent.Properties.ObjectUid,
                LocationUid = parkingEvent.LocationUid
            };

            if (parkingEvent.EventType.Equals("PKIN"))
            {
                geViolation.EventInDateTime = parkingEvent.Timestamp.ToUtcDateTimeOrNull().ToTimeZone(customer.TimezoneId);
                geViolation.ParkinTime      = parkingEvent.Timestamp.ToUtcDateTimeOrNull().ToTimeZone(customer.TimezoneId);
            }

            if (parkingEvent.EventType.Equals("PKOUT"))
            {
                geViolation.EventOutDateTime = parkingEvent.Timestamp.ToUtcDateTimeOrNull().ToTimeZone(customer.TimezoneId);
                geViolation.ParkoutTime      = parkingEvent.Timestamp.ToUtcDateTimeOrNull().ToTimeZone(customer.TimezoneId);
            }

            geViolation.RegulationId  = 81;
            geViolation.ViolationType = ViolationType.FireHydrant;
            using (var context = new PredixContext())
            {
                context.GeViolations.Add(geViolation);
                context.SaveChanges();
            }
        }
Beispiel #4
0
        //private static DateTime? EpochToDateTime(string epoch)
        //{
        //    if (string.IsNullOrWhiteSpace(epoch))
        //        return null;
        //    return DateTimeOffset.FromUnixTimeMilliseconds(Convert.ToInt64(epoch)).DateTime;
        //    //System.DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
        //    //dtDateTime = dtDateTime.AddSeconds(Convert.ToInt64(epoch)).ToLocalTime();
        //    //return dtDateTime;
        //}

        private void Save(ParkingEvent parkingEvent, Customer customer)
        {
            if (parkingEvent == null)
            {
                return;
            }
            using (PredixContext context = new PredixContext())
            {
                Commentary.Print("Saving Event Data", true);
                parkingEvent.CreatedDate = parkingEvent.Timestamp.ToUtcDateTimeOrNull().ToTimeZone(customer.TimezoneId);
                context.ParkingEvents.Add(parkingEvent);
                //context.ParkingEvents.AddOrUpdate(x => new { x.LocationUid, x.EventType }, parkingEvent);
                context.SaveChanges();
            }
        }
Beispiel #5
0
        public void GetByLocation(string locationUid, string eventType, IImage imageService, Options options, Customer customer)
        {
            ParkingEvent parkingEvent = null;
            Dictionary <string, string> additionalHeaders =
                new Dictionary <string, string> {
                { "predix-zone-id", Endpoint.PredixZoneIdForParking }
            };
            string bodyMessage = $"{{\"locationUid\":\"{locationUid}\",\"eventTypes\":[\"{eventType}\"]}}";

            _predixWebSocketClient.OpenAsync(Endpoint.WebSocketUrlForEvents, bodyMessage, additionalHeaders, imageService, options, customer: customer);
            //if (!string.IsNullOrWhiteSpace(response.Result))
            //{
            //    var jsonRespone = JsonConvert.DeserializeObject<JObject>(response.Result);
            //    parkingEvent = jsonRespone != null
            //        //? ((JArray)jsonRespone["content"]).ToObject<ParkingEvent>()
            //        ? (jsonRespone).ToObject<ParkingEvent>()
            //        : new ParkingEvent();
            //}
            //await SaveAsync(parkingEvent);
            //return parkingEvent;
        }
Beispiel #6
0
        public void MediaOnDemand(ParkingEvent parkingEvent, string imageAssetUid, string timestamp, Customer customer)
        {
            var   media = GetMedia(imageAssetUid, timestamp);
            Image image = new Image {
                PropertyId = parkingEvent.Properties.Id
            };
            var      i         = 1;
            TimeSpan startTime = DateTime.Now.TimeOfDay;

            while (i < 6 && (image?.Entry == null || !image.Entry.Contents.Any(x => x.Status.Equals("SUCCESS", StringComparison.OrdinalIgnoreCase))))
            {
                i++;
                if (!string.IsNullOrWhiteSpace(media?.PollUrl))
                {
                    Dictionary <string, string> additionalHeaders =
                        new Dictionary <string, string> {
                        { "predix-zone-id", Endpoint.PredixZoneIdForImage }
                    };
                    var response = _predixHttpClient.GetAllAsync(media.PollUrl, additionalHeaders);
                    if (!string.IsNullOrWhiteSpace(response.Result))
                    {
                        try
                        {
                            var jsonRespone = JsonConvert.DeserializeObject <JObject>(response.Result);
                            image = jsonRespone != null
                                ? (jsonRespone).ToObject <Image>()
                                : new Image();
                        }
                        catch (Exception e)
                        {
                            Commentary.Print(e.Message);
                            Commentary.Print(response.Result);
                        }
                    }
                }
                if (image?.Entry == null ||
                    !image.Entry.Contents.Any(x => x.Status.Equals("SUCCESS", StringComparison.OrdinalIgnoreCase)))
                {
                    Commentary.Print(
                        $"Polling for Media Data {i} time after {DateTime.Now.TimeOfDay.Subtract(startTime).TotalMinutes} minutes: {media.PollUrl}",
                        true);
                    //Thread.Sleep(1000 * 60);
                    if (i < 6)
                    {
                        Task.Delay(1000 * 60).Wait(1000 * 60);
                    }

                    continue;
                }
                var imageBinary = (from content in image.Entry.Contents
                                   let additionalHeaders = new Dictionary <string, string> {
                    { "predix-zone-id", Endpoint.PredixZoneIdForImage }
                }
                                   select _predixHttpClient.GetFile(content.Url, additionalHeaders)
                                   into response
                                   select response.Result).FirstOrDefault();
                image.Base64 = imageBinary;
                image        = MarkPixelCoordinates(parkingEvent: parkingEvent, image: image, customer: customer);
            }
            if (image == null)
            {
                return;
            }
            image.PropertyId    = parkingEvent.Properties.Id;
            image.ImageAssetUid = imageAssetUid;

            image.OriginalBase64 = null;
            image.Base64         = null;

            Save(image);
            //return image.Base64;
        }
Beispiel #7
0
        public Image MarkPixelCoordinates(ParkingEvent parkingEvent, Image image, Customer customer)
        {
            try
            {
                image.OriginalBase64 = image.Base64;
                if (!string.IsNullOrWhiteSpace(parkingEvent.Properties.PixelCoordinates))
                {
                    //IsBase64(image.Base64);
                    string selectedBase64 = image.Base64.Split(',').ToList <string>()[1];
                    var    bitMapImage    = Base64StringToBitmap(selectedBase64.Trim());
                    var    coordinates    = parkingEvent.Properties.PixelCoordinates.Split(',').ToList();
                    using (var graphics = Graphics.FromImage(bitMapImage))
                    {
                        Pen yellowPen = new Pen(Color.Yellow, 3);
                        try
                        {
                            var a1 = coordinates[0].Split(':').Select(float.Parse).ToList()[0];
                            var a2 = coordinates[0].Split(':').Select(float.Parse).ToList()[1];
                            var b1 = coordinates[1].Split(':').Select(float.Parse).ToList()[0];
                            var b2 = coordinates[1].Split(':').Select(float.Parse).ToList()[1];
                            var c1 = coordinates[2].Split(':').Select(float.Parse).ToList()[0];
                            var c2 = coordinates[2].Split(':').Select(float.Parse).ToList()[1];
                            var d1 = coordinates[3].Split(':').Select(float.Parse).ToList()[0];
                            var d2 = coordinates[3].Split(':').Select(float.Parse).ToList()[1];
                            graphics.DrawPolygon(yellowPen, new PointF[]
                            {
                                new PointF(a1, a2),
                                new PointF(b1, b2),
                                new PointF(c1, c2),
                                new PointF(d1, d2)
                            });
                            // Create font and brush.
                            Font       drawFont  = new Font("Arial", 26);
                            SolidBrush drawBrush = new SolidBrush(Color.White);

                            // Create point for upper-left corner of drawing.
                            PointF drawPoint = new PointF(150.0F, 110.0F);
                            //StringFormat stringFormat = new StringFormat
                            //{
                            //    LineAlignment = StringAlignment.Center,
                            //    Alignment = StringAlignment.Center
                            //};
                            //graphics.DrawString($"Event Id: {parkingEvent.Id}, Asset Uid: {parkingEvent.AssetUid}, Pixel Coordinates {parkingEvent.Properties.PixelCoordinates}",
                            //    drawFont, drawBrush, drawPoint);
                            List <string> writings = new List <string>
                            {
                                $"Event Id: {parkingEvent.Id}",
                                $"In or Out: {parkingEvent.EventType}",
                                $"Local Time: {parkingEvent.Timestamp.ToUtcDateTimeOrNull().ToTimeZone(customer.TimezoneId)} {parkingEvent.EventTime?.ToString("F")}"
                                //$"Location Uid: {parkingEvent.LocationUid}",
                                //$"Asset Uid: {parkingEvent.AssetUid}",
                                //$"Pixel Coordinates {parkingEvent.Properties.PixelCoordinates}"
                            };
                            foreach (var writing in writings)
                            {
                                drawPoint.Y = drawPoint.Y + 40;
                                graphics.DrawString(writing,
                                                    drawFont, drawBrush, drawPoint);
                            }
                        }
                        catch (Exception e)
                        {
                            Commentary.Print(
                                $"Failed to mark pixel coordinates {parkingEvent.Properties.PixelCoordinates} PropertyId {parkingEvent.Properties.Id}");
                            Commentary.Print(e.Message);
                        }
                    }

                    using (MemoryStream memoryStream = new MemoryStream())
                    {
                        string randomTempFileName = Path.GetTempPath();
                        if (!Directory.Exists($"{randomTempFileName}CivicSmart\\{DateTime.Now:yyyy-MM-dd}"))
                        {
                            Directory.CreateDirectory($"{randomTempFileName}CivicSmart\\{DateTime.Now:yyyy-MM-dd}");
                        }

                        var fileName =
                            $"{randomTempFileName}CivicSmart\\{DateTime.Now:yyyy-MM-dd}\\geviolation{DateTime.Now.Ticks}.jpg";
                        using (FileStream fs = new FileStream(fileName,
                                                              FileMode.Create, FileAccess.ReadWrite))
                        {
                            Commentary.Print($"Image: {fileName}", true);
                            bitMapImage.Save(memoryStream, ImageFormat.Jpeg);
                            byte[] bytes = memoryStream.ToArray();
                            fs.Write(bytes, 0, bytes.Length);
                            image.Base64 = image.Base64.Split(',').ToList <string>()[0] + "," +
                                           Convert.ToBase64String(bytes);
                            image.ImagePath = fileName.Replace($"{randomTempFileName}CivicSmart", "");
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Commentary.Print(
                    $"Failed to convert base64 to Image {image.Base64} PropertyId {parkingEvent.Properties.Id}");
                Commentary.Print(e.Message);
                return(image);
            }

            return(image);
        }
Beispiel #8
0
        public bool ProcessEvent(IImage imageService, Options options, Customer customer, ParkingEvent parkingEvent)
        {
            try
            {
                Commentary.Print($"Location ID :{parkingEvent.LocationUid}");
                parkingEvent.CustomerId = customer.Id;
                if (parkingEvent.Properties == null)
                {
                    parkingEvent.Properties = new ParkingEventProperties
                    {
                        CreatedDate  = parkingEvent.Timestamp.ToUtcDateTimeOrNull().ToTimeZone(customer.TimezoneId),
                        ModifiedDate = parkingEvent.Timestamp.ToUtcDateTimeOrNull().ToTimeZone(customer.TimezoneId)
                    }
                }
                ;
                parkingEvent.Properties.LocationUid = parkingEvent.LocationUid;


                var isVoilation = false;
                using (var context = new PredixContext())
                {
                    var anyRecord = context.ParkingEvents.Any(x => x.LocationUid == parkingEvent.LocationUid &&
                                                              x.EventType == parkingEvent.EventType &&
                                                              x.Properties.ObjectUid == parkingEvent.Properties.ObjectUid &&
                                                              x.Properties.ImageAssetUid == parkingEvent.Properties.ImageAssetUid);
                    if (anyRecord)
                    {
                        return(false);
                    }

                    var nodeMasterRegulations =
                        context.NodeMasterRegulations.Join(context.ParkingRegulations,
                                                           node => node.RegulationId,
                                                           regulation => regulation.RegualationId,
                                                           (node, regulation) => new { Node = node, Regulation = regulation })
                        .Where(x => x.Regulation.IsActive && x.Node.LocationUid == parkingEvent.LocationUid)
                        .Select(x => x.Regulation).ToList();

                    //var nodeMasterRegulation =
                    //    nodeMasterRegulations.Where(x => x.LocationUid == parkingEvent.LocationUid)
                    //        .ToList();
                    if (nodeMasterRegulations.Any())
                    {
                        var latLongs           = parkingEvent.Properties.GeoCoordinates.Split(',').ToList();
                        var parkingRegulations = new List <ParkingRegulation>();
                        foreach (var regulation in nodeMasterRegulations)
                        {
                            ViolationPercentage(latLongs, regulation, parkingEvent);
                            if (parkingEvent.MatchRate > 0)
                            {
                                parkingRegulations.Add(regulation);
                            }
                            Commentary.Print(
                                $"Regulation Id: {regulation.RegualationId}, Location Uid: {parkingEvent.LocationUid}, Asset Uid: {parkingEvent.AssetUid}, Match Rate {parkingEvent.MatchRate}",
                                true);
                        }

                        foreach (var regulation in parkingRegulations)
                        {
                            Commentary.Print(
                                $"Location Uid: {parkingEvent.LocationUid}, Asset Uid: {parkingEvent.AssetUid},parkingEvent.Timestamp.ToUtcDateTimeOrNull().DayOfWeek:{parkingEvent.Timestamp.ToUtcDateTimeOrNull().ToTimeZone(customer.TimezoneId).DayOfWeek}, ViolationType: {regulation.ViolationType}",
                                true);
                            if (regulation.DayOfWeek.Split('|').Select(x => x.ToUpper())
                                .Contains(parkingEvent.Timestamp.ToUtcDateTimeOrNull().ToTimeZone(customer.TimezoneId).DayOfWeek.ToString()
                                          .Substring(0, 3).ToUpper()))
                            {
                                GeViolation geViolation = new GeViolation();

                                switch (regulation.ViolationType)
                                {
                                case ViolationType.NoParking:
                                    Commentary.Print(
                                        $"Location Uid: {parkingEvent.LocationUid}, Asset Uid: {parkingEvent.AssetUid}, Checking No Parking",
                                        true);
                                    isVoilation = NoParkingCheck(regulation, parkingEvent, geViolation, context,
                                                                 customer);
                                    break;

                                case ViolationType.StreetSweeping:
                                    Commentary.Print(
                                        $"Location Uid: {parkingEvent.LocationUid}, Asset Uid: {parkingEvent.AssetUid}, Checking Street Sweeping",
                                        true);
                                    isVoilation = IsStreetSweeping(regulation, parkingEvent, geViolation, context,
                                                                   customer);
                                    break;

                                case ViolationType.TimeLimitParking:
                                    Commentary.Print(
                                        $"Location Uid: {parkingEvent.LocationUid}, Asset Uid: {parkingEvent.AssetUid}, Checking Time Limit",
                                        true);
                                    isVoilation = IsTimeLimitExceed(regulation, parkingEvent, geViolation, context,
                                                                    customer);
                                    break;

                                case ViolationType.ReservedParking:
                                    //This is out of scope for now, so we ae skipping this logic
                                    break;

                                case ViolationType.FireHydrant:
                                    Commentary.Print(
                                        $"Location Uid: {parkingEvent.LocationUid}, Asset Uid: {parkingEvent.AssetUid}, Fire Hydrant",
                                        true);
                                    isVoilation = IsFireHydrant(parkingEvent, geViolation, regulation, context,
                                                                customer);
                                    break;
                                }

                                Commentary.Print(
                                    $"Location Uid: {parkingEvent.LocationUid}, Asset Uid: {parkingEvent.AssetUid}, Is Violation: {isVoilation}",
                                    true);
                            }

                            if (isVoilation)
                            {
                                break;
                            }
                        }
                    }

                    context.SaveChanges();
                }

                if (!isVoilation)
                {
                    return(true);
                }
                Save(parkingEvent, customer);
                imageService.MediaOnDemand(parkingEvent, parkingEvent.Properties.ImageAssetUid,
                                           parkingEvent.Timestamp, customer);
                return(false);
            }
            catch (Exception e)
            {
                Commentary.Print("******************************************");
                Commentary.Print(e.ToString());
                return(false);
            }
        }