private void MaintainGpsLocation()
        {
            if (IsMaintainGpsLocationRunning)
            {
                return;
            }
            GPSHelper gps          = new GPSHelper();
            var       lastLocation = new GeoCoordinate(UserViewModel.Location.Latitude, UserViewModel.Location.Longitude);

            TaskEx.Run(async() =>
            {
                IsMaintainGpsLocationRunning = true;
                while (UserViewModel.AllowGPS)
                {
                    var location = await gps.GetPositionAsync();
                    if (location != null && !location.IsUnknown)
                    {
                        Deployment.Current.Dispatcher.BeginInvoke(() =>
                        {
                            UserViewModel.Location.Latitude   = location.Latitude;
                            UserViewModel.Location.Longitude  = location.Longitude;
                            UserViewModel.Location.IsGeoCoded = false;
                            UserViewModel.Location.Timestamp  = DateTime.Now.Ticks;
                            if (location.GetDistanceTo(lastLocation) > 300)
                            {
                                lastLocation = new GeoCoordinate(UserViewModel.Location.Latitude, UserViewModel.Location.Longitude);
                                UpdateViewModel();
                            }
                        });
                    }
                    Thread.Sleep(TimeSpan.FromSeconds(10));
                }
                IsMaintainGpsLocationRunning = false;
            });
        }
        public void InitTowerEntityController(Vector2 _GPSCoords)
        {
            //Box colliders are disabled by default in the prefab in order to avoid to add them to the tower capture at spawn time
            ActivateBoxColliders(true);

            GPSCoords = networkObject.towerGPSCoords = _GPSCoords;

            //Calculates the tower position in Unity given the GPS coordinates
            var _towerPos = GPSHelper.LatLongToUnityCoords(_GPSCoords.x, _GPSCoords.y);

            //Updates tower position on network
            networkObject.towerNetPosition = _towerPos;

            //Update tower position on client
            transform.position = _towerPos;

            //Spawn tower capture controller on the network on the same position of the tower
            var towerCaptureController = NetworkManager.Instance.InstantiateTowerCaptureNetworkController(0, transform.position);

            towerCaptureController.networkStarted += TowerComponents_networkStarted;

            //Spawn on the network a NetworkUI contrller
            var towerNetUIController = NetworkManager.Instance.InstantiateTowerUIEntity(0, transform.position);

            towerNetUIController.networkStarted += TowerNetUIController_networkStarted;

            networkObject.SendRpc(RPC_UPDATE_TOWER_ATTRRIBUTES,
                                  Receivers.AllBuffered,
                                  OwnerFaction);
        }
        async private void inputFiled_ActionIconTapped(object sender, System.EventArgs e)
        {
            btnNext.Visibility     = System.Windows.Visibility.Collapsed;
            progressBar.Visibility = System.Windows.Visibility.Visible;
            App.ViewModel.UserViewModel.AllowGPS = true;
            var gps    = new GPSHelper();
            var result = await gps.GetPositionAsync();

            if (result != null)
            {
                int zipHelper = 0;
                var zip       = await bingHelper.GeoCoordinateToZipCodeAsync(result.Latitude, result.Longitude);

                inputFiled.Text = zip;

                App.ViewModel.UserViewModel.Location =
                    new Location()
                {
                    IsGeoCoded = true,
                    IsValid    = true,
                    Latitude   = result.Latitude,
                    Longitude  = result.Longitude,
                    Accuracy   = 0,
                    ZipCode    = int.TryParse(zip, out zipHelper) ? zipHelper : 0
                };
                inputFiled.SelectionStart = inputFiled.Text.Length;

                PostnummerServiceHelper post = new PostnummerServiceHelper();
                var r = await post.GeoToPostalCode(result.Latitude, result.Longitude);

                string p = r;
            }
            progressBar.Visibility = System.Windows.Visibility.Collapsed;
            btnNext.Visibility     = System.Windows.Visibility.Visible;
        }
Example #4
0
        async Task LoadAsync()
        {
            _progress.Show();

            var position = await GPSHelper.GetPosition();

            if (position != null)
            {
                CurrentLat  = position.Latitude.ToString();
                CurrentLong = position.Longitude.ToString();
            }

            //Dirty fix for now TODO Replace the string manipulation with proper regional detection
            CurrentLat  = CurrentLat.Replace(",", ".");
            CurrentLong = CurrentLong.Replace(",", ".");

            GetData();
        }
        public async Task <IActionResult> GetStationsWithinMetres(CityEnum city, int id, int metres = 0)
        {
            List <BikeStation> stations = (List <BikeStation>)cache.CheckCache(mySettingsOptions.DefaultCity);

            if (stations == null)
            {
                string result = await dbhelper.GetAllStations(city.ToString());

                stations = JsonConvert.DeserializeObject <List <BikeStation> >(result).ToList();
                cache.AddToCache(city.ToString(), stations);
            }
            metres = metres > 0 ? metres : mySettingsOptions.DefaultSearchRadius;

            var mystation      = stations.SingleOrDefault(x => x.stationNumber == id);
            var nearbyStations = GPSHelper.FindNearbyStations(stations, mystation, metres);

            return(Ok(nearbyStations));
        }
Example #6
0
        /// <summary>
        /// Inserts event for a manual unload override
        /// </summary>
        /// <param name="SerialNumber"></param>
        public static void ForceUnload(string SerialNumber)
        {
            using (var uow = SimpleIoc.Default.GetInstance <IUnitOfWorkFactory>().CreateUnitOfWork())
            {
                var truck  = uow.SettingsRepository.GetCurrentTruck();
                var driver = uow.SettingsRepository.GetCurrentDriver();

                var    aggEvt = instance._aggregateEvents.FirstOrDefault(evt => evt.SerialNumber == SerialNumber && !string.IsNullOrEmpty(evt.Epc));
                string epc    = (aggEvt != null) ? aggEvt.Epc : "";

                AggregateEvent agEvent = new AggregateEvent();
                agEvent.Timestamp = DateTime.Now.ToUniversalTime();

                var gpsCoords = GPSDataProvider.GetLastCoords();

                double lat = GPSHelper.SafeLat(gpsCoords);
                double lng = GPSHelper.SafeLong(gpsCoords);

                agEvent.SerialNumber = SerialNumber;
                agEvent.Epc          = epc;
                agEvent.AverageLat   = lat;
                agEvent.AverageLong  = lng;
                agEvent.MedianLat    = lat;
                agEvent.MedianLong   = lng;
                agEvent.FirstLat     = lat;
                agEvent.FirstLong    = lng;
                agEvent.LastLat      = lat;
                agEvent.LastLong     = lng;
                agEvent.TruckID      = (truck != null) ? truck.Id : "";
                agEvent.DriverID     = (driver != null) ? driver.Id : "";
                agEvent.EventType    = EventType.UNLOADED;
                agEvent.Created      = DateTime.Now.ToUniversalTime();

                instance._aggregateEvents.Add(agEvent);
                uow.AggregateEventRepository.Add(agEvent);
                uow.SaveChanges();

                instance.CorrectLoadNumber(uow, false, agEvent);
                instance.UpdateModuleStatus(uow, false, agEvent);

                //Messenger.Default.Send<AggregateEvent>(agEvent);
            }
        }
        private async void InitializeGPS()
        {
            if (App.ViewModel.UserViewModel.AllowGPS)
            {
                var gps    = new GPSHelper();
                var result = await gps.GetPositionAsync();

                if (result != null)
                {
                    App.ViewModel.UserViewModel.Location =
                        new Location()
                    {
                        IsGeoCoded = true,
                        IsValid    = true,
                        Latitude   = result.Latitude,
                        Longitude  = result.Longitude
                    };
                }
            }
        }
Example #8
0
        // Should be called every second

        void UpdateDriverBehaviour()
        {
            float newSpeed = 0;

            lock (lockInstance)
            {
                if (mLastKnownLocation == null)
                {
                    logService.WriteLog("JourneyManager:UpdateDriverBehaviour", "Can't UpdateDriverBehaviour, lastKnownLocation is null.");
                    Messenger.Default.Send(new NotificationMessage(this, "UnknownLocation"));
                    return;
                }

                Messenger.Default.Send(new NotificationMessage(this, "RecordingData"));
                logService.WriteLog("JourneyManager:UpdateDriverBehaviour", $"UpdateDriverBehaviour - distanceTravelled = {mDistanceTravelled}, Accuracy {mLastKnownLocation.Accuracy}");
                newSpeed = (float)mLastKnownLocation.Speed * Constants.kMetresPerSecondToKnots;
                float newDirection = (float)mLastKnownLocation.Heading;

                // Only do this when the trip has been going for long enough and we have an accurate reading
                if (mDistanceTravelled > 10.0f && mLastKnownLocation.Accuracy < Constants.kRequiredAccuracy)
                {
                    if (newSpeed > 5.0f)
                    {
                        float speedChange = newSpeed - mOldSpeed;
                        if (speedChange > 7.0f)
                        {
                            mDB0++;
                            logService.WriteLog("JourneyManager:UpdateDriverBehaviour", "Speed change > 7");
                        }
                        if (speedChange > 9.0f)
                        {
                            mDB2++;
                            logService.WriteLog("JourneyManager:UpdateDriverBehaviour", "Speed change > 9");
                        }
                        if (speedChange < -7.0f)
                        {
                            mDB4++;
                            logService.WriteLog("JourneyManager:UpdateDriverBehaviour", "Speed change < -7");
                        }
                        if (speedChange < -9.0f)
                        {
                            mDB6++;
                            logService.WriteLog("JourneyManager:UpdateDriverBehaviour", "Speed change < -9");
                        }

                        var angleDiff = Math.Abs(newDirection - mOldDirection);
                        if (angleDiff > 30.0f && newSpeed > 20.0f && angleDiff < 330.0f)
                        {
                            mDB8++;
                            logService.WriteLog("JourneyManager:UpdateDriverBehaviour", "Excessive cornering");
                        }

                        var distance = mCurrentJourney.LastOrDefault().DistanceBetween(new double[] { mTempOldLat, mTempOldLng, mLastKnownLocation.Latitude, mLastKnownLocation.Longitude });
                        int millis   = (int)(mLastKnownLocation.TimeStamp.TimeOfDay.TotalMilliseconds - mTempOldTime);

                        float calculatedSpeed = ((millis / 1000) * distance) * Constants.kMetresPerSecondToKnots;

                        logService.WriteLog("JourneyManager:UpdateDriverBehaviour", $"GPS Speed = {(mLastKnownLocation.Speed * Constants.kMetresPerSecondToKnots)}, calculated speed = {calculatedSpeed}, diff = {(mLastKnownLocation.Speed - calculatedSpeed)}");
                        logService.WriteLog("JourneyManager:UpdateDriverBehaviour", $"Speed has changed by {speedChange}, direction has changed by {angleDiff}");
                        logService.WriteLog("JourneyManager:UpdateDriverBehaviour", $"New speed = {newSpeed}, new bearing = {newDirection}");
                    }

                    mOldSpeed     = newSpeed;
                    mOldDirection = newDirection;
                    mTempOldLat   = mLastKnownLocation.Latitude;
                    mTempOldLng   = mLastKnownLocation.Longitude;
                    mTempOldTime  = mLastKnownLocation.TimeStamp.Ticks;
                }
            }


            lock (mCurrentJourney)
            {
                newSpeed = Math.Max(0.0f, newSpeed);
                if (mCurrentJourney.Count > 0)
                {
                    {
                        var lastPoint = mCurrentJourney[mCurrentJourney.Count - 1];

                        var distance = mOldLocation.DistanceTo(mLastKnownLocation);

                        mDistanceTravelled += 0.868976f * (float)(100.0f * 3600.0f * distance / 1609.344f);
                        logService.WriteLog("JourneyManager:UpdateDriverBehaviour", "Distance travelled = " + mDistanceTravelled);

                        // Handle average speed processing
                        var averageSpeed = 0.0f;
                        mSpeedHistory.Add(newSpeed);

                        // Store 8 speeds
                        while (mSpeedHistory.Count > 8)
                        {
                            mSpeedHistory.RemoveAt(0);
                        }

                        for (int i = 0; i < mSpeedHistory.Count; i++)
                        {
                            averageSpeed += mSpeedHistory[i];
                        }
                        averageSpeed /= mSpeedHistory.Count;
                        logService.WriteLog("JourneyManager:UpdateDriverBehaviour", "Average speed = " + averageSpeed);

                        mAverageSpeed = averageSpeed;
                        if (mMaxSpeedLocation == null || (newSpeed > mMaxSpeed && newSpeed > 5.0f))
                        {
                            mMaxSpeedLocation = mLastKnownLocation;
                            mMaxSpeed         = newSpeed;
                            var locDateTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(mLastKnownLocation.TimeStamp.TimeOfDay.TotalMilliseconds); // GPS time is milliseconds since 1970
                            mMaxSpeedTime = GPSHelper.TimeForTimeStamp(locDateTime.Ticks);
                            logService.WriteLog("JourneyManager:UpdateDriverBehaviour", "Setting new max speed for this segment = " + mMaxSpeed + " at: " + mMaxSpeedTime);
                        }

                        float dist     = (float)mLastKnownLocation.DistanceTo(lastPoint);
                        var   timeDiff = mLastKnownLocation.TimeStamp - lastPoint.TimeStamp;
                        if (dist > 10.0 && timeDiff.Minutes > 5.0)
                        {
                            mCurrentJourney.Add(mLastKnownLocation);
                            logService.WriteLog("JourneyManager:UpdateDriverBehaviour", "Adding new location to journey, new length = " + mCurrentJourney.Count);
                        }

                        mOldLocation = mLastKnownLocation;
                    }
                }
            }
        }
Example #9
0
        bool AddEvent(LocationServiceData location, string eventType)
        {
            var res = false;

            try
            {
                lock (lockInstance)
                {
                    var nfi = new NumberFormatInfo
                    {
                        NumberDecimalSeparator = "."
                    };

                    if (location == null)
                    {
                        logService.WriteLog("JourneyManager:AddEvent", "ERROR: AddEvent location was NULL");
                        throw new Exception();
                    }

                    logService.WriteLog("JourneyManager:AddEvent", $"Adding event at {location.TimeStamp.TimeOfDay}, type = {eventType}");

                    var gpsTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(location.TimeStamp.TimeOfDay.TotalMilliseconds); // GPS time is milliseconds since 1970
                    var seconds = GPSHelper.TimeForTimeStamp(gpsTime.Ticks);
                    var latStr  = GPSHelper.ToDegreesMinutesSeconds(location.Latitude, GPSCoordinate.Latitude);
                    var lngStr  = GPSHelper.ToDegreesMinutesSeconds(location.Longitude, GPSCoordinate.Longitude);

                    var rr = string.Empty;

                    var horiAcc = (float)location.Accuracy;
                    var HDOP    = 10 * (int)(horiAcc / 5.0f);

                    if (eventType == "MV" && mMaxSpeedTime > 0 && mMaxSpeed > 5.0f)
                    {
                        logService.WriteLog("JourneyManager:AddEvent", "Max speed position update");
                        // Need to increment counter an extra time if we have a max speed (.Position Update) packet
                        //UserData.Instance.RecordNumber += 1;
                        res = true; // increase record number

                        var maxSpeedLatStr = GPSHelper.ToDegreesMinutesSeconds(mMaxSpeedLocation.Latitude, GPSCoordinate.Latitude);
                        var maxSpeedLngStr = GPSHelper.ToDegreesMinutesSeconds(mMaxSpeedLocation.Longitude, GPSCoordinate.Longitude);
                        rr = string.Format("{0},{1}:{2}:{3}:{4}:8:{5}", mMaxSpeedTime, maxSpeedLatStr, maxSpeedLngStr, mMaxSpeed.ToString("0.00", nfi),
                                           (int)Math.Max(0.0f, mMaxSpeedLocation.Heading), HDOP);
                    }

                    var speedInKnots = (float)Math.Max(location.Speed, 0.0f) * Constants.kMetresPerSecondToKnots;
                    var version      = VersionNum;

                    //var userData = UserData.Instance;
                    var sik = speedInKnots.ToString("0.00", nfi);
                    var gps = GpsRunning ? "#1" : string.Empty;
                    var buf = $"TF,{SimNumber}/{seconds},4T54H1.v{version},{RecordNum},{latStr}:{lngStr}:{sik}:{(int)Math.Max(0.0f, location.Heading)}:8:{HDOP},{(int)mDistanceTravelled},{eventType},{(AppStarted - DateTime.Now).Hours}:5:0061:04D0,1:-3:32:57:" +
                              $"{JourneyCounter}:{JourneyCounter}:0:|{mDB0}:{mDB2}:{mDB4}:{mDB6}:{mDB8}::::::,1:420,1:1:20:0,{Odometer},{(int)Math.Max(mAverageSpeed, 0.0f)},{rr},#{PairId}{gps}/\r\n";

                    MessageQueue.Add(buf);

                    res = true;

                    mMaxDB0 = Math.Max(mDB0, mMaxDB0);
                    mMaxDB2 = Math.Max(mDB2, mMaxDB2);
                    mMaxDB4 = Math.Max(mDB4, mMaxDB4);
                    mMaxDB6 = Math.Max(mDB6, mMaxDB6);
                    mMaxDB8 = Math.Max(mDB8, mMaxDB8);

                    // AB what does this do? :|
                    //NSString *DBMax = [[NSString alloc] initWithFormat:@"Max DB %d %d %d %d %d", self.maxDB0, self.maxDB2, self.maxDB4, self.maxDB6, self.maxDB8];
                    //[LocationData getInstance].String7 = [[NSString alloc] initWithString:DBMax];

                    SendUDP();
                }
            }
            catch (Exception ex)
            {
                logService.WriteLog("JourneyManager:AddEvent(catch)", ex.StackTrace);
            }
            return(res);
        }
Example #10
0
        /// <summary>
        /// Inserts event for a manual unload override
        /// </summary>
        /// <param name="SerialNumber"></param>
        public static void ForceLoad(string SerialNumber)
        {
            if (!SerialNumbersOnTruckNotThreadSafe.Any(x => x == SerialNumber))
            {
                using (var uow = SimpleIoc.Default.GetInstance <IUnitOfWorkFactory>().CreateUnitOfWork())
                {
                    var truck  = uow.SettingsRepository.GetCurrentTruck();
                    var driver = uow.SettingsRepository.GetCurrentDriver();

                    var            aggEvt  = instance._aggregateEvents.FirstOrDefault(evt => evt.SerialNumber == SerialNumber && !string.IsNullOrEmpty(evt.Epc));
                    string         epc     = (aggEvt != null) ? aggEvt.Epc : "";
                    AggregateEvent agEvent = new AggregateEvent();
                    agEvent.Timestamp = DateTime.Now.ToUniversalTime();

                    var gpsCoords = GPSDataProvider.GetLastCoords();

                    double lat = GPSHelper.SafeLat(gpsCoords);
                    double lng = GPSHelper.SafeLong(gpsCoords);

                    agEvent.SerialNumber = SerialNumber;
                    agEvent.Epc          = epc;
                    agEvent.AverageLat   = lat;
                    agEvent.AverageLong  = lng;
                    agEvent.MedianLat    = lat;
                    agEvent.MedianLong   = lng;
                    agEvent.FirstLat     = lat;
                    agEvent.FirstLong    = lng;
                    agEvent.LastLat      = lat;
                    agEvent.LastLong     = lng;
                    agEvent.TruckID      = (truck != null) ? truck.Id : "";
                    agEvent.DriverID     = (driver != null) ? driver.Id : "";
                    agEvent.EventType    = EventType.LOADED;
                    agEvent.Created      = DateTime.Now.ToUniversalTime();

                    if (uow.SettingsRepository.EventOnGinYard(agEvent))
                    {
                        agEvent.LoadNumber = "";
                    }
                    else if (uow.SettingsRepository.EventAtFeeder(agEvent))
                    {
                        agEvent.LoadNumber = "";
                    }
                    else if (SerialNumbersOnTruck == null || SerialNumbersOnTruck.Count() == 0)
                    {
                        //NO MODULES ON TRUCK SO GENERATE NEW NUMBER
                        agEvent.LoadNumber = uow.TruckRepository.GetNextLoadNumber();
                    }
                    else
                    {
                        //THERE ARE OTHER MODULES ON TRUCK SO GET LAST NUMBER USED
                        agEvent.LoadNumber = uow.TruckRepository.GetLastLoadNumber();
                    }

                    instance._aggregateEvents.Add(agEvent);
                    uow.AggregateEventRepository.Add(agEvent);
                    uow.SaveChanges();

                    instance.CorrectLoadNumber(uow, true, agEvent);
                    instance.UpdateModuleStatus(uow, true, agEvent);
                    //Messenger.Default.Send<AggregateEvent>(agEvent);
                }
            }
        }
Example #11
0
        private void ProcessQuadratureStateChange2(QuadratureStateChangeMessage eventData)
        {
            try
            {
                if (!initialized)
                {
                    return;
                }

                Logging.Logger.Log("AGG", "Processing quadrature state change.");
                lock (instance.locker)
                {
                    using (var uow = SimpleIoc.Default.GetInstance <IUnitOfWorkFactory>().CreateUnitOfWork())
                    {
                        //if quadrature is turning then start the reader
                        if (eventData.DirectionOfRotation == DirectionOfRotation.RotatingClockwise || eventData.DirectionOfRotation == DirectionOfRotation.RotatingCounterClockwise)
                        {
                            if (eventData.DirectionOfRotation == DirectionOfRotation.RotatingClockwise)
                            {
                                GPSDataProvider.SetReverse(true);
                            }

                            readStartTime = DateTime.Now.AddSeconds(delay).ToUniversalTime();

                            Logging.Logger.Log("AGG", "Ignore tags before " + readStartTime.ToString());

                            isLoading   = false;
                            isUnloading = false;

                            tagBuffer.Clear();
                            Logging.Logger.Log("AGG", "Starting reader for read cycle");
                            TagDataProvider.Start(delay);

                            if (eventData.DirectionOfRotation == DirectionOfRotation.RotatingClockwise)
                            {
                                isLoading = true;
                                GPSDataProvider.SetReverse(true);
                                Logging.Logger.Log("AGG", "Loading started");
                            }
                            else
                            {
                                isUnloading = true;
                                GPSDataProvider.SetReverse(false);
                                Logging.Logger.Log("AGG", "Unloading started");
                            }
                        }
                        else
                        {
                            if (DateTime.UtcNow < readStartTime)
                            {
                                Logging.Logger.Log("AGG", "Cancelling read cycle");
                                TagDataProvider.Stop();
                                return;
                            }

                            Logging.Logger.Log("AGG", "Processing stop");
                            GPSDataProvider.SetReverse(false);
                            var      isLoadEvent = isLoading;
                            DateTime stopTime    = DateTime.Now.ToUniversalTime();

                            isLoading   = false; //stops adding tags to the buffer of distinct items scanned
                            isUnloading = false;

                            Logging.Logger.Log("AGG", "Checking for modules still in view");

                            if (!isLoadEvent)
                            {
                                System.Threading.Thread.Sleep(100);               //changed from 200 to 100
                            }
                            DateTime correctionStart = DateTime.UtcNow;
                            if (!isLoadEvent)
                            {
                                System.Threading.Thread.Sleep(200);               //changed from 2000 to 500
                            }
                            TagDataProvider.Stop();
                            DateTime correctionEnd = DateTime.UtcNow;

                            List <string> tagsStillOnTruck = new List <string>();
                            var           tagsRead         = TagDataProvider.GetTagsFirstSeenInTimeRange(readStartTime, stopTime);

                            if (!isLoadEvent)
                            {
                                tagsStillOnTruck = TagDataProvider.GetTagsLastSeenInTimeRange(correctionStart, correctionEnd).Select(t => t.SerialNumber).Distinct().ToList();
                                StringBuilder sb = new StringBuilder();
                                foreach (var s in tagsStillOnTruck)
                                {
                                    sb.Append(s + ", ");
                                }
                                Logging.Logger.Log("AGG", "Tags still on truck (detected in view after chains stopped): " + sb.ToString().TrimEnd(','));
                            }



                            var      truck      = uow.SettingsRepository.GetCurrentTruck();
                            var      driver     = uow.SettingsRepository.GetCurrentDriver();
                            string[] snsOnTruck = SerialNumbersOnTruck.ToArray();

                            TagItem[] tagsInBuffer = null;

                            lock (tagBuffer)
                            {
                                tagsInBuffer = tagBuffer.ToArray();
                            }

                            Logging.Logger.Log("AGG", "Processing unique tags seen.");
                            int agEventCount = 0;
                            foreach (var tag in tagsInBuffer)
                            {
                                var tagRead = tagsRead.Where(r => r.SerialNumber == tag.SerialNumber).FirstOrDefault();
                                //var lastTagLastTagRead = tagsRead.Where(r => r.SerialNumber == tag.SerialNumber).LastOrDefault();

                                DateTime startTime = readStartTime;
                                DateTime endTime   = stopTime;

                                var firstTag = tagsRead.Where(r => r.SerialNumber == tag.SerialNumber).FirstOrDefault();
                                var lastTag  = tagsRead.Where(r => r.SerialNumber == tag.SerialNumber).LastOrDefault();

                                if (tagRead != null)
                                {
                                    startTime = tagRead.Firstseen;
                                }
                                if (tagRead != null)
                                {
                                    endTime = tagRead.Lastseen;
                                }

                                var firstCoords = GPSDataProvider.GetFirstCoords(startTime, endTime);
                                var lastCoords  = GPSDataProvider.GetLastCoords(startTime, endTime);

                                AggregateEvent agEvent = new AggregateEvent();

                                if (isLoadEvent)
                                {
                                    agEvent.Timestamp = startTime;
                                }
                                else
                                {
                                    agEvent.Timestamp = endTime;
                                }

                                agEvent.SerialNumber = tag.SerialNumber;
                                agEvent.Epc          = tag.Epc;
                                agEvent.AverageLat   = GPSDataProvider.GetAverageLatitude(startTime, endTime);
                                agEvent.AverageLong  = GPSDataProvider.GetAverageLongitude(startTime, endTime);
                                agEvent.MedianLat    = GPSDataProvider.GetMedianLatitude(startTime, endTime);
                                agEvent.MedianLong   = GPSDataProvider.GetMedianLongitude(startTime, endTime);
                                agEvent.FirstLat     = GPSHelper.SafeLat(firstCoords);
                                agEvent.FirstLong    = GPSHelper.SafeLong(firstCoords);
                                agEvent.LastLat      = GPSHelper.SafeLat(lastCoords);
                                agEvent.LastLong     = GPSHelper.SafeLong(lastCoords);
                                agEvent.TruckID      = (truck != null) ? truck.Id : "";
                                agEvent.DriverID     = (driver != null) ? driver.Id : "";
                                agEvent.EventType    = (isLoadEvent) ? EventType.LOADED : EventType.UNLOADED;

                                lock (_aggregateEvents)
                                {
                                    //if we are on the gin yard leave load number empty
                                    if (!isLoadEvent)
                                    {
                                        agEvent.LoadNumber = "";
                                    }
                                    else
                                    {
                                        if (uow.SettingsRepository.EventOnGinYard(agEvent))
                                        {
                                            agEvent.LoadNumber = "";
                                        }
                                        else if (uow.SettingsRepository.EventAtFeeder(agEvent))
                                        {
                                            agEvent.LoadNumber = "";
                                        }
                                        else if (SerialNumbersOnTruck == null || SerialNumbersOnTruck.Count() == 0)
                                        {
                                            //NO MODULES ON TRUCK SO GENERATE NEW NUMBER
                                            agEvent.LoadNumber = uow.TruckRepository.GetNextLoadNumber();
                                        }
                                        else
                                        {
                                            //THERE ARE OTHER MODULES ON TRUCK SO GET LAST NUMBER USED
                                            agEvent.LoadNumber = uow.TruckRepository.GetLastLoadNumber();
                                        }
                                    }

                                    //only log event if it is a load of a module not previously scanned in a load cycle
                                    //or if an unload for which the serial wasn't picked up still on the truck - added check to only record unload event for modules that were on the truck
                                    if ((isLoadEvent && !snsOnTruck.Contains(agEvent.SerialNumber)) || (!isLoadEvent && snsOnTruck.Contains(agEvent.SerialNumber) /*&& !tagsStillOnTruck.Contains(agEvent.SerialNumber)*/))
                                    {
                                        agEventCount++;
                                        _aggregateEvents.Add(agEvent);
                                        agEvent.Created = DateTime.UtcNow;
                                        uow.AggregateEventRepository.Add(agEvent);
                                        uow.SaveChanges();

                                        //if unloading in the field clear last load number on events with this serial number
                                        //that were generated when loading stopped - this prevents skipping
                                        //load numbers when all modules are unloaded in the field
                                        CorrectLoadNumber(uow, isLoadEvent, agEvent);

                                        UpdateModuleStatus(uow, isLoadEvent, agEvent);

                                        Messenger.Default.Send <AggregateEvent>(agEvent);
                                    }
                                }
                            }
                            if (agEventCount > 0)
                            {
                                Messenger.Default.Send <AllAggEventsProcessComplete>(new AllAggEventsProcessComplete {
                                    IsLoading = isLoadEvent
                                });
                            }
                            tagBuffer.Clear();
                        }
                    }
                }
            }
            catch (Exception exc)
            {
                Logging.Logger.Log(exc);
            }
        }