Exemple #1
0
        protected override void OnStart(string[] args)
        {
            Commentary.WriteToFile = true;
            Commentary.Print("Hitory Events Service is Started");
            _locationService = new LocationService(GlobalVariables);
            _eventService    = new EventService(GlobalVariables);
            _imageService    = new ImageService(GlobalVariables);
            if (Convert.ToBoolean(ConfigurationManager.AppSettings["SeedData"]))
            {
                Database.SetInitializer(new MigrateDatabaseToLatestVersion <PredixContext, PredixContextInitializer>());
            }
            _schedular = new Timer(SchedularCallback);
            //Get the Interval in Minutes from AppSettings.
            int intervalMinutes = Convert.ToInt32(ConfigurationManager.AppSettings["IntervalMinutes"]);
            var scheduledTime   = DateTime.Now.AddMinutes(intervalMinutes);

            if (DateTime.Now > scheduledTime)
            {
                //If Scheduled Time is passed set Schedule for the next Interval.
                scheduledTime = scheduledTime.AddMinutes(intervalMinutes);
            }
            TimeSpan timeSpan = scheduledTime.Subtract(DateTime.Now);
            string   schedule =
                $"{timeSpan.Days} day(s) {timeSpan.Hours} hour(s) {timeSpan.Minutes} minute(s) {timeSpan.Seconds} seconds(s)";

            Commentary.Print("Simple Service scheduled to run after: " + schedule + " {0}");
            //Get the difference in Minutes between the Scheduled and Current Time.
            int dueTime = Convert.ToInt32(timeSpan.TotalMilliseconds);

            //Change the Timer's Due Time.
            _schedular.Change(dueTime, Timeout.Infinite);
            //Task.Run(() => GetHistory());
        }
Exemple #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);
        }
Exemple #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();
            }
        }
Exemple #4
0
        static void Main(string[] args)
        {
            Options options = new Options();
            var     result  = Parser.Default.ParseArguments <Options>(args);

            switch (result.Tag)
            {
            case ParserResultType.Parsed:
                var parsed = (Parsed <Options>)result;
                options = parsed.Value;
                Commentary.Print(
                    $"\nRefresh Location = {options.RefreshLocations}\nIgnore Regulation Check = {options.IgnoreRegulationCheck}\nSave Events = {options.SaveEvents}\nSave Images= {options.SaveImages}\nMark All As Violations= {options.MarkAllAsViolations}");
                break;

            case ParserResultType.NotParsed:
                var notParsed = (NotParsed <Options>)result;
                var errors    = notParsed.Errors;
                foreach (var error in errors)
                {
                    Commentary.Print($"{error}");
                }
                return;
            }

            Init();
            // History();
            var             locationType = "PARKING_ZONE";
            int             pagesize     = 50;
            List <Boundary> boundaries   = _locationService.GetBoundaries();

            foreach (var boundary in boundaries)
            {
                Commentary.Print($"BBOX: {boundary.Range}");
                Commentary.Print($"Location Type: {locationType}");
                if (options.RefreshLocations)
                {
                    Commentary.Print($"Calling Get All Locations by BBOX & Location Type");
                    var locations = _locationService.All(boundary.Range, locationType, pagesize);
                    Commentary.Print($"Total Locations: {locations.Count}");

                    _locationService.Details(locations.Select(x => x.LocationUid).Distinct().ToList());
                }

                _eventService.GetByBoundaryAsync(boundary.Range, "PKIN", "PKOUT", _imageService, options,
                                                 new Customer()
                {
                    Id = boundary.CustomerId, TimezoneId = "Eastern Standard Time"
                });
            }

            Commentary.Print($"Completed. Please enter a key to exit");
        }
Exemple #5
0
 private async Task SaveAsync(Media media)
 {
     if (media == null)
     {
         return;
     }
     using (PredixContext context = new PredixContext())
     {
         Commentary.Print($"Saving Media Data");
         context.Medias.AddOrUpdate(x => x.ImageAssetUid, media);
         await context.SaveChangesAsync();
     }
 }
Exemple #6
0
 private void Save(Media media)
 {
     if (media == null)
     {
         return;
     }
     using (PredixContext context = new PredixContext())
     {
         Commentary.Print($"Saving Media Data", true);
         context.Medias.Add(media);
         //context.Medias.AddOrUpdate(x => x.ImageAssetUid, media);
         context.SaveChanges();
     }
 }
Exemple #7
0
 private void Save(Image image)
 {
     if (image == null)
     {
         return;
     }
     using (PredixContext context = new PredixContext())
     {
         Commentary.Print($"Saving Base64", true);
         context.ImageContents.AddRange(image.Entry.Contents);
         context.Images.Add(image);
         //context.Images.AddOrUpdate(x => x.ImageAssetUid, image);
         context.SaveChanges();
     }
 }
Exemple #8
0
        protected override void OnStart(string[] args)
        {
            Commentary.Print("RTE Service is Started");

            Commentary.WriteToFile = true;
            _locationService       = new LocationService(GlobalVariables);
            _eventService          = new EventService(GlobalVariables);
            _imageService          = new ImageService(GlobalVariables);
            if (Convert.ToBoolean(ConfigurationManager.AppSettings["SeedData"]))
            {
                Database.SetInitializer(new MigrateDatabaseToLatestVersion <PredixContext, PredixContextInitializer>());
            }

            Task.Run(() => OpenSocket());
        }
Exemple #9
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();
            }
        }
Exemple #10
0
        private void OpenSocket()
        {
            Options options = new Options
            {
                IgnoreRegulationCheck = Convert.ToBoolean(ConfigurationManager.AppSettings["IgnoreRegulationCheck"]),
                MarkAllAsViolations   = Convert.ToBoolean(ConfigurationManager.AppSettings["MarkAllAsViolations"]),
                RefreshLocations      = Convert.ToBoolean(ConfigurationManager.AppSettings["RefreshLocations"]),
                SaveEvents            = Convert.ToBoolean(ConfigurationManager.AppSettings["SaveEvents"]),
                SaveImages            = Convert.ToBoolean(ConfigurationManager.AppSettings["SaveImages"]),
                Debug = Convert.ToBoolean(ConfigurationManager.AppSettings["Debug"])
            };

            Commentary.Print(
                $"\nRefresh Location = {options.RefreshLocations}");
            Commentary.Print(
                $"\nIgnore Regulation Check = {options.IgnoreRegulationCheck}");
            Commentary.Print(
                $"\nSave Events = {options.SaveEvents}");
            Commentary.Print(
                $"\nSave Images= {options.SaveImages}");
            Commentary.Print(
                $"\nMark All As Violations= {options.MarkAllAsViolations}");
            var             locationType = "PARKING_ZONE";
            int             pagesize     = 50;
            List <Boundary> boundaries   = _locationService.GetBoundaries();

            foreach (var boundary in boundaries)
            {
                Commentary.Print($"BBOX: {boundary.Range}");
                Commentary.Print($"Location Type: {locationType}");
                if (options.RefreshLocations)
                {
                    Commentary.Print($"Calling Get All Locations by BBOX & Location Type");
                    var locations = _locationService.All(boundary.Range, locationType, pagesize);
                    Commentary.Print($"Total Locations: {locations.Count}");

                    _locationService.Details(locations.Select(x => x.LocationUid).Distinct().ToList());
                }

                _eventService.GetByBoundaryAsync(boundary.Range, "PKIN", "PKOUT", _imageService, options, new Customer {
                    Id = boundary.CustomerId, TimezoneId = "Eastern Standard Time"
                });
            }

            Commentary.Print($"Completed. Please enter a key to exit");
        }
Exemple #11
0
        public async Task <string> GetFile(string url, Dictionary <string, string> additionalHeaders)
        {
            Commentary.Print($"Fething Image Base64", true);
            Commentary.Print($"Image URL: {url}", true);
            _securityService.SetClientToken().Wait();
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls |
                                                   SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
            using (HttpClient httpClient = new HttpClient(new LoggingHandler(new HttpClientHandler())))
            {
                httpClient.DefaultRequestHeaders.Authorization =
                    new AuthenticationHeaderValue("Bearer", Endpoint.ClientAccessToken);
                foreach (var additionalHeader in additionalHeaders)
                {
                    httpClient.DefaultRequestHeaders.Add(additionalHeader.Key, additionalHeader.Value);
                }
                //using (MemoryStream memoryStream = new MemoryStream())
                //{
                //    using (HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK))
                //    {
                //        result.Content = new ByteArrayContent(memoryStream.ToArray());
                //        result.Content.Headers.ContentType =
                //            new MediaTypeHeaderValue($"image/jpg");
                //        var imageUrl = $"data:image/jpg;base64," +
                //                       Convert.ToBase64String(memoryStream.ToArray(), 0, memoryStream.ToArray().Length);
                //        return imageUrl;
                //    }
                //}

                using (HttpResponseMessage httpResponseMessage = await httpClient.GetAsync(url))
                {
                    using (HttpContent httpContent = httpResponseMessage.Content)
                    {
                        var result = await httpContent.ReadAsByteArrayAsync();

                        var base64 = $"data:image/jpg;base64," +
                                     Convert.ToBase64String(result);
                        return(base64);
                    }
                }
            }
        }
Exemple #12
0
        private void GetHistory()
        {
            try
            {
                IPredixWebSocketClient predixWebSocketClient = new PredixWebSocketClient();
                var locations = _locationService.GetLocationsUids();
                Commentary.Print($"Total Locations: {locations.Count}");
                Options options = new Options
                {
                    IgnoreRegulationCheck = Convert.ToBoolean(ConfigurationManager.AppSettings["IgnoreRegulationCheck"]),
                    MarkAllAsViolations   = Convert.ToBoolean(ConfigurationManager.AppSettings["MarkAllAsViolations"]),
                    RefreshLocations      = Convert.ToBoolean(ConfigurationManager.AppSettings["RefreshLocations"]),
                    SaveEvents            = Convert.ToBoolean(ConfigurationManager.AppSettings["SaveEvents"]),
                    SaveImages            = Convert.ToBoolean(ConfigurationManager.AppSettings["SaveImages"]),
                    Debug = Convert.ToBoolean(ConfigurationManager.AppSettings["Debug"])
                };

                foreach (var location in locations)
                {
                    var inEvents  = _eventService.Get(location, "PKIN", DateTime.UtcNow.AddMinutes(-2).ToEpoch().ToString(), DateTime.UtcNow.AddSeconds(30).ToEpoch().ToString());
                    var outEvents = _eventService.Get(location, "PKOUT", DateTime.UtcNow.AddMinutes(-2).ToEpoch().ToString(), DateTime.UtcNow.AddSeconds(30).ToEpoch().ToString());
                    Commentary.Print($"location: {location}, In Events: {inEvents.Count}, Out Events: {outEvents.Count}");
                    inEvents.AddRange(outEvents);
                    foreach (var evnt in inEvents)
                    {
                        predixWebSocketClient.ProcessEvent(_imageService, options,
                                                           new Customer()
                        {
                            Id = 4120, TimezoneId = "Eastern Standard Time"
                        },
                                                           evnt);
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                Commentary.Print(e.ToString());
            }
        }
Exemple #13
0
        private Media GetMedia(string imageAssetUid, string timestamp)
        {
            Commentary.Print($"Fething Media Data", true);
            Dictionary <string, string> additionalHeaders =
                new Dictionary <string, string> {
                { "predix-zone-id", Endpoint.PredixZoneIdForImage }
            };
            var response = _predixHttpClient.GetAllAsync(Endpoint.MediaOnDemand
                                                         .Replace("{ps_asset}", imageAssetUid)
                                                         .Replace("{timestamp}", timestamp), additionalHeaders);

            if (string.IsNullOrWhiteSpace(response.Result))
            {
                return(null);
            }
            var jsonRespone = JsonConvert.DeserializeObject <JObject>(response.Result);
            var media       = jsonRespone != null
                ? (jsonRespone).ToObject <Media>()
                : new Media();

            media.ImageAssetUid = imageAssetUid;
            Save(media);
            return(media);
        }
Exemple #14
0
        public void OpenAsync(string url, string bodyMessage,
                              Dictionary <string, string> additionalHeaders, IImage imageService, Options options, Customer customer)
        {
            _securityService.SetClientToken().Wait();
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls |
                                                   SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

            var cancellationTokenSource = new CancellationTokenSource(new TimeSpan(1, 1, 0, 0));

            using (ClientWebSocket clientWebSocket = new ClientWebSocket())
            {
                Uri serverUri = new Uri(url);
                clientWebSocket.Options.SetRequestHeader("Authorization", $"Bearer {Endpoint.ClientAccessToken}");
                foreach (var additionalHeader in additionalHeaders)
                {
                    clientWebSocket.Options.SetRequestHeader(additionalHeader.Key, additionalHeader.Value);
                }

                try
                {
                    clientWebSocket.ConnectAsync(serverUri, cancellationTokenSource.Token)
                    .Wait(cancellationTokenSource.Token);
                }
                catch (Exception exception)
                {
                    Commentary.Print(exception.ToString());
                }

                while (clientWebSocket.State == WebSocketState.Open)
                {
                    Commentary.Print("Opened Socket Connection");
                    string response = null;
                    try
                    {
                        ArraySegment <byte> bytesToSend = new ArraySegment <byte>(Encoding.UTF8.GetBytes(bodyMessage));
                        clientWebSocket.SendAsync(bytesToSend, WebSocketMessageType.Text, true,
                                                  CancellationToken.None).Wait(cancellationTokenSource.Token);
                        byte[] incomingData           = new byte[1024];
                        WebSocketReceiveResult result =
                            clientWebSocket.ReceiveAsync(new ArraySegment <byte>(incomingData), CancellationToken.None)
                            .Result;
                        if (result.CloseStatus.HasValue)
                        {
                            Commentary.Print($"Closed; Status: {result.CloseStatus}, {result.CloseStatusDescription}");
                        }
                        else
                        {
                            response = Encoding.UTF8.GetString(incomingData, 0, result.Count);
                            //Console.WriteLine("Received message: " + response);
                            Commentary.Print("Received Message");
                        }
                    }
                    catch (Exception exception)
                    {
                        Commentary.Print(exception.ToString());
                        //Commentary.Print($"WebSocket State:{clientWebSocket.State}");
                        continue;
                    }

                    if (string.IsNullOrWhiteSpace(response))
                    {
                        continue;
                    }
                    Task.Run(() =>
                             ProcessEvent(imageService, options, customer, response),
                             cancellationTokenSource.Token).ConfigureAwait(false);
                    //Task.Factory.StartNew(() => ProcessEvent(imageService, options, customerId, response), cancellationTokenSource.Token);
                }

                Commentary.Print($"WebSocket State:{clientWebSocket.State}");
            }
        }
Exemple #15
0
 protected override void OnStop()
 {
     Commentary.Print("RTA Service is Stoped");
 }
Exemple #16
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);
            }
        }
Exemple #17
0
 private void SchedularCallback(object e)
 {
     Commentary.Print("Simple Service Log: {0}");
     this.GetHistory();
 }
Exemple #18
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);
        }
Exemple #19
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;
        }