示例#1
0
        public GPSData Read(TextReader reader)
        {
            reader.ThrowIfNull("reader");

            var data = new GPSData();
            var gpx  = LoadGpx(reader);

            foreach (var track in gpx.trk)
            {
                var way = new Way();
                foreach (var trackSegment in track.trkseg)
                {
                    foreach (var trackPoint in trackSegment.trkpt)
                    {
                        way.Add(new WayPoint
                        {
                            Latitude  = trackPoint.lat,
                            Longitude = trackPoint.lon,
                            Elevation = trackPoint.eleSpecified ? (decimal?)trackPoint.ele : null
                        });
                    }
                }
                data.Add(way);
            }
            return(data);
        }
示例#2
0
        /// <summary>
        /// Re-Sets the COMPort for the GPS.
        /// </summary>
        /// <param name="COMPort">Serial connection port. (DEfault COM3).</param>
        public ErrorType SetPort(string COMPort = "COM3")
        {
            if (COMPort == null)
            {
                COMPort = "COM3";
            }

            IsConnected = false;

            if (serialConnection != null && serialConnection.IsOpen)
            {
                serialConnection.Close();
                serialConnection.Dispose();

                serialConnection = null;

                GC.Collect();
            }

            gpsData = new GPSData();

            log.Info("Re-setting the GPS Port on: " + COMPort + ".");

            Port = COMPort;

            return(TryConnect());
        }
    public static void TestPlaneToJson()
    {
        //The one thing we want to check
        //  -a valid plane object converts to a valid JSON object
        //We could do some tests here as far as malformed/invalid objects, but that ObjectTests should probably be ensuring we are getting a proper object

        //make some planes
        Plane plane1 = new Plane("abcd", new PlaneAttributes("abcd", 2, 45, 20, 100, 19000)); //valid plane object
        Plane plane2 = new Plane("DEF328", new PlaneAttributes("483CBA50", 1, 35, 15, 50, 12000));  //valid plane object

        //Give them a current position - AddPosition(GPSData data)
        GPSData gps1 = new GPSData (-90, 90, 20000, 232050);
        GPSData gps2 = new GPSData (-45, 45, 15000, 190000);
        plane1.AddPosition(gps1);
        plane2.AddPosition(gps2);

        //convert the objects to JSON
        string jsonPlane1 = plane1.ToJson();
        string jsonPlane2 = plane2.ToJson();

        JsonObject correctJSONObject1 = (JsonObject)Json.Parse(createCorrectDataSet());
        JsonObject correctJSONObject2 = (JsonObject)Json.Parse(createCorrectDataSet2());

        //test them
        jsonPlane1.ShouldBe(correctJSONObject1.PrettyPrint());
        jsonPlane2.ShouldBe(correctJSONObject2.PrettyPrint());
    }
    public static void TryStuff(int aFieldId)
    {
        CommonData dataField = null;

        switch (aFieldId)
        {
        case (0):
            dataField                       = new GPSData();
            dataField.CommonStuff           = "abcd";
            (dataField as GPSData).GPSStuff = "bcde";
            break;

        case (1):
            dataField             = new DigitalData();
            dataField.CommonStuff = "abcd";
            (dataField as DigitalData).DigitalStuff = "cdef";
            break;

        case (2):
            dataField             = new DriverData();
            dataField.CommonStuff = "abcd";
            (dataField as DriverData).DriverStuff = "defg";
            break;

        default:
            break;
        }
    }
示例#5
0
        public GPSData Read(TextReader reader)
        {
            reader.ThrowIfNull("reader");

            var data = new GPSData();
            var gpx = LoadGpx(reader);
            foreach (var track in gpx.trk)
            {
                var way = new Way();
                foreach (var trackSegment in track.trkseg)
                {
                    foreach (var trackPoint in trackSegment.trkpt)
                    {
                        way.Add(new WayPoint
                        {
                            Latitude = trackPoint.lat,
                            Longitude = trackPoint.lon,
                            Elevation = trackPoint.eleSpecified ? (decimal?)trackPoint.ele : null
                        });
                    }
                }
                data.Add(way);
            }
            return data;
        }
示例#6
0
    public void StoreSegmentData(string _lat, string _lng, string _type, string _vertivalID, string _time, string _callFrom)
    {
        if (_callFrom == "btnSegment")
        {
            // type is startPoint or endPoint
            var Line = _type + "=" + _lat + "," + _lng;
            File.AppendAllText(@"C:\Users\user\Desktop\Amir\MMS\Final Project\Unity\test5\Assets\Scripts\segments.txt", Line + Environment.NewLine);

            // call from btn and the btn text is End segment which means user just clicked on btn to start collecting data
            if (segment1.GetComponentInChildren <Text>().text == "End segment")
            {
                //  effect = new List<GPSData>();
            }
            else
            {
                // means the user clicked to stop collecting data
                var output = JsonConvert.SerializeObject(arrayGPS);
                // Debug.Log(output);
                string path = Application.dataPath + @"\Scripts\GPS.json";
                File.AppendAllText(path, output);

                // here we need to calculate IRI
                double lat1        = double.Parse(arrayGPS[0].lat) * Math.PI / 180;
                double lon1        = double.Parse(arrayGPS[0].lon) * Math.PI / 180;
                double lat2        = double.Parse(arrayGPS[arrayGPS.Count - 1].lat) * Math.PI / 180;
                double lon2        = double.Parse(arrayGPS[arrayGPS.Count - 1].lon) * Math.PI / 180;
                double deltaPhi    = lat2 - lat1;
                double deltaLambda = lon2 - lon1;
                double a           = (Math.Sin(deltaPhi / 2) * Math.Sin(deltaPhi / 2)) + Math.Cos(lat1) * Math.Cos(lat2) *
                                     (Math.Sin(deltaLambda / 2) * Math.Sin(deltaLambda / 2));
                double c = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a)) * 1000000;
                double d = 637.1 * c;

                // here I have to calculate the vrtical displacement
                double verticalSum = arrayVerticalDBetweenTwoPoint.Sum();
                var    IRI         = verticalSum / d;
                ValueIRI.text = "" + (IRI);
            }
        }
        else if (_callFrom == "details" & segment1.GetComponentInChildren <Text>().text == "End segment")
        {
            if (counterStoreData % 10 == 0)
            {
                var Line = _lat + "," + _lng + "," + _vertivalID;
                File.AppendAllText(@"C:\Users\user\Desktop\Amir\MMS\Final Project\Unity\test5\Assets\Scripts\segments.txt", Line + Environment.NewLine);

                GPSData myObject = new GPSData();
                myObject.lat      = _lat;
                myObject.lon      = _lng;
                myObject.vertical = _vertivalID;
                arrayGPS.Add(myObject);
                if (arrayGPS.Count > 1)
                {
                    arrayVerticalDBetweenTwoPoint.Add(Math.Abs(double.Parse(arrayGPS[arrayGPS.Count - 1].vertical) - double.Parse(arrayGPS[arrayGPS.Count - 2].vertical)));
                }
            }
        }
    }
示例#7
0
 public void UpdateData(double xpos, DateTime time)
 {
     position = (float)xpos;
     data     = filemanager.ReadGPSstatus(position);
     ReadCache(position);
     updateLabels(time, 0, 0, 0, 0);
     PlotGraph(data);
     CacheData = CacheData2;
 }
 public static void TestConversionLAX()
 {
     GPSData lax = new GPSData(33.941589, -118.40853, 3000, 0x41D58BCD15000000);
     // timestamp: 10/27/2015, 08:22:44
     lax.coords.x.ShouldBe(-2932528.977, 0.9);
     lax.coords.y.ShouldBe(3682374.702, 0.9);
     lax.coords.z.ShouldBe(-4297472.089, 0.9);
     lax.coords.w.ShouldBe(1445934164, 0.1);
 }
 public static void TestConversionMSU()
 {
     GPSData msu = new GPSData(39.74578, -105.007383, 5000, 0x41D59032F3400000);
     // timestamp: 11/2/2015, 16:37:33
     msu.coords.x.ShouldBe(682662.0279, 0.9);
     msu.coords.y.ShouldBe(5665808.203, 0.9);
     msu.coords.z.ShouldBe(-2839095.976, 0.9);
     msu.coords.w.ShouldBe(1447087053, 0.1);
 }
 public static void TestConversionNY()
 {
     GPSData ny = new GPSData(40.712784, -74.005941, 3000, 0x41D59032A6000000);
     // timestamp: 11/9/2015, 16:32:24
     ny.coords.x.ShouldBe(-1122564.584, 0.9);
     ny.coords.y.ShouldBe(813143.3387 , 0.9);
     ny.coords.z.ShouldBe(-6221456.635, 0.9);
     ny.coords.w.ShouldBe(1447086744, 0.1);
 }
 public static void TestConversionTKY()
 {
     GPSData tky = new GPSData(35.689488, 139.691706, 3000, 0x41D58A6398800000);
     // timestamp: 10/23/2015, 01:33:22
     tky.coords.x.ShouldBe(-295056.6677, 0.9);
     tky.coords.y.ShouldBe(-5770066.357, 0.9);
     tky.coords.z.ShouldBe(-2692053.453, 0.9);
     tky.coords.w.ShouldBe(1445564002, 0.1);
 }
    public static void TestGPSConstructor()
    {
        GPSData GPS = new GPSData(-90, 90, 20000, 232050);

        GPS.lattitude.ShouldBe(-90);
        GPS.longitude.ShouldBe(90);
        GPS.altitude.ShouldBe(20000);
        GPS.timeStamp.ShouldBe(232050);
        //XYZ coords tested by GPSTests...
    }
示例#13
0
 public MomentDetail(LogFileManager manager)
 {
     filemanager = manager;
     InitializeComponent();
     chart1.Series[0].XValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.String;
     ReadCache(0f);
     data = CacheData2[0];
     PlotGraph(data);
     CacheData = CacheData2;
 }
        /// <summary>
        ///  udostępniona metoda dodania danych gps do bazy
        /// </summary>
        /// <param name="addDataRequest"></param>
        /// <returns>zwracana odpowiedź czy udało się dodać dane do bazy</returns>
        public BaseResponse AddData(AddDataRequest addDataRequest)
        {
            var response = new BaseResponse();

            try
            {
                var addSession         = new SessionService.SessionService();
                AddSessionResponse res = addSession.AddSession(new AddSessionRequest
                {
                    IdBoat    = addDataRequest.IdBoat,
                    StartDate = addDataRequest.GpsDataList.Max(x => x.SecondsFromStart),
                    StopDate  = addDataRequest.GpsDataList.Min(x => x.SecondsFromStart)
                });

                _unitOfWork.BeginTransaction();
                if (res.IsSuccess)
                {
                    foreach (var item in addDataRequest.GpsDataList)
                    {
                        GPSData data = Mapper.Map <GPSData>(item);
                        data.BoatDirection = 4;
                        data.BoatSpeed     = 6;
                        data.WindDirection = 2;
                        data.WindSpeed     = 9;
                        data.IdSession     = new Guid("4ADAEDD9-DAB7-E511-82AF-ACB57D99B460");
                        data.IdGPSData     = Guid.NewGuid();
                        _repositoryGpsData.Add(data);
                    }

                    _unitOfWork.Commit();
                    response.IsSuccess = true;
                }
                else
                {
                    _unitOfWork.Commit();
                    response.IsSuccess    = false;
                    response.ErrorMessage = "Nie udalo sie utworzyc sesji.";
                }
            }
            catch (DbEntityValidationException dbEx)
            {
                foreach (var validationErrors in dbEx.EntityValidationErrors)
                {
                    foreach (var validationError in validationErrors.ValidationErrors)
                    {
                        response.ErrorMessage += validationError.PropertyName + "\n";
                        response.ErrorMessage += validationError.ErrorMessage + "\n";
                    }
                }
                response.IsSuccess = false;
            }

            return(response);
        }
    public void AddPosition(GPSData data)
    {
        //take this GPSData and add it into our plane object
        if (data == null) {
            throw new ArgumentNullException("GPSData was null");
        }

        positions.AddLast(data);
        if (positions.Count >= 4) {
            positions.RemoveFirst();
        }
    }
示例#16
0
        private void DealGpsDataProc(object obj)
        {
            try
            {
                Byte[] data = (Byte[])obj;

                //1-4字节为包类型,默认传的是1,这里没有用到
                int type = System.BitConverter.ToInt32(data.Skip(0).Take(4).ToArray(), 0);

                //5-8字节为考车号
                int kch = System.BitConverter.ToInt32(data.Skip(4).Take(4).ToArray(), 0);
                if (kch <= 0)
                {
                    Log.GetLogger().ErrorFormat("udp 数据解析得到的考车号为 {0}", kch);
                    return;
                }
                if (!m_dicCars.ContainsKey(kch) || !m_dicExamProcedures.ContainsKey(kch))
                {
                    Log.GetLogger().ErrorFormat("不存在考车 {0},请检查配置", kch);
                    return;
                }
                ExamProcedure examProcedure = m_dicExamProcedures[kch];

                Log.GetLogger().DebugFormat("考车 {0} 接收到 GPS 数据", kch);

                //接下来的数据结构可以参考 GPSData 类
                //8个字节存放double类型的经度
                //8个字节存放double类型的纬度
                //4个字节存放float类型的方向角
                //4个字节存放float类型的速度
                //4个字节存放float类型的里程
                double longitude      = System.BitConverter.ToDouble(data.Skip(8).Take(8).ToArray(), 0);
                double latitude       = System.BitConverter.ToDouble(data.Skip(16).Take(8).ToArray(), 0);
                float  directionAngle = System.BitConverter.ToSingle(data.Skip(24).Take(4).ToArray(), 0);
                float  speed          = System.BitConverter.ToSingle(data.Skip(28).Take(4).ToArray(), 0);
                float  mileage        = System.BitConverter.ToSingle(data.Skip(32).Take(4).ToArray(), 0);
                Log.GetLogger().DebugFormat("longitude={0}, latitude={1}, angle={2}, speed={3}, mileage={4}",
                                            longitude, latitude, directionAngle, speed, mileage);

                GPSData gpsData = new GPSData(longitude, latitude, directionAngle, speed, mileage);

                if (!examProcedure.HandleGPS(gpsData))
                {
                    Log.GetLogger().ErrorFormat("examProcedure.HandleGPS failed, kch={0}", kch);
                }
            }
            catch (Exception e)
            {
                Log.GetLogger().ErrorFormat("catch an error : {0}", e.Message);
            }

            Log.GetLogger().DebugFormat("DealGpsDataProc end");
        }
示例#17
0
        public async Task <string> ReadAsync(uint bufferLength)
        {
            String   str    = ""; // new StringBuilder();
            GPSData  gps    = new GPSData();
            GPSSpeed gs     = new GPSSpeed();
            string   retVal = "GPS not initialised";

            try
            {
                // Once we have written the contents successfully we load the stream. By getting the
                //right bufferlength, we can get the read more accurate without over or under buffer read
                bufferLength = await dr.LoadAsync(bufferLength);

                while (dr.UnconsumedBufferLength > 0)
                {
                    str += dr.ReadString(bufferLength) + "\n";
                    //if (str.Contains("GGA"))
                    //break;
                }

                if (str == "")
                {
                    return("GPS Data not available");
                }

                var dataGPS   = str.Substring(str.IndexOf("GGA")).Split('\n');
                var dataSpeed = str.Substring(str.IndexOf("VTG")).Split('\n');


                if (dataGPS.Count() > 0 && gps.SetData(dataGPS[0]))
                {
                    retVal = string.Format("Time: {0}; Latitude: {1}; Longitude: {2}; Elevation: {3}; Satellites: {4}; ",
                                           gps.gpsTime, gps.latitude, gps.longitude, gps.elevation, gps.satellites);
                    latLong = string.Format("{0}; {1}", gps.latitude, gps.longitude);
                }

                if (dataSpeed.Count() > 0 && gs.SetData(dataSpeed[0]))
                {
                    retVal += string.Format("Speed in Km: {0}", gs.SpeedKM);
                }

                Speed = gs.SpeedKM;
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Reading serial data failed!" + ex.Message);
                return("");
            }

            return(retVal);
        }
示例#18
0
        private byte[] PacketForNeiMeng(GPSData temp)
        {
            string date = temp.time;

            // liaoninggps.issiNumber = {0x09,0x01,0xC,0x3b}; //strToToHexByte(temp.id);
            liaoninggps.issiNumber = strToToHexByteForID(temp.id);
            liaoninggps.lat        = ConvertDigitalToDegreesForLat(temp.lat);
            liaoninggps.lon        = ConvertDigitalToDegreesForLat(temp.lon);
            liaoninggps.speed      = new Byte[2];
            liaoninggps.speed      = ConvertToHexForSpeed(temp.speed);
            liaoninggps.dir        = new Byte[2];
            liaoninggps.dir        = ConvertToHexForSpeed(temp.dir);
            liaoninggps.loction    = 0;
            liaoninggps.v1v2       = new byte[2];
            for (int i = 0; i < 2; i++)
            {
                liaoninggps.v1v2[i] = 0;
            }
            liaoninggps.cheliangStatues = new byte[4];
            for (int i = 0; i < 4; i++)
            {
                liaoninggps.cheliangStatues[i] = 0;
            }
            liaoninggps.licheng = new byte[3];
            for (int i = 0; i < 3; i++)
            {
                liaoninggps.licheng[i] = 0;
            }


            now = DateTime.Now;

            liaoninggps.year = strToToBCD((Convert.ToInt32(now.Year) - 2000).ToString()); // Convert.ToByte((Convert.ToInt32(now.Year) - 2000).ToString("X"), 16);

            liaoninggps.month = strToToBCD(now.Month.ToString());                         // Convert.ToByte(now.Month.ToString("X"), 16);

            liaoninggps.day = strToToBCD(now.Day.ToString());                             //Convert.ToByte(now.Day.ToString("X"), 16);

            liaoninggps.hour = strToToBCD(now.Hour.ToString());                           // Convert.ToByte(now.Hour.ToString("X"), 16);

            liaoninggps.minute = strToToBCD(now.Minute.ToString());                       // Convert.ToByte(now.Minute.ToString("X"), 16);

            liaoninggps.second = strToToBCD(now.Second.ToString());                       // Convert.ToByte(now.Second.ToString("X"), 16);

            var result_temp = liaoNinpro.GetByte(liaoninggps);

            liaoninggps.JiaoYan = getChecksum(result_temp);
            var result = liaoNinpro.GetByte(liaoninggps);

            return(result);
        }
        private void Run()
        {
            GPSData data = new GPSData();

            while (true)
            {
                if (!Resource.GPSDataQueue.TryDequeue(out data))
                {
                    if (!Enabled)
                    {
                        threadStatus = ThreadState.Stopped;
                        return;
                    }
                    Thread.Sleep(5);
                    continue;
                }
                lock (Resource.lckDBInstanceList)
                {
                    foreach (DBManager dbManager in Resource.DBInstanceList.Values)
                    {
                        dbManager.Execute(data);
                    }
                }

                if (!Enabled)
                {
                    if (Resource.GPSDataQueue.Count > 0)
                    {
                        continue;
                    }

                    threadStatus = ThreadState.Stopped;
                    Logger.Info("Thread: commomTableThread exit safely");
                    return;
                }

                while (Suspended && Enabled)
                {
                    threadStatus = ThreadState.Suspended;
                    Thread.Sleep(50);
                }
                threadStatus = ThreadState.Running;
                //if there is no table to insert,thread will suspend
                while (Resource.DBInstanceList.Count <= 0 && Enabled)
                {
                    threadStatus = ThreadState.Suspended;
                    Thread.Sleep(100);
                }
            }
        }
示例#20
0
 public void Enqueue(GPSData data)
 {
     try
     {
         if (_isRunning)
         {
             _messageQueue.Enqueue(data);
         }
     }
     catch (Exception e)
     {
         LogManager.Error(e.Message, e);
         throw;
     }
 }
示例#21
0
 public void OnLogTimerEvent(object source, EventArgs e)
 {
     if ((m_GPSTrackDBWriter != null) || (m_GPSTrackWriter != null))
     {
         GPSData currData = m_GPSWrapper.GetCurrentGPSData();
         if (m_GPSTrackDBWriter != null)
         {
             m_GPSTrackDBWriter.LogPosition(ref currData);
         }
         if (m_GPSTrackWriter != null)
         {
             m_GPSTrackWriter.LogPosition(ref currData);
         }
     }
 }
示例#22
0
 public async Task SaveGPSDataAsync(GPSData data)
 {
     if (data.Id == null)
     {
         Debug.WriteLine("New GPSData");
         await _gpsDataTable.InsertAsync(data);
         await SyncAsync();
     }
     else
     {
         Debug.WriteLine("Update GPSData");
         await _gpsDataTable.UpdateAsync(data);
         await SyncAsync();
     }
 }
示例#23
0
        private void RefreshScreen()
        {
            GPSData m_currentData = m_GPSWrapper.GetCurrentGPSData();

            this.txtNoOfSatellites.Text = Convert.ToString(m_currentData.NoOfTrackedSatellites);
            this.txtFixType.Text        = m_currentData.FixType;
            this.txtFixTime.Text        = m_currentData.TimeOfLastFixGPS;

            // latest tatitude and longitude stored in object
            this.txtLongitude.Text = m_currentData.LatestFixPosition.GetLongitude(CoordinateFormat.DegreesMinutesSeconds);
            this.txtLatitude.Text  = m_currentData.LatestFixPosition.GetLatitude(CoordinateFormat.DegreesMinutesSeconds);
            this.txtCurrSpeed.Text = m_currentData.CurrentSpeed(UnitOfMeasure.Mile).ToString();

            this.txtErrorCount.Text = m_iErrorCount.ToString();;
        }
示例#24
0
 private void Gps1_GotLocation(object sender, GPSData e)
 {
     try
     {
         if (e.Longitude.Equals(0) & e.Latitude.Equals(0))
         {
             this.LeftLayoutData.Items["lblAddress"].Text = "";
         }
         else
         {
             this.LeftLayoutData.Items["lblAddress"].Text = e.Location;
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message);
     }
 }
示例#25
0
        public void StartDataCollection()
        {
            Device.StartTimer(TimeSpan.FromMinutes(2), () =>
            {
                if (_stopDataCollection)
                {
                    // Stop
                    _stopDataCollection = false;
                    return(false);
                }

                // Get GPS Data from Box
                var rawData = _bluetoothConnection.GetGPSData();
                var gpsData = new GPSData(rawData.position.latitude.value, rawData.position.longitude.value, rawData.trueVelocity, rawData.time);

                // Call GPSDataReceived Event
                GPSDataReceived?.Invoke(gpsData);
                return(true);
            });
        }
示例#26
0
    public void mapdatatest()
    {
        float latitude;
        float longitude;

        float expectedlati = 23.5f;
        float expectedlong = 45;
        //checking game are correct updating the gps data;
        GPSData gpsdata = new GPSData();

        // input the data then checking the the data

        gpsdata.updateGpsData(expectedlati, expectedlong);

        latitude  = gpsdata.getLatitude();
        longitude = gpsdata.getLongitude();

        // checking both the latitude and longitude
        Assert.AreEqual(latitude, expectedlati);
        Assert.AreEqual(longitude, expectedlong);
    }
示例#27
0
        public ActionResult Index()
        {
            string         markers   = "[";
            string         conString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
            SqlCommand     cmd       = new SqlCommand("Sp_GeoLoc");
            List <GPSData> lstGPS    = new List <GPSData>();

            using (SqlConnection con = new SqlConnection(conString))
            {
                cmd.Connection = con;
                con.Open();
                using (SqlDataReader sdr = cmd.ExecuteReader())
                {
                    while (sdr.Read())
                    {
                        GPSData _gps = new GPSData();
                        _gps.Name      = sdr["Name"].ToString();
                        _gps.Latitude  = sdr["Lat"].ToString();
                        _gps.Longitude = sdr["Long"].ToString();
                        _gps.Speed     = Convert.ToString(sdr["Speed"].ToString());
                        _gps.ignition  = Convert.ToInt32(sdr["ignition"]);
                        _gps.Location  = RetrieveFormatedAddress(_gps.Latitude, _gps.Longitude);
                        lstGPS.Add(_gps);

                        markers += "{";
                        markers += string.Format("'title': '{0} Speed {1} Ignition {2}',", sdr["Name"], sdr["Speed"], sdr["ignition"]);
                        markers += string.Format("'lat': '{0}',", sdr["Lat"]);
                        markers += string.Format("'lng': '{0}',", sdr["Long"]);
                        markers += string.Format("'description': '{0}'", sdr["Speed"]);
                        markers += "},";
                    }
                }
                con.Close();
            }

            markers        += "];";
            ViewBag.Markers = markers;
            return(View(lstGPS));
        }
示例#28
0
 /// <summary>
 /// 打卡地方赋值
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void Gps1_GotLocation(object sender, GPSData e)
 {
     if ((e.IsError).Equals(false))
     {
         if (e.Longitude != 0 & e.Latitude != 0)
         {
             Longitude       = e.Longitude;
             Latitude        = e.Latitude;
             addressInfo     = e.Location;
             lblAddress.Text = e.Location;
             MapView1.GeoTag = new GeoTag(Longitude, Latitude, addressInfo);
         }
         else
         {
             lblAddress.Text = "定位失败";
         }
     }
     else
     {
         lblAddress.Text = "定位失败";
     }
 }
示例#29
0
        /* Handles the NMEA protocol messages. */
        private void receiveBackgroundThread()
        {
            while (true)
            {
                var sp = serialConnection;

                if (sp == null)
                {
                    continue;
                }


                try {
                    if (!sp.IsOpen)
                    {
                        //TryConnect ();
                        continue;
                    }



                    var data = sp.ReadLine();

                    //Console.WriteLine (data);
                    //log.Info (data);

                    if (!IsConnected)
                    {
                        IsConnected = true;
                    }

                    var rawData = data.Split(',');

                    // Check for invalid packets.
                    if (rawData.Length <= 5)
                    {
                        continue;
                    }

                    // Ignore no signal data.
                    if (String.IsNullOrWhiteSpace(rawData [2]) || String.IsNullOrWhiteSpace(rawData [4]))
                    {
                        continue;
                    }

                    if (rawData [0] == "$GPGGA")
                    {
                        gpsData = new GPSData(rawData);


                        var rawLat = gpsData.Latitude;
                        var rawLon = gpsData.Longitude;


                        var lon = "";
                        var lat = "";

                        if (rawLat != null)
                        {
                            if (rawLat.Length > 5)
                            {
                                var degree = rawLat.Substring(0, 2);

                                if (degree.StartsWith("0"))
                                {
                                    degree = degree.Substring(1);
                                }


                                var minutes = rawLat.Substring(2);


                                double fMinutes = double.Parse(minutes);


                                fMinutes = fMinutes / 60;

                                fMinutes = Math.Round(fMinutes, 6);

                                var deciDegree = double.Parse(degree);



                                lat = (deciDegree + fMinutes).ToString();
                            }
                        }

                        if (rawLon != null)
                        {
                            if (rawLon.Length > 6)
                            {
                                var degree = rawLon.Substring(0, 3);

                                if (degree.StartsWith("00"))
                                {
                                    degree = degree.Substring(2);
                                }
                                else if (degree.StartsWith("0"))
                                {
                                    degree = degree.Substring(1);
                                }


                                var minutes = rawLon.Substring(3);


                                double fMinutes = double.Parse(minutes);


                                fMinutes = fMinutes / 60;

                                fMinutes = Math.Round(fMinutes, 6);

                                var deciDegree = double.Parse(degree);

                                lon = (deciDegree + fMinutes).ToString();
                            }
                        }


                        gpsData = new GPSData(lon, lat, gpsData.Altitude);
                    }
                }
                catch (Exception ex) {
                    if (ex is ThreadAbortException)
                    {
                        break;
                    }
                    else if (ex is System.IO.IOException)
                    {
                        break;
                    }
                    else
                    {
                        log.Fatal("RECEIVE ERROR: " + ex.ToString());
                    }
                }
            }
        }
 /// <summary>
 /// dodanie danych gps do bazy
 /// </summary>
 /// <param name="entity"></param>
 public void Add(GPSData entity)
 {
     _sailingDbContext.GPSData.Add(entity);
 }
 /// <summary>
 /// aktualizacja danych w bazie
 /// </summary>
 /// <param name="entity"></param>
 public void Update(GPSData entity)
 {
     _sailingDbContext.GPSData.AddOrUpdate(entity);
 }
示例#32
0
 ///<exclude/>
 public bool Equals(GPSData other)
 {
     if (ReferenceEquals(null, other)) return false;
     if (ReferenceEquals(this, other)) return true;
     return other._Tm.Equals(_Tm) && other._TimeFromGPS.Equals(_TimeFromGPS) && other._Latitude.Equals(_Latitude) && other._Longitude.Equals(_Longitude) && other._Altitude.Equals(_Altitude) && other._HorizontalError.Equals(_HorizontalError) && other._VerticalError.Equals(_VerticalError) && other._Heading.Equals(_Heading) && other._HorizontalSpeed.Equals(_HorizontalSpeed) && other._VerticalSpeed.Equals(_VerticalSpeed) && other._NumSatellites.Equals(_NumSatellites) && other._FixType.Equals(_FixType);
 }
示例#33
0
        public void BuildXMPFile_LerpGPSData(string imgFolder)
        {
            if (imgFolder.Length < 3)
            {
                Program.AddLog("BuildXMPFile_LerpGPSData: wrong Path." + imgFolder);
                return;
            }
            if (!Directory.Exists(imgFolder))
            {
                Program.AddLog("BuildXMPFile_LerpGPSData: No Path." + imgFolder);
                return;
            }
            if (m_gps_data.Count < 1)
            {
                return;
            }
            string[] files = Directory.GetFiles(imgFolder);

            GPSData firstGPSData = m_gps_data.First().Value;

            foreach (var file in files)
            {
                string ext = Path.GetExtension(file);
                ext = ext.ToLower();
                if (ext == ".jpg")
                {
                    string filename   = Path.GetFileNameWithoutExtension(file);
                    string keyword    = "";
                    int    idx        = 0;
                    bool   isFilename = XMPGenerator.GetIndexAndKeyword(out keyword, out idx, filename);
                    if (!isFilename)
                    {
                        continue;
                    }
                    string xmpFileName = Path.ChangeExtension(file, "xmp");
                    if (File.Exists(xmpFileName))
                    {
                        File.Delete(xmpFileName);
                    }
                    idx -= 1;
                    int gpsIdx     = idx / 30;
                    int gpsSecStep = idx % 30;
                    gpsIdx += 1;
                    int gpsIdxNext = gpsIdx + 1;
                    if (!m_gps_data.ContainsKey(gpsIdx))
                    {
                        continue;
                    }
                    if (!m_gps_data.ContainsKey(gpsIdxNext))
                    {
                        continue;
                    }
                    GPSData gpsData  = m_gps_data[gpsIdx];
                    GPSData gpsData2 = m_gps_data[gpsIdxNext];
                    double  p        = gpsSecStep / 30.0;
                    double  posX     = (gpsData2.posX - gpsData.posX) * p + gpsData.posX;
                    double  posY     = (gpsData2.posY - gpsData.posY) * p + gpsData.posY;
                    double  altitude = (gpsData2.altitude - gpsData.altitude) * p + gpsData.altitude;

                    XMPFile xmp_file = new XMPFile();
                    xmp_file.LoadXML("Sample.xmp");
                    xmp_file.RemoveNode(100);
                    xmp_file.RemoveNode(102);
                    xmp_file.RemoveAttribute(1);
                    xmp_file.SetPosition(posX, posY, altitude);
                    xmp_file.SaveXML(xmpFileName);
                }
            }
        }
示例#34
0
        public void LoadGPSFile_csv(string filename)
        {
            gps_csv_filename = filename;
            StreamReader reader = new StreamReader(filename);
            int          count  = 0;
            double       latRef = 0;
            double       lonRef = 0;

            while (!reader.EndOfStream)
            {
                var line = reader.ReadLine();
                if (line.Length <= 3)
                {
                    continue;
                }
                if (line[0] == '#')
                {
                    continue;
                }
                var values = line.Split(',');
                if (values.Length < 2)
                {
                    continue;
                }

                if (count == 0)
                {
                    count++;
                    continue;
                }

                GPSData line_data = new GPSData();
                line_data.idx       = count;
                line_data.timeStamp = Convert.ToInt64(values[0]);
                line_data.latitude  = Convert.ToDouble(values[1]);
                line_data.longitude = Convert.ToDouble(values[2]);
                line_data.altitude  = Convert.ToDouble(values[3]);
                line_data.heading   = Convert.ToDouble(values[4]);

                if (count == 1)
                {
                    line_data.posX = 0;
                    line_data.posY = 0;
                    latRef         = line_data.latitude;
                    lonRef         = line_data.longitude;
                }
                else
                {
                    double posX;
                    double posY;
                    posX = KMLFile.distanceEarth(latRef, lonRef, latRef, line_data.longitude);
                    if (lonRef > line_data.longitude)
                    {
                        posX *= -1.0;
                    }
                    posY = KMLFile.distanceEarth(latRef, lonRef, line_data.latitude, lonRef);
                    if (latRef > line_data.latitude)
                    {
                        posY *= -1.0;
                    }
                    // km -> m
                    line_data.posX = posX * 1000.0;
                    line_data.posY = posY * 1000.0;
                }


                m_gps_data.Add(count, line_data);
                count++;
            }
            reader.Close();
            return;
        }
    //Written by Ross Baldwin
    //Here is the main constructor for a plane object
    //This constructor will take a JsonObject, and parse all the data from that object
    //  Exceptions:  Throws 'MissingFieldException' if any of the data fields are "", null, or 0 in an attribute, or if GPS data is missing or out of range
    public Plane(JsonObject dataObj)
    {
        //throw new NotImplementedException();
        //Instance variables
        string unverifiedGUID;
        GPSData verifiedGPSData;

        //Pull GUID out of the JSON object
        unverifiedGUID = dataObj.Get<string>("acasGUID");

        //verify GUID - length should be 8, and only numbers
        int n;
        if(int.TryParse(unverifiedGUID, out n) == false || Int32.Parse(unverifiedGUID) <= 0 || unverifiedGUID.Length != 8){throw new MissingFieldException();}
        //Set GUID
        this.acasGUID = unverifiedGUID;

        //Pull the JSON sub-objects out
        JsonObject attObj = dataObj["attributes"] as JsonObject;
        JsonObject gpsObj = dataObj["GPSData"] as JsonObject;

        //Pull the attributes out of the JSON object, and verify
        //  Check for planeModelGUID in range {}
        string planeModelGUID = attObj.Get<string>("planeModelGUID");
        if(planeModelGUID.Equals("")){throw new MissingFieldException();}
        //	Check for planeClass in range {1, 6} (1,2,3,4,5,6)
        int planeClass = attObj.Get<int>("planeClass");
        if(planeClass < 1 || planeClass > 6){throw new MissingFieldException();}
        //  Check for planeWidth in range {1, 125} (up to 125m wide)
        double planeWidth = attObj.Get<double>("planeWidth");
        if(planeWidth < 1 || planeWidth > 125){throw new MissingFieldException();}
        //  Check for planeHeight in range {1, 30} (up to 30m long)
        double planeHeight = attObj.Get<double>("planeHeight");
        if(planeHeight < 1 || planeHeight > 30){throw new MissingFieldException();}
        //  Check for planeLength in range {1, 125} (up to 125m long)
        double planeLength = attObj.Get<double>("planeLength");
        if(planeLength < 1 || planeLength > 125){throw new MissingFieldException();}
        //  Check for maxHeight in range {1, 17000} (within the atmosphere)
        double maxHeight = attObj.Get<double>("maxHeight");
        if(maxHeight < 1 || maxHeight > 17000){throw new MissingFieldException();}

        //Create Plane Attributes Object, and populate it
        this.attributes = new PlaneAttributes(planeModelGUID, planeClass, planeWidth, planeHeight, planeLength, maxHeight);

        //Pull the GPS data out of the JSON object, and verify the data
        //  Check for lat in range {-90, 90} (in range of latitude)
        double latitude = gpsObj.Get<double>("latitude");
        if(latitude < -90 || latitude > 90){throw new MissingFieldException();}
        //  Check for lon in range {-180, 180} (in range of longitude)
        double longitude = gpsObj.Get<double>("longitude");
        if(longitude < -180 || longitude > 180){throw new MissingFieldException();}
        //  Check for altitude in range {0, 17000} (Above ground, within atmosphere
        double altitude = gpsObj.Get<double>("altitude");
        if(altitude < 0 || altitude > 17000){throw new MissingFieldException();}
        //  Check for timeStamp > 1446834292 (11/6/2015 in Unix time)
        long timeStamp = gpsObj.Get<long>("timeStamp");
        if(timeStamp < 1446834292){throw new MissingFieldException();}

        //Construct new GPSData object, the list, and add it to the list in the first postion
        verifiedGPSData = new GPSData (latitude, longitude, altitude, timeStamp);
        this.positions = new LinkedList<GPSData>();
        this.positions.AddFirst(verifiedGPSData);
    }
示例#36
0
 public void Write(TextWriter writer, GPSData data)
 {
     throw new NotImplementedException();
 }
示例#37
0
 public void NotifyPrecessCompleted(GPSData gpsdata)
 {
     if (this.ProcessCompletedEvent != null)
         ProcessCompletedEvent(this, gpsdata);
 }
示例#38
0
 public void SetData(float accuracy, double latitude, double longitude, double altitude, long time)
 {
     isChanged = true;
     lastData  = new GPSData(accuracy, latitude, longitude, altitude, time);
 }
 /// <summary>
 /// usunięcie danych z bazy
 /// </summary>
 /// <param name="entity"></param>
 public void Delete(GPSData entity)
 {
     _sailingDbContext.Entry(entity).State = EntityState.Deleted;
 }
示例#40
0
 public void Write(TextWriter writer, GPSData data)
 {
     throw new NotImplementedException();
 }
示例#41
0
        public void PlotGraph(GPSData data)
        {
            VisibleGLONASS = VisibleGPS = UsedGLONASS = UsedGPS = 0;

            int counter = 0;

            for (int i = 0; i < 32; i++)
            {
                if (data.GPS[i].Signal_Status == 1)
                {
                    try
                    {
                        chart1.Series[0].Points[counter].SetValueXY(i.ToString() + "(" + data.GPS[i].SNR.ToString() + ")", data.GPS[i].SNR);
                        chart1.Series[0].Points[counter].Color = Color.Blue;
                    }
                    catch
                    {
                        chart1.Series[0].Points.AddXY(i.ToString() + "(" + data.GPS[i].SNR.ToString() + ")", data.GPS[i].SNR);
                        chart1.Series[0].Points[chart1.Series[0].Points.Count - 1].Color = Color.Blue;
                    }
                    VisibleGPS++;
                    counter++;
                }
                if (data.GPS[i].Signal_Status == 2)
                {
                    try
                    {
                        chart1.Series[0].Points[counter].SetValueXY(i.ToString() + "(" + data.GPS[i].SNR.ToString() + ")", data.GPS[i].SNR);
                        chart1.Series[0].Points[counter].Color = Color.Green;
                    }
                    catch
                    {
                        chart1.Series[0].Points.AddXY(i.ToString() + "(" + data.GPS[i].SNR.ToString() + ")", data.GPS[i].SNR);
                        chart1.Series[0].Points[chart1.Series[0].Points.Count - 1].Color = Color.Green;
                    }
                    VisibleGPS++;
                    UsedGPS++;
                    counter++;
                }
            }
            //removing previous unneccesary datas
            if (counter < chart1.Series[0].Points.Count && counter != 0)
            {
                for (int i = chart1.Series[0].Points.Count - 1; i >= counter; i--)
                {
                    chart1.Series[0].Points.RemoveAt(i);
                }
            }
            counter = 0;
            for (int i = 0; i < 32; i++)
            {
                if (data.Glonass[i].Signal_Status == 1)
                {
                    try
                    {
                        chart2.Series[0].Points[counter].SetValueXY(i.ToString() + "(" + data.Glonass[i].SNR.ToString() + ")", data.Glonass[i].SNR);
                        chart2.Series[0].Points[counter].Color = Color.Blue;
                    }
                    catch
                    {
                        chart2.Series[0].Points.AddXY(i.ToString() + "(" + data.Glonass[i].SNR.ToString() + ")", data.Glonass[i].SNR);
                        chart2.Series[0].Points[chart1.Series[0].Points.Count - 1].Color = Color.Blue;
                    }
                    VisibleGLONASS++;
                    counter++;
                }
                if (data.Glonass[i].Signal_Status == 2)
                {
                    try
                    {
                        chart2.Series[0].Points[counter].SetValueXY(i.ToString() + "(" + data.Glonass[i].SNR.ToString() + ")", data.Glonass[i].SNR);
                        chart2.Series[0].Points[counter].Color = Color.Green;
                    }
                    catch
                    {
                        chart2.Series[0].Points.AddXY(i.ToString() + "(" + data.Glonass[i].SNR.ToString() + ")", data.Glonass[i].SNR);
                        chart2.Series[0].Points[chart1.Series[0].Points.Count - 1].Color = Color.Green;
                    }
                    VisibleGLONASS++;
                    UsedGLONASS++;
                    counter++;
                }
            }
            //removing previous unneccesary datas
            if (counter < chart2.Series[0].Points.Count && counter != 0)
            {
                for (int i = chart2.Series[0].Points.Count - 1; i >= counter; i--)
                {
                    chart2.Series[0].Points.RemoveAt(i);
                }
            }
            updateLabels(data.Time, VisibleGPS, UsedGPS, VisibleGLONASS, UsedGLONASS);
        }
示例#42
0
        public void BuildCSVFile_Lerp(string imgFolder)
        {
            if (imgFolder.Length < 3)
            {
                Program.AddLog("BuildCSVFile_Lerp: wrong Path." + imgFolder);
                return;
            }
            if (!Directory.Exists(imgFolder))
            {
                Program.AddLog("BuildCSVFile_Lerp: No Path." + imgFolder);
                return;
            }
            if (m_gps_data.Count < 1)
            {
                return;
            }
            string[]     files        = Directory.GetFiles(imgFolder);
            string       srcFilename  = Path.GetFileNameWithoutExtension(gps_csv_filename);
            string       destPath     = Path.GetDirectoryName(gps_csv_filename);
            string       destFilename = Path.Combine(destPath, srcFilename + "_lerp.csv");
            StreamWriter writer       = new StreamWriter(destFilename);

            writer.WriteLine("imagename,X,Y,Z");
            GPSData firstGPSData = m_gps_data.First().Value;

            foreach (var file in files)
            {
                string ext = Path.GetExtension(file);
                ext = ext.ToLower();
                if (ext == ".jpg")
                {
                    string filename   = Path.GetFileNameWithoutExtension(file);
                    string keyword    = "";
                    int    idx        = 0;
                    bool   isFilename = XMPGenerator.GetIndexAndKeyword(out keyword, out idx, filename);
                    if (!isFilename)
                    {
                        continue;
                    }
                    idx -= 1;
                    int gpsIdx     = idx / 30;
                    int gpsSecStep = idx % 30;
                    gpsIdx += 1;
                    int gpsIdxNext = gpsIdx + 1;
                    if (!m_gps_data.ContainsKey(gpsIdx))
                    {
                        continue;
                    }
                    if (!m_gps_data.ContainsKey(gpsIdxNext))
                    {
                        continue;
                    }
                    GPSData gpsData  = m_gps_data[gpsIdx];
                    GPSData gpsData2 = m_gps_data[gpsIdxNext];
                    double  p        = gpsSecStep / 30.0;
                    double  posX     = (gpsData2.posX - gpsData.posX) * p + gpsData.posX;
                    double  posY     = (gpsData2.posY - gpsData.posY) * p + gpsData.posY;
                    double  altitude = (gpsData2.altitude - gpsData.altitude) * p + gpsData.altitude;

                    string line_data = string.Format("{0},{1},{2},{3}", Path.GetFileName(file), posX, posY, altitude);
                    writer.WriteLine(line_data);
                }
            }

            writer.Close();
        }
示例#43
0
        protected bool CorrectGpsData(GPSData data)
        {
            GPSData[] refgpsdatas;

            System.Collections.ArrayList list = new System.Collections.ArrayList();
            lock (((UbloxGPSController)controller).refGpsDataQueue)
            {
                refgpsdatas = ((UbloxGPSController)controller).refGpsDataQueue.ToArray();
            }

            //if (data.TimeStamp > refgpsdatas[0].TimeStamp)
            //{
            //    lock (refgpsdatas)
            //    {
            //        System.Threading.Monitor.Wait(refgpsdatas);
            //    }
            //}
            for (int i = 0; i < refgpsdatas.Length; i++)
            {
                if (refgpsdatas[i].TimeStamp != null && data.TimeStamp == refgpsdatas[i].TimeStamp)
                {

                    //   data.SetPrrOffset(refgpsdatas[i].PrOffset,refgpsdatas[i].CPrOffset);
                    data.SetPrsmOffset(refgpsdatas[i], refgpsdatas[i].PrOffset, refgpsdatas[i].CPrOffset);
                    if (data.satelliteIds.Length < 5) //有效衛星數至少5顆
                        return false;

                    return true;
                }

            }

            return false;
        }