public VehicleDto(Vehicle vehicle)
        {
            VIN             = vehicle.VIN;
            Username        = vehicle.UserIdentityGuid;
            InstagramUri    = vehicle.InstagramUri;
            FacebookUri     = vehicle.FacebookUri;
            ImageUri        = vehicle.Image.Uri;
            ColorCode       = vehicle.Color.Code;
            ColorName       = vehicle.Color.Name;
            Description     = vehicle.Description;
            Manufacturer    = vehicle.ModelYear.Model.Manufacturer.Name;
            Model           = vehicle.ModelYear.Model.Name;
            Year            = vehicle.ModelYear.Year;
            Transmission    = vehicle.Transmission.Name;
            VehicleLocation = new VehicleLocation(vehicle.VehicleLocation.Latitude, vehicle.VehicleLocation.Longitude);
            ViewCount       = vehicle.ViewCount;
            Status          = vehicle.Status.Name;

            if (vehicle.VehicleImages != null)
            {
                foreach (var vi in vehicle.VehicleImages)
                {
                    VehicleImages.Add(vi.Image);
                }
            }
        }
Exemple #2
0
        public async Task <string> AddIt(LocationContext context, VehicleLocation vehicleLocation)
        {
            _context = context;
            _context.VehicleLocations.Add(vehicleLocation);
            await _context.SaveChangesAsync();

            string vehicleLatLong = "";

            vehicleLatLong += vehicleLocation.VehicleId;
            vehicleLatLong += "#";
            vehicleLatLong += vehicleLocation.Latitude;
            vehicleLatLong += ",";
            vehicleLatLong += vehicleLocation.Longitude;

            vehicleLocation.VehicleLatLong        = vehicleLatLong;
            _context.Entry(vehicleLocation).State = EntityState.Modified;
            _context.VehicleLocations.Update(vehicleLocation);

            try
            {
                await _context.SaveChangesAsync();

                return("Response:{ status: Succes, description: Vehicle data saved}");
            }
            catch (DbUpdateConcurrencyException e)
            {
                return("Look here " + e.Message);
            }
        }
        public static DataSet SaveLocation(VehicleLocation vehiclelocation, string Action)
        {
            try
            {
                string ConnectionString = Common.GetConnectionString();

                List <SqlParameter> parameters = new List <SqlParameter>();
                parameters.Add(new SqlParameter("@LocationID", vehiclelocation.LocationID));
                parameters.Add(new SqlParameter("@VehicleId", vehiclelocation.VehicleId));
                parameters.Add(new SqlParameter("@LocationLatitude", vehiclelocation.LocationLatitude));
                parameters.Add(new SqlParameter("@LocationLongitude", vehiclelocation.LocationLongitude));
                parameters.Add(new SqlParameter("@LocationFullAddress", vehiclelocation.LocationFullAddress));
                parameters.Add(new SqlParameter("@LandMark", vehiclelocation.LandMark));
                parameters.Add(new SqlParameter("@CityName", vehiclelocation.CityName));
                parameters.Add(new SqlParameter("@Action", Action));

                //int rowsAffected = SqlHelper.ExecuteNonQuery(ConnectionString, CommandType.StoredProcedure, "spSaveLocation", parameters.ToArray());
                //return rowsAffected;
                using (DataSet dt = SqlHelper.ExecuteDataset(ConnectionString, CommandType.StoredProcedure, "spSaveLocation", parameters.ToArray()))
                {
                    return(dt);
                }
            }
            catch (Exception e)
            {
                //loggerErr.Error(e.Message + " - " + e.StackTrace);
                throw e;
            }
        }
Exemple #4
0
        public async Task <IActionResult> PutVehicleLocation([FromRoute] int id, [FromBody] VehicleLocation vehicleLocation)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != vehicleLocation.Id)
            {
                return(BadRequest());
            }

            _context.Entry(vehicleLocation).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!VehicleLocationExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
        private DateTime CreateLocalTimestamp(VehicleLocation location)
        {
            var ukTimezone = TimeZoneInfo.FindSystemTimeZoneById("Europe/London");
            var datetime   = DateTime.UnixEpoch.AddSeconds(location.LastGpsFix).AddMinutes(1);

            datetime = TimeZoneInfo.ConvertTimeFromUtc(datetime, ukTimezone);
            return(datetime);
        }
Exemple #6
0
        public async Task <IActionResult> PostVehicleLocation([FromBody] VehicleLocation vehicleLocation)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            PostCheck checkIt  = new PostCheck();
            string    response = await checkIt.AddIt(_context, vehicleLocation);

            return(Ok(response));
        }
        public IActionResult Post(VehicleLocation vehicleLocation)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            locationService.Add(vehicleLocation);

            return(CreatedAtRoute(new { Id = vehicleLocation.DeviceId }, vehicleLocation));
        }
Exemple #8
0
        public async Task <string> DoesItExist(LocationContext context, VehicleLocation vehicleLocation)
        {
            _context = context;
            var response = await _context.VehicleLocations.SingleOrDefaultAsync(m => m.VehicleLatLong == vehicleLocation.VehicleLatLong);

            if (response == null)
            {
                return("1");
            }
            return("0");
        }
Exemple #9
0
        private void UpdateMoveControlSensorData()
        {
            VehicleLocation location = localData.Location;

            if (localData != null)
            {
                sensorData_Address.SetValueAndColor(location.LastAddress, (location.InAddress ? 100 : 0));
                sensorData_Section.SetValueAndColor(location.NowSection);
                sensorData_Distance.SetValueAndColor(location.DistanceFormSectionHead.ToString("0"));
            }
            else
            {
                sensorData_Address.SetValueAndColor("");
                sensorData_Section.SetValueAndColor("");
                sensorData_Distance.SetValueAndColor("");
            }

            sensorData_Real.SetValueAndColor(computeFunction.GetMapAGVPositionStringWithAngle(localData.Real));
            sensorData_LocationAGVPosition.SetValueAndColor(computeFunction.GetLocateAGVPositionStringWithAngle(localData.MoveControlData.LocateControlData.LocateAGVPosition));
            sensorData_MIPCAGVPosition.SetValueAndColor(computeFunction.GetLocateAGVPositionStringWithAngle(localData.MoveControlData.MotionControlData.EncoderAGVPosition));

            MoveCommandData command = localData.MoveControlData.MoveCommand;

            if (command != null)
            {
                sensorData_CommandID.SetValueAndColor(command.CommandID);
                sensorData_CommandStartTime.SetValueAndColor(command.StartTime.ToString("HH:mm:ss"));
                sensorData_CommandStstus.SetValueAndColor(command.CommandStatus.ToString());
                sensorData_MoveStatus.SetValueAndColor(command.MoveStatus.ToString(), (int)command.MoveStatus);
                sensorData_CommandEncoder.SetValueAndColor(command.CommandEncoder.ToString("0"));
                SetLabelTextAndColor(label_MoveControlSensorData_SensorSstatusValue, command.SensorStatus);
                SetLabelTextAndColor(label_MoveControlSensorData_ReserveValue, (command.WaitReserveIndex == -1 ? EnumVehicleSafetyAction.Normal : EnumVehicleSafetyAction.SlowStop));
                SetLabelTextAndColor(label_MoveControlSensorData_PauseValue, command.AGVPause);
            }
            else
            {
                sensorData_CommandID.SetValueAndColor("");
                sensorData_CommandStartTime.SetValueAndColor("");
                sensorData_CommandStstus.SetValueAndColor("");
                sensorData_MoveStatus.SetValueAndColor("");
                sensorData_CommandEncoder.SetValueAndColor("");
                label_MoveControlSensorData_SensorSstatusValue.Text = "";
                label_MoveControlSensorData_ReserveValue.Text       = "";
                label_MoveControlSensorData_PauseValue.Text         = "";
            }

            SetLabelTextAndColor(label_MoveControlSensorData_SafetySensorValue, localData.MIPCData.SafetySensorStatus);
            SetLabelTextAndColor(label_MoveControlSensorData_LocalPauseValue, localData.MoveControlData.SensorStatus.LocalPause);

            sensorData_Velocity.SetValueAndColor(String.Concat(localData.MoveControlData.MotionControlData.LineVelocity.ToString("0"), "/",
                                                               localData.MoveControlData.MotionControlData.SimulateLineVelocity.ToString("0")));
        }
Exemple #10
0
        public static async Task <Vehicle> CreateVehicle(int branchId, int fuel, int?odometer,
                                                         VehicleManufacturingInfo manufacturingInfo, VehiclePurchaseInfo purchaseInfo,
                                                         VehicleLocation locationInfo, VehicleSpecs vehicleSpex)
        {
            var vehicle = new Vehicle();

            vehicle.SetBasicData(branchId, fuel);
            vehicle.SetLocationInfo(locationInfo);
            vehicle.SetSpecs(vehicleSpex);
            vehicle.SetPurchaseInfo(purchaseInfo);
            vehicle.MarkVehicleAsReady();
            vehicle.Odometer = odometer;
            return(vehicle);
        }
        private Dictionary <string, object> CreateGeoJsonProperties(VehicleLocation location)
        {
            DateTime datetime = CreateLocalTimestamp(location);

            var properties = new Dictionary <string, object>();

            properties.Add("heading", location.Heading);
            properties.Add("colour", _routeColourService.Get(location.ServiceName)?.Colour);
            properties.Add("text_colour", _routeColourService.Get(location.ServiceName)?.TextColor);
            properties.Add("name", location.ServiceName);
            properties.Add("vehicleId", location.VehicleId);
            properties.Add("last_update", datetime.ToString());
            properties.Add("destination", location.Destination);
            return(properties);
        }
        public IActionResult SaveLocation([FromBody] VehicleLocation vehiclelocation) //int LocationID, int VehicleId, decimal LocationLatitude, decimal LocationLongitude, string LocationFullAddress
        {
            //List<VehicleLocation> vehicleLocation = new List<VehicleLocation>();
            //string GetConnectionString = VehiclesController.GetConnectionString();
            List <ServiceDetails> serviceDetail = new List <ServiceDetails>();
            string Action = "Add";

            try
            {
                if (vehiclelocation.VehicleId <= 0 || vehiclelocation.VehicleId == null)
                {
                    return(StatusCode((int)HttpStatusCode.BadRequest, new { error = new { message = "Please enter a VehicleId" } }));
                }
                //else if (vehiclelocation.LocationLatitude == "" || vehiclelocation.LocationLatitude == "string" || vehiclelocation.LocationLatitude == null)
                //{
                //    return StatusCode((int)HttpStatusCode.BadRequest, new { error = new { message = "Please enter a Latitude value" } });
                //}
                //else if (vehiclelocation.LocationLongitude == "" || vehiclelocation.LocationLongitude == "string" || vehiclelocation.LocationLongitude == null)
                //{
                //    return StatusCode((int)HttpStatusCode.BadRequest, new { error = new { message = "Please enter a Longitude value" } });
                //}
                else if (vehiclelocation.CityName == "" || vehiclelocation.CityName == "string" || vehiclelocation.CityName == null)
                {
                    return(StatusCode((int)HttpStatusCode.BadRequest, new { error = new { message = "Please enter a CityName" } }));
                }
                else
                {
                    DataSet dt  = Data.Vehicles.SaveLocation(vehiclelocation, Action);
                    string  row = dt.Tables[0].Rows[0]["ErrorMessage"].ToString();
                    if (row == "Success")

                    {
                        return(StatusCode((int)HttpStatusCode.OK, "Saved Successfully"));
                    }
                    else
                    {
                        return(StatusCode((int)HttpStatusCode.Forbidden, new { error = new { message = row } }));
                    }
                }
            }

            catch (Exception e)
            {
                string SaveErrorLog = Data.Common.SaveErrorLog("SaveLocation", e.Message);

                return(StatusCode((int)HttpStatusCode.InternalServerError, new { error = new { message = e.Message.ToString() } }));
            }
        }
Exemple #13
0
        public View GetInfoWindow(Marker marker)
        {
            if (marker.Title != null)
            {
                var vehicleInfo = VehicleLocation.FirstOrDefault(x => x.trackerId.ToString() == marker.Title);


                View view = LayoutInflater.Inflate(Resource.Layout.WindowsInfoAdapterLayout, null, false);

                var label     = view.FindViewById <TextView>(Resource.Id.vehicleLabel);
                var model     = view.FindViewById <TextView>(Resource.Id.vehicleModel);
                var regNumber = view.FindViewById <TextView>(Resource.Id.vehicleregNumber);

                if (vehicleInfo.label != "")
                {
                    label.Text = vehicleInfo.label;
                }
                else
                {
                    label.Visibility = ViewStates.Gone;
                }

                if (vehicleInfo.model != "")
                {
                    model.Text = vehicleInfo.model;
                }
                else
                {
                    model.Visibility = ViewStates.Gone;
                }

                if (vehicleInfo.regNumber != "")
                {
                    regNumber.Text = vehicleInfo.regNumber;
                }
                else
                {
                    regNumber.Visibility = ViewStates.Gone;
                }

                return(view);
            }
            else
            {
                return(null);
            }
        }
        private (VehicleManufacturingInfo, VehicleLocation, VehiclePurchaseInfo, VehicleSpecs, VehicleLicenseInfo) CreateVehicleValueObjects(VehicleDto vehicleDto)
        {
            var manufacturingInfoDto = vehicleDto.VehicleManufacturingInfo;
            VehicleManufacturingInfo vehicleManufacturingInfo = null;

            if (manufacturingInfoDto != null)
            {
                vehicleManufacturingInfo = new VehicleManufacturingInfo(manufacturingInfoDto.ModelId, manufacturingInfoDto.Year, manufacturingInfoDto.ChassisNo);
            }

            var             locationInfoDto = vehicleDto.LocationInfo;
            VehicleLocation vehicleLocation = null;

            if (locationInfoDto != null)
            {
                vehicleLocation = new VehicleLocation(locationInfoDto.CurrentLocationId);
            }

            var purchaseInfoDto = vehicleDto.PurchaseInfo;
            VehiclePurchaseInfo vehiclePurchaseInfo = null;

            if (purchaseInfoDto != null)
            {
                vehiclePurchaseInfo = VehiclePurchaseInfo.CreateVehiclePurchaseInfo(purchaseInfoDto.VendorId, purchaseInfoDto.Date, purchaseInfoDto.Price);
            }

            var          spexDto     = vehicleDto.Specs;
            VehicleSpecs vehicleSpex = null;

            if (spexDto != null)
            {
                vehicleSpex = VehicleSpecs.CreateVehicleSpex(spexDto.ColorId, spexDto.TrimLevelId,
                                                             spexDto.FuelTypeId, spexDto.FuelTankSize, spexDto.EngineSize);
            }

            var licenseInfoDto = vehicleDto.VehicleLicenseInfo;
            VehicleLicenseInfo vehicleLicenseInfo = null;

            if (licenseInfoDto != null)
            {
                vehicleLicenseInfo = VehicleLicenseInfo.Create(licenseInfoDto.LicenseTypeId, licenseInfoDto.UsageTypeId,
                                                               licenseInfoDto.PlateNo, licenseInfoDto.Number, licenseInfoDto.ExpiryDate);
            }

            return(vehicleManufacturingInfo, vehicleLocation, vehiclePurchaseInfo, vehicleSpex, vehicleLicenseInfo);
        }
Exemple #15
0
        public async Task <string> SaveAddress(string newAddress, VehicleLocation vehicleLocation)
        {
            vehicleLocation.Address = newAddress;
            _context.Entry(vehicleLocation).State = EntityState.Modified;
            _context.VehicleLocations.Update(vehicleLocation);

            try
            {
                await _context.SaveChangesAsync();

                return("Response:{ status: Succes, description: Vehicle data saved}");
            }
            catch (DbUpdateConcurrencyException e)
            {
                return("Look here " + e.Message);
            }
        }
Exemple #16
0
 public VehicleLocationToDb(VehicleLocation vehiclelocation)
     : base(s_metadata)
 {
     SetSqlInt64(0, vehiclelocation.ID);
     SetSqlDateTime(1, vehiclelocation.Times ?? SqlTypes.SqlDateTime.Null);
     SetSqlString(2, vehiclelocation.Phone);
     SetSqlString(3, vehiclelocation.VehicleNumber);
     SetSqlString(4, vehiclelocation.Longitude);
     SetSqlString(5, vehiclelocation.Latitude);
     SetSqlString(6, vehiclelocation.Str1);
     SetSqlString(7, vehiclelocation.Str2);
     SetSqlString(8, vehiclelocation.Str3);
     SetSqlString(9, vehiclelocation.Str4);
     SetSqlString(10, vehiclelocation.Str5);
     SetSqlInt64(11, vehiclelocation.Int1);
     SetSqlInt64(12, vehiclelocation.Int2);
     SetSqlInt64(13, vehiclelocation.Int3);
     SetSqlDateTime(14, vehiclelocation.Datetime1 ?? SqlTypes.SqlDateTime.Null);
     SetSqlDateTime(15, vehiclelocation.Datetime2 ?? SqlTypes.SqlDateTime.Null);
     SetSqlDateTime(16, vehiclelocation.Datetime3 ?? SqlTypes.SqlDateTime.Null);
 }
Exemple #17
0
        public MapAGVPosition GetAGVPositionByVehicleLocation(VehicleLocation now)
        {
            if (localData.TheMapInfo.AllSection.ContainsKey(now.NowSection))
            {
                MapAGVPosition returnValue = new MapAGVPosition();

                returnValue.Angle      = localData.TheMapInfo.AllSection[now.NowSection].FromVehicleAngle;
                returnValue.Position.X = localData.TheMapInfo.AllSection[now.NowSection].FromAddress.AGVPosition.Position.X +
                                         (localData.TheMapInfo.AllSection[now.NowSection].ToAddress.AGVPosition.Position.X -
                                          localData.TheMapInfo.AllSection[now.NowSection].FromAddress.AGVPosition.Position.X) *
                                         (now.DistanceFormSectionHead / localData.TheMapInfo.AllSection[now.NowSection].Distance);
                returnValue.Position.Y = localData.TheMapInfo.AllSection[now.NowSection].FromAddress.AGVPosition.Position.Y +
                                         (localData.TheMapInfo.AllSection[now.NowSection].ToAddress.AGVPosition.Position.Y -
                                          localData.TheMapInfo.AllSection[now.NowSection].FromAddress.AGVPosition.Position.Y) *
                                         (now.DistanceFormSectionHead / localData.TheMapInfo.AllSection[now.NowSection].Distance);

                return(returnValue);
            }
            else
            {
                return(null);
            }
        }
        /// <summary>
        /// Return a list of all gps messages with there timestamp from the log
        /// </summary>
        /// <param name="fn"></param>
        /// <returns></returns>
        private Dictionary<long, VehicleLocation> readGPSMsgInLog(string fn)
        {
            Dictionary<long, VehicleLocation> vehiclePositionList = new Dictionary<long, VehicleLocation>();

            // Telemetry Log
            if (fn.ToLower().EndsWith("tlog"))
            {
                using (MAVLinkInterface mine = new MAVLinkInterface())
                {
                    mine.logplaybackfile =
                        new BinaryReader(File.Open(fn, FileMode.Open, FileAccess.Read, FileShare.Read));
                    mine.logreadmode = true;

                    CurrentState cs = new CurrentState();

                    while (mine.logplaybackfile.BaseStream.Position < mine.logplaybackfile.BaseStream.Length)
                    {
                        MAVLink.MAVLinkMessage packet = mine.readPacket();

                        cs.datetime = mine.lastlogread;

                        cs.UpdateCurrentSettings(null, true, mine);

                        // check for valid lock
                        if (!(cs.gpsstatus >=3 || cs.gpsstatus2 >= 3))
                            continue;

                        VehicleLocation location = new VehicleLocation();
                        location.Time = cs.datetime;
                        location.Lat = cs.lat;
                        location.Lon = cs.lng;
                        location.RelAlt = cs.alt;
                        location.AltAMSL = cs.altasl;

                        location.Roll = cs.roll;
                        location.Pitch = cs.pitch;
                        location.Yaw = cs.yaw;

                        location.SAlt = cs.sonarrange;

                        vehiclePositionList[ToMilliseconds(location.Time)] = location;
                        // 4 5 7
                        Console.Write((mine.logplaybackfile.BaseStream.Position*100/
                                       mine.logplaybackfile.BaseStream.Length) + "    \r");
                    }
                    mine.logplaybackfile.Close();
                }
            }
            // DataFlash Log
            else
            {
                using (var sr = new CollectionBuffer(File.OpenRead(fn)))
                {
                    // Will hold the last seen Attitude information in order to incorporate them into the GPS Info
                    float currentYaw = 0f;
                    float currentRoll = 0f;
                    float currentPitch = 0f;
                    float currentSAlt = 0f;

                    foreach (var item in sr.GetEnumeratorType(new string[] { "GPS", "GPS2", "ATT", "CTUN", "RFND" }))
                    {
                        // Look for GPS Messages. However GPS Messages do not have Roll, Pitch and Yaw
                        // So we have to look for one ATT message after having read a GPS one

                        var gpstouse = UseGpsorGPS2();

                        if (item.msgtype == gpstouse)
                        {
                            if (!sr.dflog.logformat.ContainsKey(gpstouse))
                                continue;

                            int latindex = sr.dflog.FindMessageOffset(gpstouse, "Lat");
                            int lngindex = sr.dflog.FindMessageOffset(gpstouse, "Lng");
                            int altindex = sr.dflog.FindMessageOffset(gpstouse, "Alt");
                            int statusindex = sr.dflog.FindMessageOffset(gpstouse, "Status");
                            int raltindex = sr.dflog.FindMessageOffset(gpstouse, "RAlt");
                            if (raltindex == -1)
                                raltindex = sr.dflog.FindMessageOffset(gpstouse, "RelAlt");

                            VehicleLocation location = new VehicleLocation();

                            try
                            {
                                location.Time = item.time;

                                if (statusindex != -1)
                                {
                                    // check for valid lock
                                    if (double.Parse(item.items[statusindex], CultureInfo.InvariantCulture) < 3)
                                        continue;
                                }
                                if (latindex != -1)
                                    location.Lat = double.Parse(item.items[latindex], CultureInfo.InvariantCulture);
                                if (lngindex != -1)
                                    location.Lon = double.Parse(item.items[lngindex], CultureInfo.InvariantCulture);
                                if (raltindex != -1)
                                    location.RelAlt = double.Parse(item.items[raltindex], CultureInfo.InvariantCulture);
                                if (altindex != -1)
                                    location.AltAMSL = double.Parse(item.items[altindex], CultureInfo.InvariantCulture);

                                location.Roll = currentRoll;
                                location.Pitch = currentPitch;
                                location.Yaw = currentYaw;

                                location.SAlt = currentSAlt;

                                long millis = ToMilliseconds(location.Time);

                                //System.Diagnostics.Debug.WriteLine("GPS MSG - UTCMillis = " + millis  + "  GPS Week = " + getValueFromStringArray(gpsLineValues, gpsweekpos) + "  TimeMS = " + getValueFromStringArray(gpsLineValues, timepos));

                                if (!vehiclePositionList.ContainsKey(millis) && (location.Time != DateTime.MinValue))
                                    vehiclePositionList[millis] = location;
                            }
                            catch
                            {
                                Console.WriteLine("Bad "+gpstouse+" Line");
                            }
                        }
                        else if (item.msgtype == "ATT")
                        {
                            int Rindex = sr.dflog.FindMessageOffset("ATT", "Roll");
                            int Pindex = sr.dflog.FindMessageOffset("ATT", "Pitch");
                            int Yindex = sr.dflog.FindMessageOffset("ATT", "Yaw");

                            if (Rindex != -1)
                                currentRoll = float.Parse(item.items[Rindex], CultureInfo.InvariantCulture);
                            if (Pindex != -1)
                                currentPitch = float.Parse(item.items[Pindex], CultureInfo.InvariantCulture);
                            if (Yindex != -1)
                                currentYaw = float.Parse(item.items[Yindex], CultureInfo.InvariantCulture);
                        }
                        else if (item.msgtype == "CTUN")
                        {
                            int SAltindex = sr.dflog.FindMessageOffset("CTUN", "SAlt");

                            if (SAltindex != -1)
                            {
                                currentSAlt = float.Parse(item.items[SAltindex], CultureInfo.InvariantCulture);
                            }
                        }
                        else if (item.msgtype == "RFND")
                        {
                            int SAltindex = sr.dflog.FindMessageOffset("RFND", "Dist1");

                            if (SAltindex != -1)
                            {
                                currentSAlt = float.Parse(item.items[SAltindex], CultureInfo.InvariantCulture);
                            }
                        }
                    }
                }
            }

            return vehiclePositionList;
        }
Exemple #19
0
        private void FindSectionThread()
        {
            VehicleLocation newVehicleLocation = new VehicleLocation();
            string          sectionID          = localData.Location.NowSection;
            string          addressID          = localData.Location.LastAddress;
            MapAGVPosition  now = localData.Real;
            MapPosition     temp;
            MapSection      section;
            double          distanceToHead;
            double          distanceToTail;

            if (now == null)
            {
                return;
            }

            if (localData.TheMapInfo.AllSection.ContainsKey(sectionID))
            {
                #region 是否還在目前Section內 (判斷條件 : 頭尾不能超出,寬度為MoveControlConfig.SectionRange 預設是50mm, 非RTurn且 角度誤差在MoveControlConfig.SectionAllowDeltaTheta 預設是5度).
                section = localData.TheMapInfo.AllSection[sectionID];
                temp    = computeFunction.GetTransferPosition(section, now.Position);

                if (0 <= temp.X && temp.X <= section.Distance && Math.Abs(temp.Y) <= localData.MoveControlData.MoveControlConfig.SectionRange &&
                    Math.Abs(computeFunction.GetCurrectAngle(section.FromVehicleAngle - now.Angle)) <= localData.MoveControlData.MoveControlConfig.SectionAllowDeltaTheta)
                {
                    if (section.FromVehicleAngle == section.ToVehicleAngle)
                    {
                        if (Math.Abs(computeFunction.GetCurrectAngle(section.FromVehicleAngle - now.Angle)) <= localData.MoveControlData.MoveControlConfig.SectionAllowDeltaTheta)
                        {
                            localData.Location.DistanceFormSectionHead = temp.X;

                            distanceToHead = temp.X;
                            distanceToTail = section.Distance - temp.X;

                            if (distanceToHead <= localData.MoveControlData.MoveControlConfig.InPositionRange && distanceToHead <= distanceToTail)
                            {
                                localData.Location.InAddress   = true;
                                localData.Location.LastAddress = section.FromAddress.Id;
                            }
                            else if (distanceToTail <= localData.MoveControlData.MoveControlConfig.InPositionRange && distanceToTail <= distanceToHead)
                            {
                                localData.Location.InAddress   = true;
                                localData.Location.LastAddress = section.ToAddress.Id;
                            }
                            else
                            {
                                localData.Location.InAddress = false;
                            }

                            WriteLog(7, "", String.Concat("Section不變更 : ", sectionID));
                            localData.LastAGVPosition = now;
                            return;
                        }
                    }
                }
                #endregion

                #region 搜尋是否在相鄰Section內 (判斷條件 : 頭尾不能超出,寬度為MoveControlConfig.SectionRange 預設是50mm, 非RTurn且 角度誤差在MoveControlConfig.SectionAllowDeltaTheta 預設是5度).
                for (int i = 0; i < localData.TheMapInfo.AllSection[sectionID].NearbySection.Count; i++)
                {
                    section = localData.TheMapInfo.AllSection[sectionID].NearbySection[i];

                    if (section.FromVehicleAngle == section.ToVehicleAngle)
                    {
                        temp = computeFunction.GetTransferPosition(section, now.Position);

                        if (0 <= temp.X && temp.X <= section.Distance && Math.Abs(temp.Y) <= localData.MoveControlData.MoveControlConfig.SectionRange &&
                            Math.Abs(computeFunction.GetCurrectAngle(section.FromVehicleAngle - now.Angle)) <= localData.MoveControlData.MoveControlConfig.SectionAllowDeltaTheta)
                        {
                            if (Math.Abs(computeFunction.GetCurrectAngle(section.FromVehicleAngle - now.Angle)) <= localData.MoveControlData.MoveControlConfig.SectionAllowDeltaTheta)
                            {
                                newVehicleLocation.DistanceFormSectionHead = temp.X;
                                newVehicleLocation.NowSection = section.Id;

                                distanceToHead = temp.X;
                                distanceToTail = section.Distance - temp.X;

                                if (distanceToHead <= localData.MoveControlData.MoveControlConfig.InPositionRange && distanceToHead <= distanceToTail)
                                {
                                    newVehicleLocation.InAddress   = true;
                                    newVehicleLocation.LastAddress = section.FromAddress.Id;
                                }
                                else if (distanceToTail <= localData.MoveControlData.MoveControlConfig.InPositionRange && distanceToTail <= distanceToHead)
                                {
                                    newVehicleLocation.InAddress   = true;
                                    newVehicleLocation.LastAddress = section.ToAddress.Id;
                                }
                                else
                                {
                                    newVehicleLocation.InAddress = false;

                                    if (section.FromAddress == localData.TheMapInfo.AllSection[sectionID].FromAddress ||
                                        section.FromAddress == localData.TheMapInfo.AllSection[sectionID].ToAddress)
                                    {
                                        newVehicleLocation.LastAddress = section.FromAddress.Id;
                                    }
                                    else
                                    {
                                        newVehicleLocation.LastAddress = section.ToAddress.Id;
                                    }
                                }

                                localData.Location = newVehicleLocation;
                                WriteLog(7, "", String.Concat("切換Section(相鄰) : ", newVehicleLocation.NowSection));
                                localData.LastAGVPosition = now;
                                return;
                            }
                        }
                    }
                }
                #endregion
            }

            #region Find All (條件 : 頭尾可超出 MoveControlConfig.SectionRange 預設是50mm, 寬度在MoveControlConfig.SectionWidthRange 預設是500mm, 非RTurn且 角度誤差在MoveControlConfig.SectionAllowDeltaTheta 預設是5度 中 找尋數值最接近的)
            MapSection  minSection  = null;
            MapPosition minPosition = null;
            double      min         = -1;
            double      tempMin;
            double      deltaAngle;

            foreach (MapSection tempSection in localData.TheMapInfo.AllSection.Values)
            {
                if (tempSection.FromVehicleAngle == tempSection.ToVehicleAngle)
                {
                    temp = computeFunction.GetTransferPosition(tempSection, now.Position);

                    if (-localData.MoveControlData.MoveControlConfig.SectionRange <= temp.X && temp.X <= (tempSection.Distance + localData.MoveControlData.MoveControlConfig.SectionRange) &&
                        Math.Abs(temp.Y) <= localData.MoveControlData.MoveControlConfig.SectionWidthRange)
                    {
                        deltaAngle = Math.Abs(computeFunction.GetCurrectAngle(tempSection.FromVehicleAngle - now.Angle));

                        tempMin = Math.Abs(temp.Y) + deltaAngle * 50;

                        if (temp.X < 0)
                        {
                            tempMin = tempMin - temp.X;
                        }
                        else if (temp.X > tempSection.Distance)
                        {
                            tempMin = tempMin + temp.X - tempSection.Distance;
                        }

                        if (min == -1 || tempMin < min)
                        {
                            min         = tempMin;
                            minSection  = tempSection;
                            minPosition = temp;
                        }
                    }
                }
            }

            if (min == -1)
            {
                if (localData.MoveControlData.MoveControlConfig.LosePositionSetNullAddressSection)
                {
                    newVehicleLocation.DistanceFormSectionHead = 0;
                    newVehicleLocation.LastAddress             = "";
                    newVehicleLocation.NowSection = "";
                    newVehicleLocation.InAddress  = false;

                    localData.Location = newVehicleLocation;
                }

                WriteLog(3, "", String.Concat("目前位置 : ", computeFunction.GetMapAGVPositionStringWithAngle(now), " 搜尋不到所在Section"));
                localData.LastAGVPosition = now;
            }
            else
            {
                newVehicleLocation.NowSection = minSection.Id;

                if (minPosition.X < 0)
                {
                    newVehicleLocation.DistanceFormSectionHead = 0;
                }
                else if (minPosition.X > minSection.Distance)
                {
                    newVehicleLocation.DistanceFormSectionHead = minSection.Distance;
                }
                else
                {
                    newVehicleLocation.DistanceFormSectionHead = minPosition.X;
                }

                distanceToHead = Math.Abs(minPosition.X);
                distanceToTail = Math.Abs(minSection.Distance - minPosition.X);

                if (distanceToHead <= localData.MoveControlData.MoveControlConfig.InPositionRange && distanceToHead <= distanceToTail)
                {
                    newVehicleLocation.LastAddress = minSection.FromAddress.Id;
                    newVehicleLocation.InAddress   = true;
                }
                else if (distanceToTail < localData.MoveControlData.MoveControlConfig.InPositionRange && distanceToTail < distanceToHead)
                {
                    newVehicleLocation.LastAddress = minSection.ToAddress.Id;
                    newVehicleLocation.InAddress   = true;
                }
                else
                {
                    if (distanceToHead <= distanceToTail)
                    {
                        newVehicleLocation.LastAddress = minSection.FromAddress.Id;
                    }
                    else
                    {
                        newVehicleLocation.LastAddress = minSection.ToAddress.Id;
                    }

                    newVehicleLocation.InAddress = false;
                }

                localData.Location = newVehicleLocation;
                WriteLog(7, "", String.Concat("切換Section(All) : ", newVehicleLocation.NowSection));
                localData.LastAGVPosition = now;
            }
            #endregion
        }
        private void MiidlerInfo()
        {
            /// 充電相關資訊.
            ///
            bool 正在充電 = localData.MIPCData.Charging;
            /// SOC
            double soc      = localData.BatteryInfo.SOC;
            double 到站充電高水位  = localData.MIPCData.Config.ChargingSOC_High;
            double 在站點上充電水位 = localData.MIPCData.Config.ChargingSOC_Low;

            /// 這邊訊號在充電送出成功時就會on,會做delay,middler不用再做delay.
            /// 開始充電、結束充電.
            StartChargingByAddressID("48001??");
            StopCharging();

            /// 上報位置相關.

            /// 目前位置(座標)
            MapAGVPosition nowPosition = localData.Real;

            /// 這邊迷航是會是null 但如果config設定迷航時殘留上次數值,就會迷航前的資料.
            if (nowPosition != null)
            {
                double x     = nowPosition.Position.X;
                double y     = nowPosition.Position.Y;
                double angle = nowPosition.Angle;
            }

            double 移動方向  = localData.MoveDirectionAngle;
            double 移動速度  = localData.MoveControlData.MotionControlData.LineVelocity;
            bool   避車停止  = localData.MoveControlData.ReserveStop;
            bool   障礙物停止 = localData.MoveControlData.SafetySensorStop;

            bool AlarmBit = AlarmHandler.HasAlarm;

            bool Auto中 = (localData.AutoManual == EnumAutoState.Auto);

            /// Address Section Distance.

            VehicleLocation nowVehicleLocation = localData.Location;

            string NowSection = nowVehicleLocation.NowSection;
            /// 迷航時為空白.
            string LastAddress = nowVehicleLocation.LastAddress;
            /// 迷航時為空白.
            ///
            bool 是否在LastAddress上 = nowVehicleLocation.InAddress;

            double distance = nowVehicleLocation.DistanceFormSectionHead;


            /// 走行相關.
            /// 移動命令
            ///
            bool 現在可以下命令 = localData.MoveControlData.Ready && !localData.MoveControlData.ErrorBit;
            /// ErrorBit理論上等同AlarmHandler.HasAlarm,因此應該不會發生兩邊狀態不一致.

            bool 現在MoveControl有命令 = (localData.MoveControlData.MoveCommand != null);

            string errorMessage = "";

            MoveControl.VehicleMove(null, ref errorMessage);
            /// 這樣好了 你呼叫的地方就先打null沒關係 只是上面要有三行
            string        CommandID = "???";
            List <string> movingAddressList;
            List <string> movingSectionList;

            /// 停車.
            MoveControl.VehicleStop();

            /// Pause.Continue.

            MoveControl.VehiclePause();
            MoveControl.VehicleContinue();

            /// Cancel 下了會自己先pause在Stop.

            MoveControl.VehicleCancel();

            /// Override需要自己寫.



            /// 下面一個為完成上報,一個為過站上報.
            /// MoveControl.MoveCompleteEvent += MoveControl_MoveComplete;
            /// MoveControl.PassAddressEvent += MoveControl_PassAddress;



            /// 取放相關.
            /// 開始命令
            ///

            bool Fork現在可以下命令 = localData.LoadUnloadData.Ready && !localData.LoadUnloadData.ErrorBit;

            /// 可以視為友達版本的ForkHome訊號.

            /// LoadUnloadCommand(addressID, load or unload)
            /// return true = 開始執行, false = 無法執行
            ///
            /// 應該不會需要停止, 停止這樣下.
            /// 這邊要考慮一下 取放貨到底能不能中斷.
            StopLoadUnload();

            ///
            /// 取放 結束Event
            /// LoadUnloadControl.ForkCompleteEvent
            ///

            /// 更新loading 和CSTID
            UpdateLoadingAndCSTID();
            bool   臺車有貨物 = localData.LoadUnloadData.Loading;
            string 卡夾ID  = localData.LoadUnloadData.CstID;
        }
Exemple #21
0
        private void UpdateAddressSection_ManualMode()
        {
            if (localData.Real != null && localData.LastAGVPosition != null)
            {
                double distance = computeFunction.GetTwoPositionDistance(localData.Real, localData.LastAGVPosition);

                if (distance <= localData.MoveControlData.MoveControlConfig.InPositionRange && Math.Abs(computeFunction.GetCurrectAngle(localData.Real.Angle - localData.LastAGVPosition.Angle)) <= localData.MoveControlData.MoveControlConfig.SectionAllowDeltaTheta)
                {
                    lastFindSectionTime = DateTime.Now;

                    string sectionID = localData.Location.NowSection;

                    if (localData.TheMapInfo.AllSection.ContainsKey(sectionID))
                    {
                        if (localData.TheMapInfo.AllSection[sectionID].FromVehicleAngle == localData.TheMapInfo.AllSection[sectionID].ToVehicleAngle)
                        {
                            MapPosition temp = computeFunction.GetTransferPosition(localData.TheMapInfo.AllSection[sectionID], localData.Real.Position);

                            double sectionDeviation = temp.Y;
                            double theta            = computeFunction.GetCurrectAngle(localData.Real.Angle - localData.TheMapInfo.AllSection[sectionID].FromVehicleAngle);
                            thetaSectionDeviation = new ThetaSectionDeviation(theta, sectionDeviation);
                        }
                    }

                    return;
                }
            }

            if (localData.Real == null)
            {
                if (localData.MoveControlData.MoveControlConfig.LosePositionSetNullAddressSection)
                {
                    localData.Location = new VehicleLocation();
                }
            }
            else
            {
                if ((DateTime.Now - lastFindSectionTime).TotalMilliseconds > localData.MoveControlData.MoveControlConfig.TimeValueConfig.IntervalTimeList[EnumIntervalTimeType.ManualFindSectionInterval])
                {
                    lastFindSectionTime = DateTime.Now;

                    if (findSectionThread == null || !findSectionThread.IsAlive)
                    {
                        findSectionThread = new Thread(FindSectionThread);
                        findSectionThread.Start();
                    }
                    else
                    {
                        WriteLog(3, "", String.Concat("Find now Section Interval : ", localData.MoveControlData.MoveControlConfig.TimeValueConfig.IntervalTimeList[EnumIntervalTimeType.ManualFindSectionInterval].ToString("0"), ", 上一次搜尋還未結束"));
                    }
                }
                else
                {
                    VehicleLocation oldLocate = localData.Location;

                    if (localData.TheMapInfo.AllSection.ContainsKey(oldLocate.NowSection))
                    {
                        VehicleLocation newLocate = new VehicleLocation();
                        newLocate.NowSection = oldLocate.NowSection;
                        MapPosition temp = computeFunction.GetTransferPosition(localData.TheMapInfo.AllSection[oldLocate.NowSection], localData.Real.Position);

                        if (Math.Abs(temp.X) <= localData.MoveControlData.MoveControlConfig.InPositionRange)
                        {
                            newLocate.InAddress   = true;
                            newLocate.LastAddress = localData.TheMapInfo.AllSection[oldLocate.NowSection].FromAddress.Id;
                        }
                        else if (Math.Abs(localData.TheMapInfo.AllSection[oldLocate.NowSection].Distance - temp.X) <= localData.MoveControlData.MoveControlConfig.InPositionRange)
                        {
                            newLocate.InAddress   = true;
                            newLocate.LastAddress = localData.TheMapInfo.AllSection[oldLocate.NowSection].ToAddress.Id;
                        }
                        else
                        {
                            newLocate.LastAddress = oldLocate.LastAddress;
                        }

                        if (temp.X < 0)
                        {
                            temp.X = 0;
                        }
                        else if (temp.X > localData.TheMapInfo.AllSection[oldLocate.NowSection].Distance)
                        {
                            temp.X = localData.TheMapInfo.AllSection[oldLocate.NowSection].Distance;
                        }

                        newLocate.DistanceFormSectionHead = temp.X;

                        double sectionDeviation = temp.Y;
                        double theta            = computeFunction.GetCurrectAngle(localData.Real.Angle - localData.TheMapInfo.AllSection[oldLocate.NowSection].FromVehicleAngle);
                        thetaSectionDeviation = new ThetaSectionDeviation(theta, sectionDeviation);

                        localData.Location = newLocate;
                    }
                }
            }
        }
Exemple #22
0
        private void UpdateAddressSection_MoveControlMovingFlow(SectionLine sectionLine)
        {
            if (sectionLine == null || localData.Real == null)
            {
                return;
            }

            VehicleLocation newVehicleLocation = new VehicleLocation();

            if (localData.MoveControlData.MoveCommand.CommandStatus == EnumMoveCommandStartStatus.Reporting)
            {
                newVehicleLocation.LastAddress = localData.Location.LastAddress;
                newVehicleLocation.InAddress   = localData.Location.InAddress;
            }
            else
            {
                if (localData.TheMapInfo.AllAddress.ContainsKey(sectionLine.Start.Id))
                {
                    newVehicleLocation.LastAddress = sectionLine.Start.Id;
                }
                else
                {
                    newVehicleLocation.LastAddress = localData.Location.LastAddress;
                }
            }

            newVehicleLocation.NowSection = sectionLine.Section.Id;

            MapPosition temp;

            if (localData.MoveControlData.LocateControlData.LocateAGVPosition != null)
            {
                temp = computeFunction.GetTransferPosition(sectionLine.Section, localData.MoveControlData.LocateControlData.LocateAGVPosition.AGVPosition.Position);
            }
            else
            {
                temp = computeFunction.GetTransferPosition(sectionLine.Section, localData.Real.Position);
            }

            //MapPosition temp = computeFunction.GetTransferPosition(sectionLine.Section, localData.Real.Position);

            if (temp.X < 0)
            {
                newVehicleLocation.DistanceFormSectionHead = 0;
            }
            else if (temp.X > sectionLine.Section.Distance)
            {
                newVehicleLocation.DistanceFormSectionHead = sectionLine.Section.Distance;
            }
            else
            {
                newVehicleLocation.DistanceFormSectionHead = temp.X;
            }

            if (Math.Abs(temp.X) <= localData.MoveControlData.MoveControlConfig.InPositionRange)
            {
                newVehicleLocation.InAddress = true;
            }
            else
            {
                newVehicleLocation.InAddress = false;
            }

            if (localData.MoveControlData.MoveCommand.MoveStatus == EnumMoveStatus.Moving)
            {
                double sectionDeviation = temp.Y;
                double theta            = computeFunction.GetCurrectAngle(localData.Real.Angle - sectionLine.Section.FromVehicleAngle);

                thetaSectionDeviation = new ThetaSectionDeviation(theta, sectionDeviation);
            }

            localData.MoveControlData.MoveCommand.CommandEncoder = sectionLine.EncoderAddSectionDistanceStart + (sectionLine.SectionDirFlag ? temp.X : -temp.X);

            localData.Location = newVehicleLocation;

            localData.LastAGVPosition = localData.Real;
        }
Exemple #23
0
        /// <summary>
        /// Return a list of all cam messages in a log with timestamp
        /// </summary>
        /// <param name="fn"></param>
        /// <returns></returns>
        private Dictionary<long, VehicleLocation> readCAMMsgInLog(string fn)
        {
            Dictionary<long, VehicleLocation> list = new Dictionary<long, VehicleLocation>();

            if (fn.ToLower().EndsWith("tlog"))
                return null;

            // convert bin to log
            if (fn.ToLower().EndsWith("bin"))
            {
                string tempfile = Path.GetTempFileName();
                Log.BinaryLog.ConvertBin(fn, tempfile);
                fn = tempfile;
            }

            using (StreamReader sr = new StreamReader(fn))
            {
                int a = 0;
                while (!sr.EndOfStream)
                {
                    a++;
                    string line = sr.ReadLine();

                    var item = dflog.GetDFItemFromLine(line, a);

                    if (item.msgtype == "CAM")
                    {
                        int latindex = dflog.FindMessageOffset("CAM", "Lat");
                        int lngindex = dflog.FindMessageOffset("CAM", "Lng");
                        int altindex = dflog.FindMessageOffset("CAM", "Alt");
                        int raltindex = dflog.FindMessageOffset("CAM", "RelAlt");

                        int rindex = dflog.FindMessageOffset("CAM", "Roll");
                        int pindex = dflog.FindMessageOffset("CAM", "Pitch");
                        int yindex = dflog.FindMessageOffset("CAM", "Yaw");

                        int gtimeindex = dflog.FindMessageOffset("CAM", "GPSTime");
                        int gweekindex = dflog.FindMessageOffset("CAM", "GPSWeek");

                        VehicleLocation p = new VehicleLocation();

                        p.Time = GetTimeFromGps(int.Parse(item.items[gweekindex], CultureInfo.InvariantCulture),
                            int.Parse(item.items[gtimeindex], CultureInfo.InvariantCulture));

                        p.Lat = double.Parse(item.items[latindex], CultureInfo.InvariantCulture);
                        p.Lon = double.Parse(item.items[lngindex], CultureInfo.InvariantCulture);
                        p.AltAMSL = double.Parse(item.items[altindex], CultureInfo.InvariantCulture);
                        p.RelAlt = double.Parse(item.items[raltindex], CultureInfo.InvariantCulture);

                        p.Pitch = float.Parse(item.items[pindex], CultureInfo.InvariantCulture);
                        p.Roll = float.Parse(item.items[rindex], CultureInfo.InvariantCulture);
                        p.Yaw = float.Parse(item.items[yindex], CultureInfo.InvariantCulture);

                        list[ToMilliseconds(p.Time)] = p;
                    }
                }
            }
            return list;
        }
Exemple #24
0
        async private Task <DateTime> GetFirstSustainedTriggerTime(string fn)
        {
            DateTime SusTrigTime = new DateTime();

            Dictionary <long, VehicleLocation> vehicletriggerList = new Dictionary <long, VehicleLocation>();

            // Telemetry Log
            if (fn.ToLower().EndsWith("tlog"))
            {
                System.IO.FileStream logplaybackfile = new System.IO.FileStream(fn, FileMode.Open);

                MAVLinkInterface mine = new MAVLinkInterface(logplaybackfile);

                bool WasLastOn = false;

                MissionPlanner.CurrentState cs = new MissionPlanner.CurrentState();

                while (mine.logplaybackfile.BaseStream.Position < mine.logplaybackfile.BaseStream.Length)
                {
                    MAVLink.MAVLinkMessage packet = mine.readPacket();

                    cs.datetime = mine.lastlogread;

                    cs.UpdateCurrentSettings(null, true, mine);

                    VehicleLocation location = new VehicleLocation();
                    location.Time = cs.datetime;
                    bool tmponval = false;

                    if (((cs.ch7in > 1520) || (cs.ch7in < 1480)) && (cs.ch7in != 0)) //if ch7 val is not default we assume camera is on
                    {
                        tmponval = true;
                        if (!WasLastOn)
                        {
                            SusTrigTime = cs.datetime;
                        }
                        else
                        {
                            // logic to check if we have a sustained trigger
                            System.TimeSpan SusTime    = cs.datetime - SusTrigTime;
                            double          Sustimesec = SusTime.TotalSeconds;

                            if (Sustimesec > 30)
                            {
                                mine.logplaybackfile.Close();
                                return(SusTrigTime);
                            }
                        }
                        WasLastOn = true;
                    }
                    else
                    {
                        if (cs.ch7in != 0)
                        {
                            tmponval = false;
                            if (WasLastOn)
                            {
                                // logic to check if we have a sustained trigger
                                System.TimeSpan SusTime    = cs.datetime - SusTrigTime;
                                double          Sustimesec = SusTime.TotalSeconds;

                                if (Sustimesec > 30)
                                {
                                    mine.logplaybackfile.Close();
                                    return(SusTrigTime);
                                }
                            }
                        }
                        WasLastOn = false;
                    }
                }
                mine.logplaybackfile.Close();
            }
            return(SusTrigTime);
        }
        public IActionResult UpdateLocation([FromBody] VehicleLocation vehiclelocation)
        {
            List <ServiceDetails> serviceDetail = new List <ServiceDetails>();

            string Action = "Update";

            try
            {
                if (vehiclelocation.LocationID <= 0 || vehiclelocation.LocationID == null)
                {
                    return(StatusCode((int)HttpStatusCode.BadRequest, new { error = new { message = "Please enter a LocationID" } }));
                }
                else if (vehiclelocation.VehicleId <= 0 || vehiclelocation.VehicleId == null)
                {
                    return(StatusCode((int)HttpStatusCode.BadRequest, new { error = new { message = "Please enter a VehicleId" } }));
                }
                //else if (vehiclelocation.LocationLatitude == "" || vehiclelocation.LocationLatitude == "string" || vehiclelocation.LocationLatitude == null)
                //{
                //    return StatusCode((int)HttpStatusCode.BadRequest, new { error = new { message = "Please enter a Latitude value" } });
                //}
                //else if (vehiclelocation.LocationLongitude == "" || vehiclelocation.LocationLongitude == "string" || vehiclelocation.LocationLongitude == null)
                //{
                //    return StatusCode((int)HttpStatusCode.BadRequest, new { error = new { message = "Please enter a Longitude value" } });
                //}
                else if (vehiclelocation.CityName == "" || vehiclelocation.CityName == "string" || vehiclelocation.CityName == null)
                {
                    return(StatusCode((int)HttpStatusCode.BadRequest, new { error = new { message = "Please enter a CityName" } }));
                }
                else
                {
                    DataSet dt  = Data.Vehicles.SaveLocation(vehiclelocation, Action);
                    string  row = dt.Tables[0].Rows[0]["ErrorMessage"].ToString();

                    if (row == "Success")
                    {
                        return(StatusCode((int)HttpStatusCode.OK, "Updated Successfully"));
                    }
                    else
                    {
                        //return "Invalid";
                        return(StatusCode((int)HttpStatusCode.Forbidden, new { error = new { message = row } }));
                    }
                }

                //if (row == "Success")
                //{
                //    ServiceAmount amt = new ServiceAmount();

                //    if (dt.Tables[1].Rows.Count > 0)
                //    {

                //        for (int i = 0; i < dt.Tables[1].Rows.Count; i++)
                //        {
                //            ServiceDetails service = new ServiceDetails();
                //            service.ServiceID = (dt.Tables[1].Rows[i]["ServiceID"] == DBNull.Value ? 0 : (int)dt.Tables[1].Rows[i]["ServiceID"]);
                //            //service.ServicePlanID = (dt.Tables[1].Rows[i]["ServicePlanID"] == DBNull.Value ? 0 : (int)dt.Tables[1].Rows[i]["ServicePlanID"]);
                //            service.ServicePriceChartId = (dt.Tables[1].Rows[i]["ServicePriceChartId"] == DBNull.Value ? 0 : (int)dt.Tables[1].Rows[i]["ServicePriceChartId"]);
                //            service.PlanType = (dt.Tables[1].Rows[i]["PlanType"] == DBNull.Value ? "-" : dt.Tables[1].Rows[i]["PlanType"].ToString());
                //            service.Price = (dt.Tables[1].Rows[i]["Price"] == DBNull.Value ? 0 : (decimal)dt.Tables[1].Rows[i]["Price"]);
                //            service.VehicleId = (dt.Tables[1].Rows[i]["VehicleId"] == DBNull.Value ? 0 : (int)dt.Tables[1].Rows[i]["VehicleId"]);
                //            service.UserId = (dt.Tables[1].Rows[i]["UserId"] == DBNull.Value ? 0 : (int)dt.Tables[1].Rows[i]["UserId"]);
                //            //service.RemainderMinutes = (dt.Tables[1].Rows[i]["RemainderMinutes"] == DBNull.Value ? 0 : (int)dt.Tables[1].Rows[i]["RemainderMinutes"]);
                //            //service.LocationID = (dt.Tables[1].Rows[i]["LocationID"] == DBNull.Value ? 0 : (int)dt.Tables[1].Rows[i]["LocationID"]);
                //            //service.IsTeamsandConditionsAccepted = (dt.Tables[1].Rows[i]["IsTeamsandConditionsAccepted"] == DBNull.Value ? false : (bool)dt.Tables[1].Rows[i]["IsTeamsandConditionsAccepted"]);
                //            service.PromoCodeApplied = (dt.Tables[1].Rows[i]["PromoCodeApplied"] == DBNull.Value ? false : (bool)dt.Tables[1].Rows[i]["PromoCodeApplied"]);
                //            service.Status = (dt.Tables[1].Rows[i]["Status"] == DBNull.Value ? "-" : dt.Tables[1].Rows[i]["Status"].ToString());
                //            service.ScheduleID = (dt.Tables[1].Rows[i]["ScheduleID"] == DBNull.Value ? 0 : (int)dt.Tables[1].Rows[i]["ScheduleID"]);
                //            service.RequestedServiceDate = (dt.Tables[1].Rows[i]["RequestedServiceDate"] == DBNull.Value ? "-" : dt.Tables[1].Rows[i]["RequestedServiceDate"].ToString());
                //            service.ActualServiceDate = (dt.Tables[1].Rows[i]["ActualServiceDate"] == DBNull.Value ? "-" : dt.Tables[1].Rows[i]["ActualServiceDate"].ToString());
                //            service.ServiceOutDate = (dt.Tables[1].Rows[i]["ServiceOutDate"] == DBNull.Value ? "-" : dt.Tables[1].Rows[i]["ServiceOutDate"].ToString());
                //            service.ServiceName = (dt.Tables[1].Rows[i]["ServiceName"] == DBNull.Value ? "-" : dt.Tables[1].Rows[i]["ServiceName"].ToString());
                //            service.Description = (dt.Tables[1].Rows[i]["Description"] == DBNull.Value ? "-" : dt.Tables[1].Rows[i]["Description"].ToString());
                //            service.IsAvailable = (dt.Tables[1].Rows[i]["IsAvailable"] == DBNull.Value ? false : (bool)dt.Tables[1].Rows[i]["IsAvailable"]);

                //            serviceDetail.Add(service);
                //        }

                //        if (dt.Tables[2].Rows.Count > 0)
                //        {
                //            amt.TotalAmount = (dt.Tables[2].Rows[0]["TotalAmount"] == DBNull.Value ? 0 : (decimal)dt.Tables[2].Rows[0]["TotalAmount"]);
                //        }
                //    }

                //    return StatusCode((int)HttpStatusCode.OK, new { serviceDetail, amt });

                //}

                //else
                //{
                //    return StatusCode((int)HttpStatusCode.Forbidden, new { error = new { message = row } });
                //}
            }

            catch (Exception e)
            {
                string SaveErrorLog = Data.Common.SaveErrorLog("UpdateLocation", e.Message);

                return(StatusCode((int)HttpStatusCode.InternalServerError, new { error = new { message = e.Message.ToString() } }));
            }
        }
Exemple #26
0
        /// <summary>
        /// Return a list of all gps messages with there timestamp from the log
        /// </summary>
        /// <param name="fn"></param>
        /// <returns></returns>
        private Dictionary<long, VehicleLocation> readGPSMsgInLog(string fn)
        {
            Dictionary<long, VehicleLocation> vehiclePositionList = new Dictionary<long, VehicleLocation>();

            // Telemetry Log
            if (fn.ToLower().EndsWith("tlog"))
            {
                using (MAVLinkInterface mine = new MAVLinkInterface())
                {
                    mine.logplaybackfile =
                        new BinaryReader(File.Open(fn, FileMode.Open, FileAccess.Read, FileShare.Read));
                    mine.logreadmode = true;

                    mine.MAV.packets.Initialize(); // clear

                    CurrentState cs = new CurrentState();

                    while (mine.logplaybackfile.BaseStream.Position < mine.logplaybackfile.BaseStream.Length)
                    {
                        byte[] packet = mine.readPacket();

                        cs.datetime = mine.lastlogread;

                        cs.UpdateCurrentSettings(null, true, mine);

                        VehicleLocation location = new VehicleLocation();
                        location.Time = cs.datetime;
                        location.Lat = cs.lat;
                        location.Lon = cs.lng;
                        location.RelAlt = cs.alt;
                        location.AltAMSL = cs.altasl;

                        location.Roll = cs.roll;
                        location.Pitch = cs.pitch;
                        location.Yaw = cs.yaw;

                        vehiclePositionList[ToMilliseconds(location.Time)] = location;
                        // 4 5 7
                        Console.Write((mine.logplaybackfile.BaseStream.Position*100/
                                       mine.logplaybackfile.BaseStream.Length) + "    \r");
                    }
                    mine.logplaybackfile.Close();
                }
            }
            // DataFlash Log
            else
            {
                // convert bin to log
                if (fn.ToLower().EndsWith("bin"))
                {
                    string tempfile = Path.GetTempFileName();
                    Log.BinaryLog.ConvertBin(fn, tempfile);
                    fn = tempfile;
                }

                using (StreamReader sr = new StreamReader(fn))
                {
                    // Will hold the last seen Attitude information in order to incorporate them into the GPS Info
                    float currentYaw = 0f;
                    float currentRoll = 0f;
                    float currentPitch = 0f;
                    int a = 0;

                    while (!sr.EndOfStream)
                    {
                        a++;
                        string line = sr.ReadLine();

                        var item = dflog.GetDFItemFromLine(line, a);
                        // Look for GPS Messages. However GPS Messages do not have Roll, Pitch and Yaw
                        // So we have to look for one ATT message after having read a GPS one

                        if (item.msgtype == "GPS")
                        {
                            if (!dflog.logformat.ContainsKey("GPS"))
                                continue;

                            int latindex = dflog.FindMessageOffset("GPS", "Lat");
                            int lngindex = dflog.FindMessageOffset("GPS", "Lng");
                            int altindex = dflog.FindMessageOffset("GPS", "Alt");
                            int raltindex = dflog.FindMessageOffset("GPS", "RAlt");
                            if (raltindex == -1)
                                raltindex = dflog.FindMessageOffset("GPS", "RelAlt");

                            VehicleLocation location = new VehicleLocation();

                            try
                            {
                                location.Time = dflog.GetTimeGPS(line);
                                location.Lat = double.Parse(item.items[latindex], CultureInfo.InvariantCulture);
                                location.Lon = double.Parse(item.items[lngindex], CultureInfo.InvariantCulture);
                                location.RelAlt = double.Parse(item.items[raltindex], CultureInfo.InvariantCulture);
                                location.AltAMSL = double.Parse(item.items[altindex], CultureInfo.InvariantCulture);

                                location.Roll = currentRoll;
                                location.Pitch = currentPitch;
                                location.Yaw = currentYaw;

                                long millis = ToMilliseconds(location.Time);

                                //System.Diagnostics.Debug.WriteLine("GPS MSG - UTCMillis = " + millis  + "  GPS Week = " + getValueFromStringArray(gpsLineValues, gpsweekpos) + "  TimeMS = " + getValueFromStringArray(gpsLineValues, timepos));

                                if (!vehiclePositionList.ContainsKey(millis) && (location.Time != DateTime.MinValue))
                                    vehiclePositionList[millis] = location;
                            }
                            catch
                            {
                                Console.WriteLine("Bad GPS Line");
                            }
                        }
                        else if (item.msgtype == "ATT")
                        {
                            int Rindex = dflog.FindMessageOffset("ATT", "Roll");
                            int Pindex = dflog.FindMessageOffset("ATT", "Pitch");
                            int Yindex = dflog.FindMessageOffset("ATT", "Yaw");

                            currentRoll = float.Parse(item.items[Rindex], CultureInfo.InvariantCulture);
                            currentPitch = float.Parse(item.items[Pindex], CultureInfo.InvariantCulture);
                            currentYaw = float.Parse(item.items[Yindex], CultureInfo.InvariantCulture);
                        }
                    }
                }
            }

            return vehiclePositionList;
        }
Exemple #27
0
        // Return List with all CAMs messages splitted in string arrays
        Dictionary<long, VehicleLocation> readCAMMsgInLog(string fn)
        {
            Dictionary<long, VehicleLocation> list = new Dictionary<long, VehicleLocation>();

            if (fn.ToLower().EndsWith("tlog"))
                return null;

            // convert bin to log
            if (fn.ToLower().EndsWith("bin"))
            {
                string tempfile = Path.GetTempFileName();
                Log.BinaryLog.ConvertBin(fn, tempfile);
                fn = tempfile;
            }

            using (StreamReader sr = new StreamReader(fn))
            {

                int a = 0;
                while (!sr.EndOfStream)
                {
                    a++;
                    string line = sr.ReadLine();

                    var item = DFLog.GetDFItemFromLine(line, a);

                    if (item.msgtype == "CAM")
                    {
                        int latindex = DFLog.FindMessageOffset("CAM", "Lat");
                        int lngindex = DFLog.FindMessageOffset("CAM", "Lng");
                        int altindex = DFLog.FindMessageOffset("CAM", "Alt");
                        int raltindex = DFLog.FindMessageOffset("CAM", "RelAlt");

                        int rindex = DFLog.FindMessageOffset("CAM", "Roll");
                        int pindex = DFLog.FindMessageOffset("CAM", "Pitch");
                        int yindex = DFLog.FindMessageOffset("CAM", "Yaw");

                        int gtimeindex = DFLog.FindMessageOffset("CAM", "GPSTime");
                        int gweekindex = DFLog.FindMessageOffset("CAM", "GPSWeek");

                        VehicleLocation p = new VehicleLocation();

                        p.Time = GetTimeFromGps(int.Parse(item.items[gweekindex], CultureInfo.InvariantCulture),
                            int.Parse(item.items[gtimeindex], CultureInfo.InvariantCulture));

                        p.Lat = double.Parse(item.items[latindex], CultureInfo.InvariantCulture);
                        p.Lon = double.Parse(item.items[lngindex], CultureInfo.InvariantCulture);
                        p.AltAMSL = double.Parse(item.items[altindex], CultureInfo.InvariantCulture);
                        p.RelAlt = double.Parse(item.items[raltindex], CultureInfo.InvariantCulture);

                        p.Pitch = float.Parse(item.items[pindex], CultureInfo.InvariantCulture);
                        p.Roll = float.Parse(item.items[rindex], CultureInfo.InvariantCulture);
                        p.Yaw = float.Parse(item.items[yindex], CultureInfo.InvariantCulture);

                        list[ToMilliseconds(p.Time)] = p;
                    }
                }
                //while (!sr.EndOfStream)
                //{
                //    string line = sr.ReadLine();

                //    if (line.ToLower().StartsWith("cam"))
                //    {
                //        string[] currentCAM = line.Split(new char[] { ',', ':' });

                //        VehicleLocation p = new VehicleLocation();

                //        p.Time = GetTimeFromGps(int.Parse(getValueFromStringArray(currentCAM, weekCAMPos), CultureInfo.InvariantCulture), int.Parse(getValueFromStringArray(currentCAM, timeCAMpos), CultureInfo.InvariantCulture));

                //        p.Lat = double.Parse(getValueFromStringArray(currentCAM, latCAMpos), CultureInfo.InvariantCulture);
                //        p.Lon = double.Parse(getValueFromStringArray(currentCAM, lngCAMpos), CultureInfo.InvariantCulture);
                //        p.AltAMSL = double.Parse(getValueFromStringArray(currentCAM, altCAMpos), CultureInfo.InvariantCulture);
                //        p.RelAlt = double.Parse(getValueFromStringArray(currentCAM, altCAMpos), CultureInfo.InvariantCulture);

                //        p.Pitch = float.Parse(getValueFromStringArray(currentCAM, pitchCAMATT), CultureInfo.InvariantCulture);
                //        p.Roll = float.Parse(getValueFromStringArray(currentCAM, rollCAMATT), CultureInfo.InvariantCulture);
                //        p.Yaw = float.Parse(getValueFromStringArray(currentCAM, yawCAMATT), CultureInfo.InvariantCulture);

                //        list[ToMilliseconds(p.Time)] = p;
                //    }
                //}
            }
            return list;
        }
Exemple #28
0
        // Return List with all CAMs messages splitted in string arrays
        Dictionary<long, VehicleLocation> readCAMMsgInLog(string fn)
        {
            Dictionary<long, VehicleLocation> list = new Dictionary<long, VehicleLocation>();

            if (fn.ToLower().EndsWith("tlog"))
                return null;

            // convert bin to log
            if (fn.ToLower().EndsWith("bin"))
            {
                string tempfile = Path.GetTempFileName();
                Log.BinaryLog.ConvertBin(fn, tempfile);
                fn = tempfile;
            }

            using (StreamReader sr = new StreamReader(fn))
            {
                while (!sr.EndOfStream)
                {
                    string line = sr.ReadLine();

                    if (line.ToLower().StartsWith("cam"))
                    {
                        string[] currentCAM = line.Split(new char[] { ',', ':' });

                        VehicleLocation p = new VehicleLocation();

                        p.Time = GetTimeFromGps(int.Parse(getValueFromStringArray(currentCAM, weekCAMPos), CultureInfo.InvariantCulture), int.Parse(getValueFromStringArray(currentCAM, timeCAMpos), CultureInfo.InvariantCulture));

                        p.Lat = double.Parse(getValueFromStringArray(currentCAM, latCAMpos), CultureInfo.InvariantCulture);
                        p.Lon = double.Parse(getValueFromStringArray(currentCAM, lngCAMpos), CultureInfo.InvariantCulture);
                        p.AltAMSL = double.Parse(getValueFromStringArray(currentCAM, altCAMpos), CultureInfo.InvariantCulture);
                        p.RelAlt = double.Parse(getValueFromStringArray(currentCAM, altCAMpos), CultureInfo.InvariantCulture);

                        p.Pitch = float.Parse(getValueFromStringArray(currentCAM, pitchCAMATT), CultureInfo.InvariantCulture);
                        p.Roll = float.Parse(getValueFromStringArray(currentCAM, rollCAMATT), CultureInfo.InvariantCulture);
                        p.Yaw = float.Parse(getValueFromStringArray(currentCAM, yawCAMATT), CultureInfo.InvariantCulture);

                        list[ToMilliseconds(p.Time)] = p;
                    }
                }
            }
            return list;
        }
Exemple #29
0
        public MapAddress CheckNowAndFirstSectionAndAddress(MapSection section, MapAddress address, ref string errorMessage)
        {
            MapAGVPosition  agvPosition = localData.Real;
            VehicleLocation nowLocation = localData.Location;

            if (agvPosition == null || agvPosition.Position == null || !localData.TheMapInfo.AllAddress.ContainsKey(nowLocation.LastAddress))
            {
                errorMessage = "迷航中";
                return(null);
            }

            if (nowLocation.InAddress)
            {
                return(localData.TheMapInfo.AllAddress[nowLocation.LastAddress]);
            }

            MapAddress returnAddress = null;

            if (section.Id != nowLocation.NowSection)
            {
                if (section.FromAddress == localData.TheMapInfo.AllSection[nowLocation.NowSection].FromAddress ||
                    section.FromAddress == localData.TheMapInfo.AllSection[nowLocation.NowSection].ToAddress)
                {
                    returnAddress = section.FromAddress;
                }
                else if (section.ToAddress == localData.TheMapInfo.AllSection[nowLocation.NowSection].FromAddress ||
                         section.ToAddress == localData.TheMapInfo.AllSection[nowLocation.NowSection].ToAddress)
                {
                    returnAddress = section.ToAddress;
                }
                else
                {
                    errorMessage = "判定不再Address上且命令起始Section和local判定Section不同,且Section本身無相交,異常";
                    return(null);
                }

                if (GetDistanceFormTwoAGVPosition(returnAddress.AGVPosition, agvPosition) > localData.MoveControlData.CreateMoveCommandConfig.SafteyDistance[EnumCommandType.Move] / 2)
                {
                    errorMessage = "判定不再Address上且命令起始Section和local判定Section不同,兩條Section交點和命令起始Address差異過大";
                    return(null);
                }
                else
                {
                    return(returnAddress);
                }
            }
            else
            {
                if (section.FromVehicleAngle == section.ToVehicleAngle)
                {
                    returnAddress = new MapAddress();
                    returnAddress.InsideSection        = section;
                    returnAddress.AGVPosition.Angle    = section.FromVehicleAngle;
                    returnAddress.AGVPosition.Position = GetTransferPosition(agvPosition, section);

                    if (returnAddress.AGVPosition.Position == null)
                    {
                        errorMessage = "ComputeFunction.GetTransferPosition return null";
                        return(null);
                    }

                    return(returnAddress);
                }
                else
                {
                    errorMessage = "不能再RTurn Section啟動";
                    return(null);
                }
            }
        }
Exemple #30
0
        private DateTime CreateLocalTimestamp(VehicleLocation location)
        {
            var datetime = DateTime.UnixEpoch.AddSeconds(location.LastGpsFix);

            return(datetime);
        }
        private Dictionary<long, VehicleLocation> readTRIGMsgInLog(string fn)
        {
            Dictionary<long, VehicleLocation> list = new Dictionary<long, VehicleLocation>();


            float currentSAlt = 0;
            using (var sr = new CollectionBuffer(File.OpenRead(fn)))
            {
                foreach (var item in sr.GetEnumeratorType(new string[] { "TRIG", "RFND" }))
                {
                    if (item.msgtype == "TRIG")
                    {
                        int latindex = sr.dflog.FindMessageOffset("TRIG", "Lat");
                        int lngindex = sr.dflog.FindMessageOffset("TRIG", "Lng");
                        int altindex = sr.dflog.FindMessageOffset("TRIG", "Alt");
                        int raltindex = sr.dflog.FindMessageOffset("TRIG", "RelAlt");

                        int rindex = sr.dflog.FindMessageOffset("TRIG", "Roll");
                        int pindex = sr.dflog.FindMessageOffset("TRIG", "Pitch");
                        int yindex = sr.dflog.FindMessageOffset("TRIG", "Yaw");

                        int gtimeindex = sr.dflog.FindMessageOffset("TRIG", "GPSTime");
                        int gweekindex = sr.dflog.FindMessageOffset("TRIG", "GPSWeek");

                        VehicleLocation p = new VehicleLocation();

                        p.Time = GetTimeFromGps(int.Parse(item.items[gweekindex], CultureInfo.InvariantCulture),
                            int.Parse(item.items[gtimeindex], CultureInfo.InvariantCulture));

                        p.Lat = double.Parse(item.items[latindex], CultureInfo.InvariantCulture);
                        p.Lon = double.Parse(item.items[lngindex], CultureInfo.InvariantCulture);
                        p.AltAMSL = double.Parse(item.items[altindex], CultureInfo.InvariantCulture);
                        if (raltindex != -1)
                            p.RelAlt = double.Parse(item.items[raltindex], CultureInfo.InvariantCulture);

                        p.Pitch = float.Parse(item.items[pindex], CultureInfo.InvariantCulture);
                        p.Roll = float.Parse(item.items[rindex], CultureInfo.InvariantCulture);
                        p.Yaw = float.Parse(item.items[yindex], CultureInfo.InvariantCulture);

                        p.SAlt = currentSAlt;

                        list[ToMilliseconds(p.Time)] = p;
                    }
                    else if (item.msgtype == "RFND")
                    {
                        int SAltindex = sr.dflog.FindMessageOffset("RFND", "Dist1");

                        if (SAltindex != -1)
                        {
                            currentSAlt = float.Parse(item.items[SAltindex], CultureInfo.InvariantCulture);
                        }
                    }
                }
            }

            return list;
        }
        /// <summary>
        /// Return a list of all cam messages in a log with timestamp
        /// </summary>
        /// <param name="fn"></param>
        /// <returns></returns>
        private Dictionary<long, VehicleLocation> readCAMMsgInLog(string fn)
        {
            Dictionary<long, VehicleLocation> list = new Dictionary<long, VehicleLocation>();

            // Telemetry Log
            if (fn.ToLower().EndsWith("tlog"))
            {
                TXT_outputlog.AppendText("Warning: tlogs are not fully supported when using CAM Messages\n");

                using (MAVLinkInterface mine = new MAVLinkInterface())
                {
                    mine.logplaybackfile =
                        new BinaryReader(File.Open(fn, FileMode.Open, FileAccess.Read, FileShare.Read));
                    mine.logreadmode = true;

                    CurrentState cs = new CurrentState();

                    while (mine.logplaybackfile.BaseStream.Position < mine.logplaybackfile.BaseStream.Length)
                    {
                        MAVLink.MAVLinkMessage packet = mine.readPacket();

                        cs.datetime = mine.lastlogread;
                        cs.UpdateCurrentSettings(null, true, mine);

                        if (packet.msgid == (uint)MAVLink.MAVLINK_MSG_ID.CAMERA_FEEDBACK)
                        {
                            var msg = (MAVLink.mavlink_camera_feedback_t)packet.data;

                            VehicleLocation location = new VehicleLocation();
                            location.Time = FromUTCTimeMilliseconds((long)(msg.time_usec / 1000));// cs.datetime;
                            location.Lat = msg.lat;
                            location.Lon = msg.lng;
                            location.RelAlt = msg.alt_rel;
                            location.AltAMSL = msg.alt_msl;

                            location.Roll = msg.roll;
                            location.Pitch = msg.pitch;
                            location.Yaw = msg.yaw;

                            location.SAlt = cs.sonarrange;

                            list[ToMilliseconds(location.Time)] = location;

                            Console.Write((mine.logplaybackfile.BaseStream.Position*100/
                                           mine.logplaybackfile.BaseStream.Length) + "    \r");
                        }
                    }
                    mine.logplaybackfile.Close();
                }
            }
            // DataFlash Log
            else
            {
                float currentSAlt = 0;
                using (var sr = new CollectionBuffer(File.OpenRead(fn)))
                {
                    foreach (var item in sr.GetEnumeratorType(new string[] { "CAM", "RFND" }))
                    {
                        if (item.msgtype == "CAM")
                        {
                            int latindex = sr.dflog.FindMessageOffset("CAM", "Lat");
                            int lngindex = sr.dflog.FindMessageOffset("CAM", "Lng");
                            int altindex = sr.dflog.FindMessageOffset("CAM", "Alt");
                            int raltindex = sr.dflog.FindMessageOffset("CAM", "RelAlt");

                            int rindex = sr.dflog.FindMessageOffset("CAM", "Roll");
                            int pindex = sr.dflog.FindMessageOffset("CAM", "Pitch");
                            int yindex = sr.dflog.FindMessageOffset("CAM", "Yaw");

                            int gtimeindex = sr.dflog.FindMessageOffset("CAM", "GPSTime");
                            int gweekindex = sr.dflog.FindMessageOffset("CAM", "GPSWeek");

                            VehicleLocation p = new VehicleLocation();

                            p.Time = GetTimeFromGps(int.Parse(item.items[gweekindex], CultureInfo.InvariantCulture),
                                int.Parse(item.items[gtimeindex], CultureInfo.InvariantCulture));

                            p.Lat = double.Parse(item.items[latindex], CultureInfo.InvariantCulture);
                            p.Lon = double.Parse(item.items[lngindex], CultureInfo.InvariantCulture);
                            p.AltAMSL = double.Parse(item.items[altindex], CultureInfo.InvariantCulture);
                            if (raltindex != -1)
                                p.RelAlt = double.Parse(item.items[raltindex], CultureInfo.InvariantCulture);

                            p.Pitch = float.Parse(item.items[pindex], CultureInfo.InvariantCulture);
                            p.Roll = float.Parse(item.items[rindex], CultureInfo.InvariantCulture);
                            p.Yaw = float.Parse(item.items[yindex], CultureInfo.InvariantCulture);

                            p.SAlt = currentSAlt;

                            list[ToMilliseconds(p.Time)] = p;
                        }
                        else if (item.msgtype == "RFND")
                        {
                            int SAltindex = sr.dflog.FindMessageOffset("RFND", "Dist1");

                            if (SAltindex != -1)
                            {
                                currentSAlt = float.Parse(item.items[SAltindex], CultureInfo.InvariantCulture);
                            }
                        }
                    }
                }
            }
            return list;
        }
Exemple #33
0
 public void SetLocationInfo(VehicleLocation locationInfo)
 {
     LocationInfo = locationInfo;
 }
Exemple #34
0
        // Return List with all GPS Messages splitted in string arrays
        Dictionary<long, VehicleLocation> readGPSMsgInLog(string fn)
        {
            Dictionary<long, VehicleLocation> vehiclePositionList = new Dictionary<long,VehicleLocation>();

            // Telemetry Log
            if (fn.ToLower().EndsWith("tlog"))
            {
                MAVLinkInterface mine = new MAVLinkInterface();
                mine.logplaybackfile = new BinaryReader(File.Open(fn, FileMode.Open, FileAccess.Read, FileShare.Read));
                mine.logreadmode = true;

                mine.MAV.packets.Initialize(); // clear

                CurrentState cs = new CurrentState();

                while (mine.logplaybackfile.BaseStream.Position < mine.logplaybackfile.BaseStream.Length)
                {
                    byte[] packet = mine.readPacket();

                    cs.datetime = mine.lastlogread;

                    cs.UpdateCurrentSettings(null, true, mine);

                    VehicleLocation location = new VehicleLocation();
                    location.Time = cs.datetime;
                    location.Lat = cs.lat;
                    location.Lon = cs.lng;
                    location.RelAlt = cs.alt;
                    location.AltAMSL = cs.altasl;

                    location.Roll = cs.roll;
                    location.Pitch = cs.pitch;
                    location.Yaw = cs.yaw;

                    vehiclePositionList[ToMilliseconds(location.Time)] = location;
                    // 4 5 7
                    Console.Write((mine.logplaybackfile.BaseStream.Position * 100 / mine.logplaybackfile.BaseStream.Length) + "    \r");
                }
                mine.logplaybackfile.Close();
            }
            // DataFlash Log
            else
            {
                StreamReader sr = new StreamReader(fn);

                // Will hold the last seen Attitude information in order to incorporate them into the GPS Info
                float currentYaw = 0f;
                float currentRoll = 0f;
                float currentPitch = 0f;

                while (!sr.EndOfStream)
                {
                    string line = sr.ReadLine();

                    // Look for GPS Messages. However GPS Messages do not have Roll, Pitch and Yaw
                    // So we have to look for one ATT message after having read a GPS one
                    if (line.ToLower().StartsWith("gps"))
                    {
                        VehicleLocation location = new VehicleLocation();

                        string[] gpsLineValues = line.Split(new char[] { ',', ':' });

                        try
                        {

                            location.Time = GetTimeFromGps(int.Parse(getValueFromStringArray(gpsLineValues, gpsweekpos), CultureInfo.InvariantCulture), int.Parse(getValueFromStringArray(gpsLineValues, timepos), CultureInfo.InvariantCulture));
                            location.Lat = double.Parse(getValueFromStringArray(gpsLineValues, latpos), CultureInfo.InvariantCulture);
                            location.Lon = double.Parse(getValueFromStringArray(gpsLineValues, lngpos), CultureInfo.InvariantCulture);
                            location.RelAlt = double.Parse(getValueFromStringArray(gpsLineValues, altpos), CultureInfo.InvariantCulture);
                            location.AltAMSL = double.Parse(getValueFromStringArray(gpsLineValues, altAMSLpos), CultureInfo.InvariantCulture);

                            location.Roll = currentRoll;
                            location.Pitch = currentPitch;
                            location.Yaw = currentYaw;



                            long millis = ToMilliseconds(location.Time);

                            //System.Diagnostics.Debug.WriteLine("GPS MSG - UTCMillis = " + millis  + "  GPS Week = " + getValueFromStringArray(gpsLineValues, gpsweekpos) + "  TimeMS = " + getValueFromStringArray(gpsLineValues, timepos));

                            if (!vehiclePositionList.ContainsKey(millis))
                                vehiclePositionList[millis] = location;
                        }
                        catch { Console.WriteLine("Bad GPS Line"); }
                    }
                    else if (line.ToLower().StartsWith("att"))
                    {
                        string[] attLineValues = line.Split(new char[] { ',', ':' });

                        currentRoll = float.Parse(getValueFromStringArray(attLineValues, rollATT), CultureInfo.InvariantCulture);
                        currentPitch = float.Parse(getValueFromStringArray(attLineValues, pitchATT), CultureInfo.InvariantCulture);
                        currentYaw = float.Parse(getValueFromStringArray(attLineValues, yawATT), CultureInfo.InvariantCulture);

                    }


                }

                sr.Close();

            }

            return vehiclePositionList;
        }
 public void Add(VehicleLocation location)
 {
     db.GeoAdd(key, location.Location.Longitude, location.Location.Latitude, location.DeviceId);
 }