Example #1
2
        public static Folder PlacemarkFolder(IQueryable<Cave> caves)
        {
            //List<Placemark> cavePlacemarkList = new List<Placemark>();
            Folder caveFolder = new Folder();
            caveFolder.Name = "Cave Folder";
            foreach (Cave cave in caves)
            {
                foreach (var entrance in cave.Entrances)
                {
                    Placemark placemark = new Placemark();
                    placemark.Name = cave.Name + " (E" + entrance.Name + ")";
                    placemark.Description = new Description() { Text = cave.Description };

                    Point point = new Point();
                    point.Coordinate = new Vector(entrance.GeoLocation.Latitude ?? 0, entrance.GeoLocation.Longitude ?? 0, entrance.GeoLocation.Elevation ?? 0);

                    placemark.Geometry = point;

                    caveFolder.AddFeature(placemark);
                }

            }

            return caveFolder;
        }
Example #2
1
        public void TestCalculateLookAt()
        {
            Placemark placemark = null;
            Assert.That(() => placemark.CalculateLookAt(),
                        Throws.TypeOf<ArgumentNullException>());

            placemark = new Placemark();
            Assert.That(placemark.CalculateLookAt(), Is.Null); // Nothing to look at

            Point point = new Point();
            point.Coordinate = new Vector(37, -122);
            placemark.Geometry = point;

            var lookat = placemark.CalculateLookAt();
            Assert.That(lookat, Is.Not.Null);
            Assert.That(lookat.Latitude, Is.EqualTo(37.0));
            Assert.That(lookat.Longitude, Is.EqualTo(-122.0));
            Assert.That(lookat.Range, Is.EqualTo(1000.0));
            Assert.That(lookat.AltitudeMode, Is.EqualTo(AltitudeMode.RelativeToGround));
            Assert.That(lookat.Altitude, Is.Null);
            Assert.That(lookat.Heading, Is.Null);
            Assert.That(lookat.Tilt, Is.Null);

            LineString line = new LineString();
            line.Coordinates = new CoordinateCollection();
            line.Coordinates.Add(new Vector(37, -122));
            line.Coordinates.Add(new Vector(38, -121));

            placemark = new Placemark();
            placemark.Geometry = line;

            lookat = placemark.CalculateLookAt();
            Assert.That(lookat.Latitude, Is.EqualTo(37.5));
            Assert.That(lookat.Longitude, Is.EqualTo(-121.5));
            Assert.That(lookat.Range, Is.EqualTo(135123.4361).Within(0.0001));
        }
Example #3
1
        private void writeKML(string filename)
        {
            Color[] colours = { Color.Red, Color.Orange, Color.Yellow, Color.Green, Color.Blue, Color.Indigo, Color.Violet, Color.Pink };

            Document kml = new Document();

            Tour tour = new Tour();
            tour.Name = "First Person View";
            Playlist tourplaylist = new Playlist();

            AddNamespace(kml, "gx", "http://www.google.com/kml/ext/2.2");

            Style style = new Style();
            style.Id = "yellowLineGreenPoly";
            style.Line = new LineStyle(new Color32(HexStringToColor("7f00ffff")), 4);

            PolygonStyle pstyle = new PolygonStyle();
            pstyle.Color = new Color32(HexStringToColor("7f00ff00"));
            style.Polygon = pstyle;

            kml.AddStyle(style);

            // create sub folders
            Folder planes = new Folder();
            planes.Name = "Planes";
            kml.AddFeature(planes);

            // coords for line string
            CoordinateCollection coords = new CoordinateCollection();

            int a = 1;
            int c = -1;
            DateTime lasttime = DateTime.MaxValue;
            DateTime starttime = DateTime.MinValue;
            Color stylecolor = Color.AliceBlue;
            string mode = "";
            if (flightdata.Count > 0)
            {
                mode = flightdata[0].mode;
            }
            foreach (CurrentState cs in flightdata)
            {
                progressBar1.Value = 50 + (int)((float)a / (float)flightdata.Count * 100.0f / 2.0f);
                progressBar1.Refresh();

                if (starttime == DateTime.MinValue)
                {
                    starttime = cs.datetime;
                    lasttime = cs.datetime;
                }

                if (mode != cs.mode || flightdata.Count == a)
                {
                    c++;

                    LineString ls = new LineString();
                    ls.AltitudeMode = SharpKml.Dom.AltitudeMode.Absolute;
                    ls.Extrude = true;

                    ls.Coordinates = coords;

                    Placemark pm = new Placemark();

                    pm.Name = c + " Flight Path " + mode;
                    pm.StyleUrl = new Uri("#yellowLineGreenPoly", UriKind.Relative);
                    pm.Geometry = ls;

                    SharpKml.Dom.TimeSpan ts = new SharpKml.Dom.TimeSpan();
                    ts.Begin = starttime;
                    ts.End = cs.datetime;

                    pm.Time = ts;

                    // setup for next line
                    mode = cs.mode;
                    starttime = cs.datetime;

                    stylecolor = colours[c % (colours.Length - 1)];

                    Style style2 = new Style();
                    style2.Line = new LineStyle(new Color32(stylecolor), 4);

                    pm.StyleSelector = style2;

                    kml.AddFeature(pm);

                    coords = new CoordinateCollection();
                }

                coords.Add(new Vector(cs.lat, cs.lng, cs.alt));

                SharpKml.Dom.Timestamp tstamp = new SharpKml.Dom.Timestamp();
                tstamp.When = cs.datetime;

                FlyTo flyto = new FlyTo();

                flyto.Duration = (cs.datetime - lasttime).TotalMilliseconds / 1000.0;

                flyto.Mode = FlyToMode.Smooth;
                SharpKml.Dom.Camera cam = new SharpKml.Dom.Camera();
                cam.AltitudeMode = SharpKml.Dom.AltitudeMode.Absolute;
                cam.Latitude = cs.lat;
                cam.Longitude = cs.lng;
                cam.Altitude = cs.alt;
                cam.Heading = cs.yaw;
                cam.Roll = -cs.roll;
                cam.Tilt = (90 - (cs.pitch * -1));

                cam.GXTimePrimitive = tstamp;

                flyto.View = cam;
                //if (Math.Abs(flyto.Duration.Value) > 0.1)
                {
                    tourplaylist.AddTourPrimitive(flyto);
                    lasttime = cs.datetime;
                }

                Placemark pmplane = new Placemark();
                pmplane.Name = "Plane " + a;

                pmplane.Time = tstamp;

                pmplane.Visibility = false;

                SharpKml.Dom.Location loc = new SharpKml.Dom.Location();
                loc.Latitude = cs.lat;
                loc.Longitude = cs.lng;
                loc.Altitude = cs.alt;

                SharpKml.Dom.Orientation ori = new SharpKml.Dom.Orientation();
                ori.Heading = cs.yaw;
                ori.Roll = -cs.roll;
                ori.Tilt = -cs.pitch;

                SharpKml.Dom.Scale sca = new SharpKml.Dom.Scale();

                sca.X = 2;
                sca.Y = 2;
                sca.Z = 2;

                Model model = new Model();
                model.Location = loc;
                model.Orientation = ori;
                model.AltitudeMode = SharpKml.Dom.AltitudeMode.Absolute;
                model.Scale = sca;

                try
                {
                    Description desc = new Description();
                    desc.Text = @"<![CDATA[
              <table>
                <tr><td>Roll: " + model.Orientation.Roll + @" </td></tr>
                <tr><td>Pitch: " + model.Orientation.Tilt + @" </td></tr>
                <tr><td>Yaw: " + model.Orientation.Heading + @" </td></tr>

              </table>
            ]]>";

                    pmplane.Description = desc;
                }
                catch { }

                Link link = new Link();
                link.Href = new Uri("block_plane_0.dae", UriKind.Relative);

                model.Link = link;

                pmplane.Geometry = model;

                planes.AddFeature(pmplane);

                a++;
            }

            tour.Playlist = tourplaylist;

            kml.AddFeature(tour);

            Serializer serializer = new Serializer();
            serializer.Serialize(kml);

            //Console.WriteLine(serializer.Xml);

            StreamWriter sw = new StreamWriter(filename);
            sw.Write(serializer.Xml);
            sw.Close();

            // create kmz - aka zip file

            FileStream fs = File.Open(filename.Replace(Path.GetExtension(filename), ".kmz"), FileMode.Create);
            ZipOutputStream zipStream = new ZipOutputStream(fs);
            zipStream.SetLevel(9); //0-9, 9 being the highest level of compression
            zipStream.UseZip64 = UseZip64.Off; // older zipfile

            // entry 1
            string entryName = ZipEntry.CleanName(Path.GetFileName(filename)); // Removes drive from name and fixes slash direction
            ZipEntry newEntry = new ZipEntry(entryName);
            newEntry.DateTime = DateTime.Now;

            zipStream.PutNextEntry(newEntry);

            // Zip the file in buffered chunks
            // the "using" will close the stream even if an exception occurs
            byte[] buffer = new byte[4096];
            using (FileStream streamReader = File.Open(filename,FileMode.Open,FileAccess.Read,FileShare.ReadWrite))
            {
                StreamUtils.Copy(streamReader, zipStream, buffer);
            }
            zipStream.CloseEntry();

            filename = Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar + "block_plane_0.dae";

            // entry 2
            entryName = ZipEntry.CleanName(Path.GetFileName(filename)); // Removes drive from name and fixes slash direction
            newEntry = new ZipEntry(entryName);
            newEntry.DateTime = DateTime.Now;

            zipStream.PutNextEntry(newEntry);

            // Zip the file in buffered chunks
            // the "using" will close the stream even if an exception occurs
            buffer = new byte[4096];
            using (FileStream streamReader = File.OpenRead(filename))
            {
                StreamUtils.Copy(streamReader, zipStream, buffer);
            }
            zipStream.CloseEntry();

            zipStream.IsStreamOwner = true;	// Makes the Close also Close the underlying stream
            zipStream.Close();

            File.Delete(filename);

            flightdata.Clear();
        }
Example #4
0
        public void TestClone()
        {
            Placemark placemark = null;
            Assert.That(() => placemark.Clone(),
                        Throws.TypeOf<ArgumentNullException>());

            placemark = new Placemark();
            placemark.Id = "ID";
            placemark.Geometry = new Point();
            var clone = placemark.Clone();

            Assert.That(clone, Is.Not.SameAs(placemark));
            Assert.That(clone.Id, Is.EqualTo(placemark.Id));  // Test attribute
            Assert.That(clone.Geometry, Is.Not.Null); // Test element

            // Make sure as we change one the other doesn't
            ((Point)clone.Geometry).Extrude = true;
            Assert.That(((Point)clone.Geometry).Extrude,
                       Is.Not.EqualTo(((Point)placemark.Geometry).Extrude));

            Folder folder = new Folder();
            folder.AddFeature(placemark);
            folder.AddFeature(new Document());

            var copy = folder.Clone();
            Assert.That(copy.Features.Count(), Is.EqualTo(folder.Features.Count()));
            placemark.Id = "changed";
            Assert.That(folder.FindFeature(placemark.Id), Is.Not.Null);
            Assert.That(copy.FindFeature(placemark.Id), Is.Null);
        }
Example #5
0
        public static void Run()
        {
            // Create the style first
            var style = new Style();
            style.Id = "randomColorIcon";
            style.Icon = new IconStyle();
            style.Icon.Color = new Color32(255, 0, 255, 0);
            style.Icon.ColorMode = ColorMode.Random;
            style.Icon.Icon = new IconStyle.IconLink(new Uri("http://maps.google.com/mapfiles/kml/pal3/icon21.png"));
            style.Icon.Scale = 1.1;

            // Now create the object to apply the style to
            var placemark = new Placemark();
            placemark.Name = "IconStyle.kml";
            placemark.StyleUrl = new Uri("#randomColorIcon", UriKind.Relative);
            placemark.Geometry = new Point
            {
                Coordinate = new Vector(37.831145, -122.36868)
            };

            // Package it all together...
            var document = new Document();
            document.AddFeature(placemark);
            document.AddStyle(style);

            // And display the result
            var serializer = new Serializer();
            serializer.Serialize(document);
            Console.WriteLine(serializer.Xml);
        }
        public void CanSaveAndRestoreHiddenData()
        {
            var placemark = new Placemark { Name = "TestPlacemark" };

            placemark.ExtendedData = new ExtendedData();
            placemark.ExtendedData.AddHiddenData(new HiddenData { Name = "HIDDEN_KEY", Value = "A VALUE" });

            var buffer = new byte[2048];
            using (var ms = new MemoryStream(buffer))
            {
                KmlFile.Create(placemark, false).Save(ms);
                ms.Flush();

                using (var reader = new StreamReader(new MemoryStream(buffer)))
                {
                    Console.WriteLine(reader.ReadToEnd());
                }

                using (var ms2 = new MemoryStream(buffer))
                {
                    var kmlFile = KmlFile.Load(ms2);

                    Assert.That(kmlFile.Root, Is.InstanceOf<Placemark>());
                    var placemarkCopy = kmlFile.Root as Placemark;

                    Assert.That(placemarkCopy.ExtendedData.HiddenData.Any(), Is.True);

                    var hidden = placemarkCopy.ExtendedData.HiddenData.First(h => h.Name == "HIDDEN_KEY");

                    Assert.That(hidden, Is.Not.Null);
                }

            }
        }
Example #7
0
        public void AddLine(Line lineIn, Dictionary <string, string> dicData)
        {
            var colorLine = sb.Color32.Parse(ConvertColor(sb.Color32.Parse(lineIn.Color), lineIn.Opacity));
            var style     = new sd.Style
            {
                Line = new sd.LineStyle
                {
                    Color = colorLine,
                    Width = lineIn.Width,
                }
            };
            var line = new sd.LineString
            {
                Extrude     = true,
                Tessellate  = true,
                Coordinates = lineIn.Vectors
            };

            var placemark = new sd.Placemark
            {
                Name         = lineIn.Name,
                Geometry     = line,
                ExtendedData = ExtendedData(dicData)
            };

            placemark.AddStyle(style);

            Document.AddFeature(placemark);
        }
Example #8
0
        public static void Run()
        {
            Console.WriteLine("Creating a point at 37.42052549 latitude and -122.0816695 longitude.\n");

            // This will be used for the placemark
            Point point = new Point();
            point.Coordinate = new Vector(37.42052549, -122.0816695);

            Placemark placemark = new Placemark();
            placemark.Name = "Cool Statue";
            placemark.Geometry = point;

            // This is the root element of the file
            Kml kml = new Kml();
            kml.Feature = placemark;

            Serializer serializer = new Serializer();
            serializer.Serialize(kml);
            Console.WriteLine(serializer.Xml);

            Console.WriteLine("\nReading Xml...");

            Parser parser = new Parser();
            parser.ParseString(serializer.Xml, true);

            kml = (Kml)parser.Root;
            placemark = (Placemark)kml.Feature;
            point = (Point)placemark.Geometry;

            Console.WriteLine("Latitude:{0} Longitude:{1}", point.Coordinate.Latitude, point.Coordinate.Longitude);
        }
Example #9
0
        public static void Run()
        {
            var point = new sd.Point
            {
                Coordinate = new sb.Vector(37.42052549, -122.0816695)
            };

            var placemark = new sd.Placemark
            {
                Name     = "Да круто",
                Geometry = point
            };

            var point1 = new sd.Point
            {
                Coordinate = new sb.Vector(37.419837, -122.078902)
            };

            var placemark1 = new sd.Placemark
            {
                Name     = "Да круто",
                Geometry = point1
            };

            var document = new sd.Document
            {
                Description = new sd.Description {
                    Text = "Документ"
                }
            };

            var kml = new sd.Kml
            {
                Feature = document
            };

            var folder = new sd.Folder
            {
                Description = new sd.Description {
                    Text = "Светофоры"
                },
                Name = "СО"
            };

            folder.AddFeature(placemark);
            document.AddFeature(folder);
            document.AddFeature(placemark1);

            //var serializer = new sb.Serializer();

            //using FileStream fileStream = new FileStream("kmlTest.kml", FileMode.OpenOrCreate);
            //serializer.Serialize(kml, fileStream);
            var kmlFile = KmlFile.Create(kml, true);

            //using KmzFile kmz = SaveKmlAndLinkedContentIntoAKmzArchive(kmlFile, OutputPath);
            //using Stream output = File.Create(OutputPath);
            //kmz.Save(output);
            //Console.WriteLine("Saved to '{0}'.", OutputPath);
            //Console.ReadKey();
        }
Example #10
0
        public void KmlFileURLTest()
        {
            GeoAPI.GeometryServiceProvider.Instance = NetTopologySuite.NtsGeometryServices.Instance;
            HttpWebRequest  req  = (HttpWebRequest)WebRequest.Create(new Uri("http://112.74.67.213:6080/huayu/TestData/raw/master/online/Polygontwo_LayerToKML.kml"));
            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            var             kml  = KmlProvider.FromKml(resp.GetResponseStream());

            Assert.IsNotNull(kml);
            var fullExtent = kml.GetExtents();

            Assert.IsNotNull(fullExtent);
            List <string> ids = kml.GetObjectIDsInViewForSList(fullExtent);

            Assert.AreEqual(ids[0], "ID_00000");
            FeatureDataRow dr = kml.GetFeature(ids[0]);

            Assert.IsNotNull(dr);
            Assert.IsNotNull(dr.ItemArray);
            Assert.AreEqual(dr.ItemArray[0], "ID_00000");
            Assert.AreEqual(dr.ItemArray[1], "PolyStyle00");

            SharpKml.Dom.Placemark placemark = (SharpKml.Dom.Placemark)dr.ItemArray[2];
            Assert.IsNotNull(placemark);
            Assert.AreEqual(placemark.Id, "ID_00000");
            Assert.AreEqual(placemark.Name, "a");
            Assert.AreEqual(placemark.Description.Text.Trim().Length, 1095);
            Assert.AreEqual(placemark.StyleUrl.ToString(), "#PolyStyle00");
            Assert.IsNull(placemark.Visibility);
            Assert.IsNull(placemark.Open);
            Assert.IsNull(placemark.Address);
            Assert.IsNotNull(placemark.Snippet);
            Assert.IsNotNull(dr.Geometry);

            Assert.IsInstanceOf(typeof(GeometryCollection), dr.Geometry);
            GeometryCollection gc = (GeometryCollection)dr.Geometry;

            Assert.AreEqual(gc.NumGeometries, 3);
            Func <List <Coordinate>, string> gwl = (list) =>
            {
                var result = "";
                foreach (var item in list)
                {
                    result += $"{item.X},{item.Y}  ";
                }

                return(result);
            };

            for (int i = 0; i < gc.NumGeometries; i++)
            {
                IGeometry geo = gc.GetGeometryN(i);
                Console.WriteLine($"{i}:{geo.GeometryType},{gwl(geo.Coordinates.ToList())}");
            }
            Assert.IsNotNull(dr.Table);
            Assert.AreEqual(dr.IsFeatureGeometryNull(), false);
            Assert.AreEqual(kml.GetFeatureCount(), 2);
            Console.WriteLine(string.Format("kml.GetFeatureCount():{0}", kml.GetFeatureCount()));
            Console.WriteLine(string.Format("kml.GetExtents():{0}", kml.GetExtents()));
        }
        public SharpKml.Dom.Placemark makeSimplePlacemark(SharpKml.Dom.LineString lineString, string name)
        {
            var pm = new SharpKml.Dom.Placemark();

            pm.Geometry = lineString;
            pm.Name     = name;
            return(pm);
        }
        public SharpKml.Dom.Placemark makeSimplePlacemark(SharpKml.Dom.Polygon poly, string name, string styleName)
        {
            var pm = new SharpKml.Dom.Placemark();

            pm.Geometry = poly;
            pm.Name     = name;
            pm.StyleUrl = new Uri("#" + styleName, UriKind.Relative);
            return(pm);
        }
Example #13
0
        public override void addAddresstoKmlDocument(KmlPrepData prepData, Document KmlDoc)
        {
            Point point = new Point();

            point.Coordinate = new Vector(prepData.lat, prepData.lng);

            Placemark placemark = new Placemark();
            placemark.Geometry = point;
            placemark.Name = prepData.name;

            KmlDoc.AddFeature(placemark);
        }
Example #14
0
        /// <summary>
        /// Assembles location to folder.
        /// </summary>
        /// <param name="dbLocation">The database location.</param>
        /// <returns>Dom.Folder.</returns>
        private static Dom.Folder AssembleToFolder(FormationMatcher dbLocation)
        {
            Dom.Folder locationGroup = new Dom.Folder {
                Name = dbLocation.FormationName
            };
            if (!string.IsNullOrWhiteSpace(dbLocation.SubFormationName))
            {
                locationGroup.Name += " (" + dbLocation.SubFormationName + ")";
            }
            Location location = dbLocation.MatchedLocation;

            if (location == null)
            {
                return(locationGroup);
            }

            // This will be used for the placemark
            Dom.Point point = new Dom.Point {
                Coordinate = new Vector(location.Latitude, location.Longitude)
            };

            Dom.Placemark placemark = new Dom.Placemark {
                Name = location.Name
            };
            if (!string.IsNullOrWhiteSpace(location.OtherName))
            {
                placemark.Name += " (" + location.OtherName + ")";
            }
            placemark.Geometry = point;

            locationGroup.AddFeature(placemark);
            //foreach (PeakbaggerLocation location in dbLocation.PossibleLocations)
            //{
            //    // This will be used for the placemark
            //    Dom.Point point = new Dom.Point {Coordinate = new Vector(location.Latitude, location.Longitude)};

            //    Dom.Placemark placemark = new Dom.Placemark {Name = location.Name};
            //    if (!string.IsNullOrWhiteSpace(location.OtherName))
            //    {
            //        placemark.Name += " (" + location.OtherName + ")";
            //    }
            //    placemark.Geometry = point;

            //    locationGroup.AddFeature(placemark);
            //}
            return(locationGroup);

            // Add to the root
            //kml.Feature = locationGroup;

            //WriteToKml(filePath, kml);
            //Console.WriteLine(serializer.Xml);
        }
        private void FindCheckpoints(Placemark p, List<CheckpointLocation> locations)
        {
            Point point = p.Flatten().OfType<Point>().FirstOrDefault();
              if (point == null)
            return;

              CheckpointLocation location = new CheckpointLocation
              {
            Name = p.Name,
            Location = point.Coordinate
              };
              locations.Add(location);
        }
Example #16
0
 // TODO: Need to change so that you can handle 1's and 2's in column not just not 0
 public override void classifyProspect(JoinedProspect joinedProspect ,Placemark placemark)
 {
     if (joinedProspect.currentCustomerFlag != 0)
     {
         placemark.StyleUrl = new Uri("#currentCustomer", UriKind.Relative);
     }
     else if (joinedProspect.doNotContactFlag != 0)
     {
         placemark.StyleUrl = new Uri("#doNoContact", UriKind.Relative);
     }
     else if (joinedProspect.cancelledFlag != 0)
     {
         placemark.StyleUrl = new Uri("#cancelledCustomer", UriKind.Relative);
     }
 }
Example #17
0
        // this adds an element to the document and adds a place marker
        public override void addElementToKmlDocument(JoinedProspect joinedProspect, Document kmlDoc)
        {
            Point point = new Point();

               point.Coordinate = new Vector(joinedProspect.CorrectedLatitude, joinedProspect.CorrectedLongitude);

               Placemark placemark = new Placemark();
               placemark.Geometry = point;
               placemark.Name = joinedProspect.firstName + " " + joinedProspect.lastName;
               placemark.Address = joinedProspect.Address;
               placemark.Description = new Description() { Text = "ClassFP: " + joinedProspect.classFP + " IncorpName: " + joinedProspect.incorpName + " Address: " + joinedProspect.Address + " <h3>HelloWorld</h3>"};
               classifyProspect(joinedProspect, placemark);

               kmlDoc.AddFeature(placemark);
        }
Example #18
0
        public void TestAddChild()
        {
            var child = new Placemark();
            var parent1 = new Folder();
            var parent2 = new Folder();

            parent1.AddFeature(child);

            // child belongs to another element, should throw
            Assert.That(() => parent2.AddFeature(child),
                        Throws.TypeOf<InvalidOperationException>());

            // child has already been added once
            Assert.That(() => parent1.AddFeature(child),
                        Throws.TypeOf<InvalidOperationException>());
        }
Example #19
0
        public static void SaveLineString(List <PointLatLng> points, string name, string filePath)
        {
            Placemark root = new Placemark
            {
                Name = name
            };
            LineString str = new LineString
            {
                Coordinates = new CoordinateCollection()
            };

            foreach (PointLatLng lng in points)
            {
                str.Coordinates.Add(new Vector(lng.Lat, lng.Lng));
            }
            root.Geometry = str;
            KmlFile.Create(root, false).Save(filePath);
        }
Example #20
0
        public static void SavePoints(List <PointLatLng> points, string name, string filePath)
        {
            Kml      root     = new Kml();
            Document document = new Document();

            foreach (PointLatLng lng in points)
            {
                Placemark feature = new Placemark();
                Point     point   = new Point
                {
                    Coordinate = new Vector(lng.Lat, lng.Lng)
                };
                feature.Geometry = point;
                document.AddFeature(feature);
            }
            root.Feature = document;
            KmlFile.Create(root, false).Save(filePath);
        }
Example #21
0
        public void TestGetParent()
        {
            Placemark placemark = null;
            Assert.That(() => placemark.GetParent<Folder>(),
                        Throws.TypeOf<ArgumentNullException>());

            placemark = new Placemark();
            Assert.That(placemark.GetParent<Folder>(), Is.Null);

            var folder = new Folder();
            folder.AddFeature(placemark);
            Assert.That(placemark.GetParent<Folder>(), Is.SameAs(folder));
            Assert.That(placemark.GetParent<Kml>(), Is.Null);

            var kml = new Kml();
            kml.Feature = folder;
            Assert.That(placemark.GetParent<Kml>(), Is.SameAs(kml));
        }
Example #22
0
        public void TestCalculateBounds()
        {
            Placemark placemark = null;
            Assert.That(() => placemark.CalculateBounds(),
                       Throws.TypeOf<ArgumentNullException>());

            placemark = new Placemark();
            Assert.That(placemark.CalculateBounds(), Is.Null);

            using (var stream = SampleData.CreateStream("Engine.Data.Bounds.kml"))
            {
                KmlFile file = KmlFile.Load(stream);
                foreach (var test in TestCases)
                {
                    RunTestCase(file, test.Id, test.Box);
                }
            }
        }
Example #23
0
        public static void Run()
        {
            // Create our Kml
            var folder = new Folder();
            folder.Id = "f0";
            folder.Name = "Folder 0";

            var placemark = new Placemark();
            placemark.Id = "pm0";
            placemark.Name = "Placemark 0";
            folder.AddFeature(placemark);

            placemark = new Placemark();
            placemark.Id = "pm1";
            placemark.Name = "Placemark 1";
            folder.AddFeature(placemark);

            var kml = new Kml();
            kml.Feature = folder;

            // Display to the user
            var serializer = new Serializer();
            serializer.Serialize(kml);
            Console.WriteLine("Original Kml:\n" + serializer.Xml);

            // This is what we're going to change to
            placemark = new Placemark();
            placemark.Geometry = new Point { Coordinate = new Vector(38, -120) };
            placemark.Name = "new name";
            placemark.TargetId = "pm0";

            var update = new Update();
            update.AddUpdate(new ChangeCollection() { placemark });

            serializer.Serialize(update);
            Console.WriteLine("\nUpdate:\n" + serializer.Xml);

            // Run the update
            var file = KmlFile.Create(kml, false);
            update.Process(file);

            serializer.Serialize(kml);
            Console.WriteLine("\nUpdated Kml:\n" + serializer.Xml);
        }
Example #24
0
        public void TestChangeCoordinates()
        {
            // Create the target
            var point = new Point();
            point.Coordinate = new Vector(38.38, -122.122);

            var placemark = new Placemark();
            placemark.Id = "placemark123";
            placemark.Geometry = point;
            placemark.Name = "placemark name";

            var file = KmlFile.Create(placemark, false);

            // Now create the Update
            const double latitude = -38.38;
            const double longitude = 122.122;

            point = new Point();
            point.Coordinate = new Vector(latitude, longitude);

            placemark = new Placemark();
            placemark.Geometry = point;
            placemark.TargetId = "placemark123";

            var change = new ChangeCollection();
            change.Add(placemark);

            var update = new Update();
            update.AddUpdate(change);

            // Now test the update worked
            update.Process(file);

            placemark = file.Root as Placemark;
            Assert.That(placemark, Is.Not.Null);
            Assert.That(placemark.Id, Is.EqualTo("placemark123"));
            Assert.That(placemark.Name, Is.EqualTo("placemark name"));

            point = placemark.Geometry as Point;
            Assert.That(point, Is.Not.Null);
            Assert.That(point.Coordinate.Latitude, Is.EqualTo(latitude));
            Assert.That(point.Coordinate.Longitude, Is.EqualTo(longitude));
        }
        /// <summary>
        /// Gerador de Kml
        /// </summary>
        /// <param name="pLinhaDados"></param>
        /// <param name="pTipoDados"></param>
        /// <param name="pNome"></param>
        /// <param name="pNumOcorrencia"></param>
        public void GerarKml(string pLinhaDados, eTipoDadoGeografico pTipoDados, string pNome, int pNumOcorrencia)
        {
            Placemark placemark = new Placemark();
            placemark.Name = pNome;
            string sCor = "";

            if (pNumOcorrencia >= 20)
                sCor = "ff0000ff";
            else if (pNumOcorrencia >= 10)
                sCor = "ff8080ff";
            else if (pNumOcorrencia >= 5)
                sCor = "ffc0c0ff";
            else if (pNumOcorrencia >= 0)
                sCor = "ffffffff";

            StringBuilder sbStilo = new StringBuilder();
            sbStilo.AppendLine("<color>");
            sbStilo.AppendLine(sCor);
            sbStilo.AppendLine("</color>");

                                     string sXml = "";
            // This is the root element of the file
            Kml kml = new Kml();
            kml.Feature = placemark;

            Serializer serializer = new Serializer();
            serializer.Serialize(kml);

            int iIndiceStilo = serializer.Xml.LastIndexOf("<Placemark>") + 11;

            sXml = serializer.Xml.Insert(iIndiceStilo, sbStilo.ToString());

            int iIndiceInicial = sXml.LastIndexOf("</name>") + 8;

            sXml = sXml.Insert(iIndiceInicial, pLinhaDados);

            string caminho = @"C:\Users\" + Environment.UserName + @"\Desktop\ArquivoKml" + DateTime.Now.ToString().Replace("/", "-").Replace(":", ".") + ".kml";
            StreamWriter arquivo = new StreamWriter(caminho);
            arquivo.WriteLine(sXml);
            arquivo.Close();
            //MessageBox.Show("Arquivo Gravado em " + caminho + " com sucesso");
        }
Example #26
0
        public void AddPoligon(Polygon poly, Dictionary <string, string> dicData)
        {
            var colorPoly = sb.Color32.Parse(ConvertColor(sb.Color32.Parse(poly.ColorPoly), poly.OpacityPoly));
            var colorLine = sb.Color32.Parse(ConvertColor(sb.Color32.Parse(poly.ColorLine), poly.OpacityLine));
            var style     = new sd.Style
            {
                Polygon = new sd.PolygonStyle
                {
                    Fill    = true,
                    Color   = colorPoly,
                    Outline = true
                },
                Line = new sd.LineStyle
                {
                    Color = colorLine,
                    Width = poly.WidthLine,
                }
            };
            var polygon = new sd.Polygon
            {
                Extrude       = true,
                Tessellate    = true,
                OuterBoundary = new sd.OuterBoundary
                {
                    LinearRing = new sd.LinearRing
                    {
                        Coordinates = poly.OuterBoundaryIs
                    }
                }
            };

            var placemark = new sd.Placemark
            {
                Name         = poly.Name,
                Geometry     = polygon,
                ExtendedData = ExtendedData(dicData)
            };

            placemark.AddStyle(style);

            Document.AddFeature(placemark);
        }
Example #27
0
        private async void ConvertFileToKml()
        {
            KmlFile kmlF;
            foreach(YouMapPoint yp in loadmap.Points)
            {
                Point p = new Point();
                Placemark pl = new Placemark();
                p.Coordinate = yp.getLocationAsVector();
                pl.Geometry = p;
                doc.AddFeature(pl);
                

            }
            foreach(YouMapPolyline yp in loadmap.Polylines)
            {
                LineString ln = new LineString();
                ln.Coordinates = yp.LocationAsCords;
                Placemark pl = new Placemark();
                pl.Geometry = ln;
                doc.AddFeature(pl);

               
            }
            kml = new Kml();
            kml.Feature = doc;
            kmlF = KmlFile.Create(kml, false);
            StorageFolder root = await IOFile.getMyRootfolder();
            StorageFile newFile = await root.CreateFileAsync("Bobby.kml", CreationCollisionOption.ReplaceExisting);


            


            using (IRandomAccessStream fileStream = await newFile.OpenAsync(FileAccessMode.ReadWrite))
            {
                 Stream myStream = fileStream.AsStreamForWrite();
                 kmlF.Save(myStream); 
               
            }

         }
Example #28
0
        public async System.Threading.Tasks.Task SaveAsKmlAsync()
        {
            Kml      kml      = new Kml();
            Document document = new Document();

            document.Name = "Weeds from ThistleTracker";
            kml.Feature   = document;
            // Loop & add weedspots
            foreach (WeedSpot spot in _spots)
            {
                Point point = new Point();
                point.Coordinate = new Vector(spot.Latitude, spot.Longitude);
                SharpKml.Dom.Placemark place = new SharpKml.Dom.Placemark();
                place.Name     = spot.Name;
                place.Geometry = point;
                document.AddFeature(place);
            }
            string fileName = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Weeds.kml");

            // delete if existing
            if (File.Exists(fileName))
            {
                File.Delete(fileName);
            }

            // Create KML file
            KmlFile kmlFile = KmlFile.Create(kml, true);

            using (FileStream stream = File.OpenWrite(fileName))
            {
                kmlFile.Save(stream);
            }

            // Share with other apps
            await Share.RequestAsync(new ShareFileRequest
            {
                Title = "ThistleTracker KML Export",
                File  = new ShareFile(fileName)
            });
        }
Example #29
0
        public static int SavePoints(List <PointLatLngWithProperty> points, string name, string filePath)
        {
            int      num      = 0;
            Kml      root     = new Kml();
            Document document = new Document();

            foreach (PointLatLngWithProperty property in points)
            {
                try
                {
                    if ((property.Point.Lat != 0.0) && (property.Point.Lng != 0.0))
                    {
                        Placemark feature = new Placemark();
                        Point     point   = new Point
                        {
                            Coordinate = new Vector(property.Point.Lat, property.Point.Lng)
                        };
                        feature.Geometry    = point;
                        feature.Description = new Description();
                        foreach (KeyValuePair <string, string> pair in property.Properties)
                        {
                            Description description = feature.Description;
                            description.Text = description.Text + string.Format("{0}:{1}\r\n", pair.Key, pair.Value);
                        }
                        document.AddFeature(feature);
                        num++;
                    }
                    continue;
                }
                catch
                {
                    continue;
                }
            }
            root.Feature = document;
            KmlFile.Create(root, false).Save(filePath);
            return(num);
        }
Example #30
0
 /// <summary>
 /// Extracts the placemarks from the feature.
 /// </summary>
 /// <param name="feature">The feature.</param>
 /// <param name="placemarks">The list to add the placemark to.</param>
 private static void ExtractPlacemarks(Dom.Feature feature, List <Dom.Placemark> placemarks)
 {
     // Is the passed in value a Placemark?
     Dom.Placemark placemark = feature as Dom.Placemark;
     if (placemark != null)
     {
         placemarks.Add(placemark);
     }
     else
     {
         // Is it a Container, as the Container might have a child Placemark?
         Dom.Container container = feature as Dom.Container;
         if (container == null)
         {
             return;
         }
         // Check each Feature to see if it's a Placemark or another Container
         foreach (var f in container.Features)
         {
             ExtractPlacemarks(f, placemarks);
         }
     }
 }
Example #31
0
        public void AddPoint(Point point, string idStyle, Dictionary <string, string> dicData, sd.Folder folder = null)
        {
            var pointDoc = new sd.Point
            {
                Coordinate = new sb.Vector(point.Lon, point.Lat)
            };

            var exdata = new sd.ExtendedData();

            foreach (var data in dicData)
            {
                var dataDoc = new sd.Data
                {
                    Name  = data.Key,
                    Value = data.Value
                };
                exdata.AddData(dataDoc);
            }

            var placemark = new sd.Placemark
            {
                Name         = point.Name,
                Geometry     = pointDoc,
                StyleUrl     = new Uri($"#{idStyle}"),
                ExtendedData = exdata
            };

            if (folder == null)
            {
                Document.AddFeature(placemark);
            }
            else
            {
                folder.AddFeature(placemark);
            }
        }
Example #32
0
        public void AddPoint(Point point, string idStyle, Dictionary <string, string> dicData, sd.Folder folder = null)
        {
            var pointDoc = new sd.Point
            {
                Coordinate = new sb.Vector(point.Lat, point.Lon)
            };

            var placemark = new sd.Placemark
            {
                Name         = point.Name,
                Geometry     = pointDoc,
                StyleUrl     = new Uri($"#{idStyle}", UriKind.Relative),
                ExtendedData = ExtendedData(dicData)
            };

            if (folder == null)
            {
                Document.AddFeature(placemark);
            }
            else
            {
                folder.AddFeature(placemark);
            }
        }
Example #33
0
        private bool parsePoint(Placemark placemark, DBStation_Bus dbStationBus, DBStation dbStation, BUS bus, ROUTE route, bool hasStation)
        {
            foreach (var lineString in placemark.Flatten().OfType<SharpKml.Dom.Point>())
            {
                IList<STATION> stationsNear = dbStation.SelectStationsNear(50,
                    Methods.ConvertLatLonToDbGeography(lineString.Coordinate.Longitude, lineString.Coordinate.Latitude));

                foreach (var station in stationsNear)
                {
                    STATION_BUSES stationBus = new STATION_BUSES();

                    stationBus.STATION = station;
                    stationBus.BUS = bus;

                    dbStationBus.AddStation_Buses_Route(route, stationBus);
                    hasStation = true;
                }
            }
            return hasStation;
        }
Example #34
0
        public void TestCalculateLookAtFolder()
        {
            Location location = new Location();
            location.Latitude = 0;
            location.Longitude = 0;

            Model model = new Model();
            model.Location = location;

            Placemark placemark = new Placemark();
            placemark.Geometry = model;

            Folder folder = new Folder();
            folder.AddFeature(placemark);

            var lookat = folder.CalculateLookAt();
            Assert.That(lookat.Latitude, Is.EqualTo(0.0));
            Assert.That(lookat.Longitude, Is.EqualTo(0.0));
            Assert.That(lookat.Range, Is.EqualTo(1000.0));

            Point point = new Point();
            point.Coordinate = new Vector(10, 10);

            PhotoOverlay overlay = new PhotoOverlay();
            overlay.Location = point;

            folder.AddFeature(overlay);
            lookat = folder.CalculateLookAt();
            Assert.That(lookat.Latitude, Is.EqualTo(5.0));
            Assert.That(lookat.Longitude, Is.EqualTo(5.0));
            Assert.That(lookat.Range, Is.EqualTo(1494183.4444).Within(0.0001));
        }
Example #35
0
        private bool parsePoint(Placemark placemark, bool done, StreamWriter writetext)
        {
            StringBuilder textString = new StringBuilder();

            textString.Append("{");
            if (rdbStations.Checked)
            {
                textString.Append("\"Station_Description\": \"" + placemark.Name + "\"," + Environment.NewLine);
                textString.Append("\"Station_Coordinates\": \"");
            }
            else if (rdbReferences.Checked)
            {
                textString.Append("\"Known_As_Description\": \"" + placemark.Name + "\"," + Environment.NewLine);
            }

            foreach (var point in placemark.Geometry.Flatten().OfType<SharpKml.Dom.Point>())
            {
                DbGeography coordinates = DbGeography.PointFromText("POINT (" + point.Coordinate.Longitude
                + " " + point.Coordinate.Latitude + ")", 4326);

                textString.Append(point.Coordinate.Longitude + "," + point.Coordinate.Latitude + "\"");

                if (rdbStations.Checked)
                {
                    addStation(placemark, point, coordinates);
                    done = true;
                }
                else if (rdbReferences.Checked)
                {
                    addReference(placemark, point, coordinates);
                    done = true;
                }
            }

            textString.Append("}, " + Environment.NewLine);

            writetext.WriteLine(textString.ToString());

            return done;
        }
Example #36
0
 Placemark CreatePlaceMark(string title, SharpKml.Dom.Geometry geometry)
 {
     Placemark placeMark = new Placemark();
     placeMark.Name = title;
     placeMark.Geometry = geometry;
     return placeMark;
 }
Example #37
0
        private void AddGeometryToCollection(Placemark parent, IGeometry geom)
        {
            List<IGeometry> placeMarkGeoms;
            if (_geometrys.TryGetValue(parent, out placeMarkGeoms) == false)
            {
                placeMarkGeoms = new List<IGeometry>();
                _geometrys.Add(parent, placeMarkGeoms);
            }

            placeMarkGeoms.Add(geom);
        }
Example #38
0
        public void DoAcceptTcpClientCallback(IAsyncResult ar)
        {
            // Get the listener that handles the client request.
            TcpListener listener = (TcpListener)ar.AsyncState;

            // End the operation and display the received data on
            // the console.
            using (
                TcpClient client = listener.EndAcceptTcpClient(ar))
            {
                // Signal the calling thread to continue.
                tcpClientConnected.Set();



                try
                {
                    // Get a stream object for reading and writing
                    log.Info("Accepted Client " + client.Client.RemoteEndPoint.ToString());
                    //client.SendBufferSize = 100 * 1024; // 100kb
                    //client.LingerState.Enabled = true;
                    //client.NoDelay = true;

                    // makesure we have valid image
                    GCSViews.FlightData.myhud.streamjpgenable = true;

                    NetworkStream stream = client.GetStream();

                    // 3 seconds
                    stream.ReadTimeout = 3000;

again:

                    var asciiEncoding = new ASCIIEncoding();

                    var request = new byte[1024];

                    int    len  = stream.Read(request, 0, request.Length);
                    string head = System.Text.Encoding.ASCII.GetString(request, 0, len);
                    log.Info(head);

                    int index = head.IndexOf('\n');

                    string url = head.Substring(0, index - 1);
                    //url = url.Replace("\r", "");
                    //url = url.Replace("GET ","");
                    //url = url.Replace(" HTTP/1.0", "");
                    //url = url.Replace(" HTTP/1.1", "");

                    Tracking.AddEvent("HTTPServer", "Get", url, "");
/////////////////////////////////////////////////////////////////
                    if (url.Contains("websocket"))
                    {
                        using (var writer = new StreamWriter(stream, Encoding.Default))
                        {
                            writer.WriteLine("HTTP/1.1 101 WebSocket Protocol Handshake");
                            writer.WriteLine("Upgrade: WebSocket");
                            writer.WriteLine("Connection: Upgrade");
                            writer.WriteLine("WebSocket-Location: ws://localhost:56781/websocket/server");

                            int start = head.IndexOf("Sec-WebSocket-Key:") + 19;
                            int end   = head.IndexOf('\r', start);
                            if (end == -1)
                            {
                                end = head.IndexOf('\n', start);
                            }
                            string accept = ComputeWebSocketHandshakeSecurityHash09(head.Substring(start, end - start));

                            writer.WriteLine("Sec-WebSocket-Accept: " + accept);

                            writer.WriteLine("Server: APM Planner");

                            writer.WriteLine("");

                            writer.Flush();

                            while (client.Connected)
                            {
                                Thread.Sleep(200);
                                log.Debug(stream.DataAvailable + " " + client.Available);

                                while (client.Available > 0)
                                {
                                    Console.Write(stream.ReadByte());
                                }

                                byte[] packet = new byte[256];

                                string sendme = MainV2.comPort.MAV.cs.roll + "," + MainV2.comPort.MAV.cs.pitch + "," + MainV2.comPort.MAV.cs.yaw;

                                packet[0] = 0x81; // fin - binary
                                packet[1] = (byte)sendme.Length;

                                int i = 2;
                                foreach (char ch in sendme)
                                {
                                    packet[i++] = (byte)ch;
                                }

                                stream.Write(packet, 0, i);

                                //break;
                            }
                        }
                    }
                    /////////////////////////////////////////////////////////////////
                    else if (url.Contains("georefnetwork.kml"))
                    {
                        string header = "HTTP/1.1 200 OK\r\nContent-Type: application/vnd.google-earth.kml+xml\r\nContent-Length: " + georefkml.Length + "\r\n\r\n";
                        byte[] temp   = asciiEncoding.GetBytes(header);
                        stream.Write(temp, 0, temp.Length);

                        byte[] buffer = Encoding.ASCII.GetBytes(georefkml);

                        stream.Write(buffer, 0, buffer.Length);

                        goto again;

                        //stream.Close();
                    }
                    /////////////////////////////////////////////////////////////////
                    else if (url.Contains("network.kml"))
                    {
                        SharpKml.Dom.Document kml = new SharpKml.Dom.Document();

                        SharpKml.Dom.Placemark pmplane = new SharpKml.Dom.Placemark();
                        pmplane.Name = "P/Q " + MainV2.comPort.MAV.cs.altasl;

                        pmplane.Visibility = true;

                        SharpKml.Dom.Location loc = new SharpKml.Dom.Location();
                        loc.Latitude  = MainV2.comPort.MAV.cs.lat;
                        loc.Longitude = MainV2.comPort.MAV.cs.lng;
                        loc.Altitude  = MainV2.comPort.MAV.cs.altasl;

                        if (loc.Altitude < 0)
                        {
                            loc.Altitude = 0.01;
                        }

                        SharpKml.Dom.Orientation ori = new SharpKml.Dom.Orientation();
                        ori.Heading = MainV2.comPort.MAV.cs.yaw;
                        ori.Roll    = -MainV2.comPort.MAV.cs.roll;
                        ori.Tilt    = -MainV2.comPort.MAV.cs.pitch;

                        SharpKml.Dom.Scale sca = new SharpKml.Dom.Scale();

                        sca.X = 2;
                        sca.Y = 2;
                        sca.Z = 2;

                        SharpKml.Dom.Model model = new SharpKml.Dom.Model();
                        model.Location     = loc;
                        model.Orientation  = ori;
                        model.AltitudeMode = SharpKml.Dom.AltitudeMode.Absolute;
                        model.Scale        = sca;

                        SharpKml.Dom.Link link = new SharpKml.Dom.Link();
                        link.Href = new Uri("block_plane_0.dae", UriKind.Relative);

                        model.Link = link;

                        pmplane.Geometry = model;

                        SharpKml.Dom.LookAt la = new SharpKml.Dom.LookAt()
                        {
                            Altitude     = loc.Altitude.Value,
                            Latitude     = loc.Latitude.Value,
                            Longitude    = loc.Longitude.Value,
                            Tilt         = 80,
                            Heading      = MainV2.comPort.MAV.cs.yaw,
                            AltitudeMode = SharpKml.Dom.AltitudeMode.Absolute,
                            Range        = 50
                        };

                        if (loc.Latitude.Value != 0 && loc.Longitude.Value != 0)
                        {
                            kml.Viewpoint = la;
                            kml.AddFeature(pmplane);
                        }

                        SharpKml.Dom.CoordinateCollection coords = new SharpKml.Dom.CoordinateCollection();

                        //if (loc.Latitude.Value != 0 && loc.Longitude.Value != 0)
                        {
                            //foreach (var point in MainV2.comPort.MAV.wps.Values)
                            {
                                //    coords.Add(new SharpKml.Base.Vector(point.x, point.y, point.z));
                            }
                        }
                        //else
                        {
                            PointLatLngAlt home = null;
                            // draw track
                            try
                            {
                                foreach (var point in GCSViews.FlightPlanner.instance.fullpointlist)
                                {
                                    if (point.Tag.ToLower().Contains("home"))
                                    {
                                        home = point;
                                    }

                                    if (point != null)
                                    {
                                        coords.Add(new SharpKml.Base.Vector(point.Lat, point.Lng, point.Alt));
                                    }
                                }
                            }
                            catch { }

                            foreach (var point in GCSViews.FlightPlanner.instance.fullpointlist)
                            {
                                if (point == null)
                                {
                                    continue;
                                }

                                SharpKml.Dom.Placemark wp = new SharpKml.Dom.Placemark();
                                wp.Name = "WP " + point.Tag + " Alt: " + point.Alt;
                                SharpKml.Dom.Point wppoint = new SharpKml.Dom.Point();
                                var altmode = SharpKml.Dom.AltitudeMode.RelativeToGround;
                                wppoint.AltitudeMode = altmode;
                                wppoint.Coordinate   = new Vector()
                                {
                                    Latitude = point.Lat, Longitude = point.Lng, Altitude = point.Alt
                                };
                                wp.Geometry = wppoint;
                                kml.AddFeature(wp);
                            }
                        }

                        SharpKml.Dom.LineString ls = new SharpKml.Dom.LineString();
                        ls.AltitudeMode = SharpKml.Dom.AltitudeMode.RelativeToGround;
                        ls.Coordinates  = coords;
                        ls.Extrude      = false;
                        ls.Tessellate   = true;

                        Style style = new Style();
                        style.Id   = "yellowLineGreenPoly";
                        style.Line = new LineStyle(new Color32(HexStringToColor("ff00ffff")), 4);

                        Style style2 = new Style();
                        style2.Id   = "yellowLineGreenPoly";
                        style2.Line = new LineStyle(new Color32(HexStringToColor("7f00ffff")), 4);

                        // above ground
                        SharpKml.Dom.Placemark pm = new SharpKml.Dom.Placemark()
                        {
                            Geometry = ls, Name = "WPs", StyleSelector = style
                        };

                        kml.AddFeature(pm);

                        // on ground
                        SharpKml.Dom.LineString ls2 = new SharpKml.Dom.LineString();
                        ls2.Coordinates  = coords;
                        ls2.Extrude      = false;
                        ls2.Tessellate   = true;
                        ls2.AltitudeMode = SharpKml.Dom.AltitudeMode.ClampToGround;

                        SharpKml.Dom.Placemark pm2 = new SharpKml.Dom.Placemark()
                        {
                            Geometry = ls2, Name = "onground", StyleSelector = style2
                        };

                        kml.AddFeature(pm2);

                        SharpKml.Base.Serializer serializer = new SharpKml.Base.Serializer();
                        serializer.Serialize(kml);

                        byte[] buffer = Encoding.ASCII.GetBytes(serializer.Xml);

                        string header = "HTTP/1.1 200 OK\r\nContent-Type: application/vnd.google-earth.kml+xml\r\nContent-Length: " + buffer.Length + "\r\n\r\n";
                        byte[] temp   = asciiEncoding.GetBytes(header);
                        stream.Write(temp, 0, temp.Length);

                        stream.Write(buffer, 0, buffer.Length);

                        goto again;

                        //stream.Close();
                    }
                    /////////////////////////////////////////////////////////////////
                    else if (url.Contains("block_plane_0.dae"))
                    {
                        string header = "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n\r\n";
                        byte[] temp   = asciiEncoding.GetBytes(header);
                        stream.Write(temp, 0, temp.Length);

                        BinaryReader file   = new BinaryReader(File.Open("block_plane_0.dae", FileMode.Open, FileAccess.Read, FileShare.Read));
                        byte[]       buffer = new byte[1024];
                        while (file.PeekChar() != -1)
                        {
                            int leng = file.Read(buffer, 0, buffer.Length);

                            stream.Write(buffer, 0, leng);
                        }
                        file.Close();
                        stream.Close();
                    }
                    /////////////////////////////////////////////////////////////////
                    else if (url.Contains("hud.html"))
                    {
                        string header = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n";
                        byte[] temp   = asciiEncoding.GetBytes(header);
                        stream.Write(temp, 0, temp.Length);

                        BinaryReader file   = new BinaryReader(File.Open("hud.html", FileMode.Open, FileAccess.Read, FileShare.Read));
                        byte[]       buffer = new byte[1024];
                        while (file.PeekChar() != -1)
                        {
                            int leng = file.Read(buffer, 0, buffer.Length);

                            stream.Write(buffer, 0, leng);
                        }
                        file.Close();
                        stream.Close();
                    }
                    /////////////////////////////////////////////////////////////////
                    else if (url.ToLower().Contains("hud.jpg") || url.ToLower().Contains("map.jpg") || url.ToLower().Contains("both.jpg"))
                    {
                        refreshmap();

                        string header = "HTTP/1.1 200 OK\r\nContent-Type: multipart/x-mixed-replace;boundary=APMPLANNER\r\n\r\n--APMPLANNER\r\n";
                        byte[] temp   = asciiEncoding.GetBytes(header);
                        stream.Write(temp, 0, temp.Length);

                        while (client.Connected)
                        {
                            System.Threading.Thread.Sleep(200); // 5hz
                            byte[] data = null;

                            if (url.ToLower().Contains("hud"))
                            {
                                GCSViews.FlightData.myhud.streamjpgenable = true;
                                data = GCSViews.FlightData.myhud.streamjpg.ToArray();
                            }
                            else if (url.ToLower().Contains("map"))
                            {
                                data = GetControlJpegRaw(GCSViews.FlightData.mymap);
                            }
                            else
                            {
                                GCSViews.FlightData.myhud.streamjpgenable = true;
                                Image img1   = Image.FromStream(GCSViews.FlightData.myhud.streamjpg);
                                Image img2   = GetControlJpeg(GCSViews.FlightData.mymap);
                                int   bigger = img1.Height > img2.Height ? img1.Height : img2.Height;
                                Image imgout = new Bitmap(img1.Width + img2.Width, bigger);

                                Graphics grap = Graphics.FromImage(imgout);

                                grap.DrawImageUnscaled(img1, 0, 0);
                                grap.DrawImageUnscaled(img2, img1.Width, 0);

                                MemoryStream streamjpg = new MemoryStream();
                                imgout.Save(streamjpg, System.Drawing.Imaging.ImageFormat.Jpeg);
                                data = streamjpg.ToArray();
                            }

                            header = "Content-Type: image/jpeg\r\nContent-Length: " + data.Length + "\r\n\r\n";
                            temp   = asciiEncoding.GetBytes(header);
                            stream.Write(temp, 0, temp.Length);

                            stream.Write(data, 0, data.Length);

                            header = "\r\n--APMPLANNER\r\n";
                            temp   = asciiEncoding.GetBytes(header);
                            stream.Write(temp, 0, temp.Length);
                        }
                        GCSViews.FlightData.myhud.streamjpgenable = false;
                        stream.Close();
                    }
                    /////////////////////////////////////////////////////////////////
                    else if (url.Contains("/guided?"))
                    {
                        //http://127.0.0.1:56781/guided?lat=-34&lng=117.8&alt=30

                        Regex rex = new Regex(@"lat=([\-\.0-9]+)&lng=([\-\.0-9]+)&alt=([\.0-9]+)", RegexOptions.IgnoreCase);

                        Match match = rex.Match(url);

                        if (match.Success)
                        {
                            Locationwp gwp = new Locationwp()
                            {
                                lat = double.Parse(match.Groups[1].Value),
                                lng = double.Parse(match.Groups[2].Value),
                                alt = float.Parse(match.Groups[3].Value)
                            };
                            try
                            {
                                MainV2.comPort.setGuidedModeWP(gwp);
                            }
                            catch { }

                            string header = "HTTP/1.1 200 OK\r\n\r\nSent Guide Mode Wp";
                            byte[] temp   = asciiEncoding.GetBytes(header);
                            stream.Write(temp, 0, temp.Length);
                        }
                        else
                        {
                            string header = "HTTP/1.1 200 OK\r\n\r\nFailed Guide Mode Wp";
                            byte[] temp   = asciiEncoding.GetBytes(header);
                            stream.Write(temp, 0, temp.Length);
                        }
                        stream.Close();
                    }
                    /////////////////////////////////////////////////////////////////
                    else if (url.ToLower().Contains(".jpg"))
                    {
                        Regex rex = new Regex(@"([^\s]+)\s(.+)\sHTTP/1", RegexOptions.IgnoreCase);

                        Match match = rex.Match(url);

                        if (match.Success)
                        {
                            string fileurl = match.Groups[2].Value;

                            using (Image orig = Image.FromFile(georefimagepath + fileurl))
                                using (Image resi = ResizeImage(orig, new Size(640, 480)))
                                    using (MemoryStream memstream = new MemoryStream())
                                    {
                                        resi.Save(memstream, System.Drawing.Imaging.ImageFormat.Jpeg);

                                        memstream.Position = 0;

                                        string header = "HTTP/1.1 200 OK\r\nContent-Type: image/jpg\r\nContent-Length: " + memstream.Length + "\r\n\r\n";
                                        byte[] temp   = asciiEncoding.GetBytes(header);
                                        stream.Write(temp, 0, temp.Length);

                                        using (BinaryReader file = new BinaryReader(memstream))
                                        {
                                            byte[] buffer = new byte[1024];
                                            while (file.BaseStream.Position < file.BaseStream.Length)
                                            {
                                                int leng = file.Read(buffer, 0, buffer.Length);

                                                stream.Write(buffer, 0, leng);
                                            }
                                        }
                                    }

                            goto again;

                            //stream.Close();
                        }
                        /////////////////////////////////////////////////////////////////
                        else
                        {
                            string header = "HTTP/1.1 404 not found\r\nContent-Type: image/jpg\r\n\r\n";
                            byte[] temp   = asciiEncoding.GetBytes(header);
                            stream.Write(temp, 0, temp.Length);
                        }
                        stream.Close();
                    }
                    /////////////////////////////////////////////////////////////////
                    else if (url.ToLower().Contains("post /guide"))
                    {
                        Regex rex = new Regex(@"lat"":([\-\.0-9]+),""lon"":([\-\.0-9]+),""alt"":([\.0-9]+)", RegexOptions.IgnoreCase);

                        Match match = rex.Match(head);

                        if (match.Success)
                        {
                            Locationwp gwp = new Locationwp()
                            {
                                lat = double.Parse(match.Groups[1].Value),
                                lng = double.Parse(match.Groups[2].Value),
                                alt = float.Parse(match.Groups[3].Value)
                            };
                            try
                            {
                                MainV2.comPort.setGuidedModeWP(gwp);
                            }
                            catch { }

                            string header = "HTTP/1.1 200 OK\r\n\r\nSent Guide Mode Wp";
                            byte[] temp   = asciiEncoding.GetBytes(header);
                            stream.Write(temp, 0, temp.Length);
                        }
                        else
                        {
                            string header = "HTTP/1.1 200 OK\r\n\r\nFailed Guide Mode Wp";
                            byte[] temp   = asciiEncoding.GetBytes(header);
                            stream.Write(temp, 0, temp.Length);
                        }
                        stream.Close();
                    }
                    /////////////////////////////////////////////////////////////////
                    else if (url.ToLower().Contains("/command_long"))
                    {
                        string header = "HTTP/1.1 404 not found\r\nContent-Type: image/jpg\r\n\r\n";
                        byte[] temp   = asciiEncoding.GetBytes(header);
                        stream.Write(temp, 0, temp.Length);

                        stream.Close();
                    }
                    /////////////////////////////////////////////////////////////////
                    else if (url.ToLower().Contains("/rcoverride"))
                    {
                        string header = "HTTP/1.1 404 not found\r\nContent-Type: image/jpg\r\n\r\n";
                        byte[] temp   = asciiEncoding.GetBytes(header);
                        stream.Write(temp, 0, temp.Length);

                        stream.Close();
                    }
                    /////////////////////////////////////////////////////////////////
                    else if (url.ToLower().Contains("/get_mission"))
                    {
                        string header = "HTTP/1.1 404 not found\r\nContent-Type: image/jpg\r\n\r\n";
                        byte[] temp   = asciiEncoding.GetBytes(header);
                        stream.Write(temp, 0, temp.Length);

                        stream.Close();
                    }
                    /////////////////////////////////////////////////////////////////
                    else if (url.ToLower().Contains("/mavlink/"))
                    {
                        /*
                         * GET /mavlink/ATTITUDE+VFR_HUD+NAV_CONTROLLER_OUTPUT+META_WAYPOINT+GPS_RAW_INT+HEARTBEAT+META_LINKQUALITY+GPS_STATUS+STATUSTEXT+SYS_STATUS?_=1355828718540 HTTP/1.1
                         * Host: ubuntu:9999
                         * Connection: keep-alive
                         * X-Requested-With: XMLHttpRequest
                         * User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11
                         * Accept:
                         * Referer: http://ubuntu:9999/index.html
                         * Accept-Encoding: gzip,deflate,sdch
                         * Accept-Language: en-GB,en-US;q=0.8,en;q=0.6
                         * Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
                         *
                         * HTTP/1.1 200 OK
                         * Content-Type: application/json
                         * Content-Length: 2121
                         * Date: Thu, 29 Nov 2012 12:13:38 GMT
                         * Server: ubuntu
                         *
                         * {
                         * "VFR_HUD": {"msg": {"throttle": 0, "groundspeed": 0.0, "airspeed": 0.0, "climb": 0.0, "mavpackettype": "VFR_HUD", "alt": -0.47999998927116394, "heading": 108}, "index": 687, "time_usec": 0},
                         * "STATUSTEXT": {"msg": {"mavpackettype": "STATUSTEXT", "severity": 1, "text": "Initialising APM..."}, "index": 2, "time_usec": 0},
                         * "SYS_STATUS": {"msg": {"onboard_control_sensors_present": 4294966287, "load": 0, "battery_remaining": -1, "errors_count4": 0, "drop_rate_comm": 0, "errors_count2": 0, "errors_count3": 0, "errors_comm": 0, "current_battery": -1, "errors_count1": 0, "onboard_control_sensors_health": 4294966287, "mavpackettype": "SYS_STATUS", "onboard_control_sensors_enabled": 4294945807, "voltage_battery": 10080}, "index": 693, "time_usec": 0},
                         * "META_LINKQUALITY": {"msg": {"master_in": 11110, "mav_loss": 0, "mavpackettype": "META_LINKQUALITY", "master_out": 194, "packet_loss": 0.0}, "index": 194, "time_usec": 0},
                         * "ATTITUDE": {"msg": {"pitchspeed": -0.000976863200776279, "yaw": 1.8878594636917114, "rollspeed": -0.0030046366155147552, "time_boot_ms": 194676, "pitch": -0.09986469894647598, "mavpackettype": "ATTITUDE", "yawspeed": -0.0015030358918011189, "roll": -0.029391441494226456}, "index": 687, "time_usec": 0},
                         * "GPS_RAW_INT": {"msg": {"fix_type": 1, "cog": 0, "epv": 65535, "lon": 0, "time_usec": 0, "eph": 9999, "satellites_visible": 0, "lat": 0, "mavpackettype": "GPS_RAW_INT", "alt": 137000, "vel": 0}, "index": 687, "time_usec": 0},
                         * "HEARTBEAT": {"msg": {"custom_mode": 0, "system_status": 4, "base_mode": 81, "autopilot": 3, "mavpackettype": "HEARTBEAT", "type": 2, "mavlink_version": 3}, "index": 190, "time_usec": 0},
                         * "GPS_STATUS": {"msg": {"satellite_snr": "", "satellite_azimuth": "", "satellite_prn": "", "satellite_elevation": "", "satellites_visible": 0, "satellite_used": "", "mavpackettype": "GPS_STATUS"}, "index": 2, "time_usec": 0},
                         * "NAV_CONTROLLER_OUTPUT": {"msg": {"wp_dist": 0, "nav_pitch": 0.0, "target_bearing": 0, "nav_roll": 0.0, "aspd_error": 0.0, "alt_error": 0.0, "mavpackettype": "NAV_CONTROLLER_OUTPUT", "xtrack_error": 0.0, "nav_bearing": 0}, "index": 687, "time_usec": 0}}
                         */

                        JavaScriptSerializer serializer = new JavaScriptSerializer();

                        object[] data = new object[20];


                        Messagejson message = new Messagejson();


                        if (MainV2.comPort.MAV.packets[(byte)MAVLink.MAVLINK_MSG_ID.ATTITUDE] != null)
                        {
                            message.ATTITUDE = new Message2()
                            {
                                index = MainV2.comPort.MAV.packetseencount[(byte)MAVLink.MAVLINK_MSG_ID.ATTITUDE], msg = MainV2.comPort.MAV.packets[(byte)MAVLink.MAVLINK_MSG_ID.ATTITUDE].ByteArrayToStructure <MAVLink.mavlink_attitude_t>(6)
                            }
                        }
                        ;
                        if (MainV2.comPort.MAV.packets[(byte)MAVLink.MAVLINK_MSG_ID.VFR_HUD] != null)
                        {
                            message.VFR_HUD = new Message2()
                            {
                                index = MainV2.comPort.MAV.packetseencount[(byte)MAVLink.MAVLINK_MSG_ID.VFR_HUD], msg = MainV2.comPort.MAV.packets[(byte)MAVLink.MAVLINK_MSG_ID.VFR_HUD].ByteArrayToStructure <MAVLink.mavlink_vfr_hud_t>(6)
                            }
                        }
                        ;
                        if (MainV2.comPort.MAV.packets[(byte)MAVLink.MAVLINK_MSG_ID.NAV_CONTROLLER_OUTPUT] != null)
                        {
                            message.NAV_CONTROLLER_OUTPUT = new Message2()
                            {
                                index = MainV2.comPort.MAV.packetseencount[(byte)MAVLink.MAVLINK_MSG_ID.NAV_CONTROLLER_OUTPUT], msg = MainV2.comPort.MAV.packets[(byte)MAVLink.MAVLINK_MSG_ID.NAV_CONTROLLER_OUTPUT].ByteArrayToStructure <MAVLink.mavlink_nav_controller_output_t>(6)
                            }
                        }
                        ;
                        if (MainV2.comPort.MAV.packets[(byte)MAVLink.MAVLINK_MSG_ID.GPS_RAW_INT] != null)
                        {
                            message.GPS_RAW_INT = new Message2()
                            {
                                index = MainV2.comPort.MAV.packetseencount[(byte)MAVLink.MAVLINK_MSG_ID.GPS_RAW_INT], msg = MainV2.comPort.MAV.packets[(byte)MAVLink.MAVLINK_MSG_ID.GPS_RAW_INT].ByteArrayToStructure <MAVLink.mavlink_gps_raw_int_t>(6)
                            }
                        }
                        ;
                        if (MainV2.comPort.MAV.packets[(byte)MAVLink.MAVLINK_MSG_ID.HEARTBEAT] != null)
                        {
                            message.HEARTBEAT = new Message2()
                            {
                                index = MainV2.comPort.MAV.packetseencount[(byte)MAVLink.MAVLINK_MSG_ID.HEARTBEAT], msg = MainV2.comPort.MAV.packets[(byte)MAVLink.MAVLINK_MSG_ID.HEARTBEAT].ByteArrayToStructure <MAVLink.mavlink_heartbeat_t>(6)
                            }
                        }
                        ;
                        if (MainV2.comPort.MAV.packets[(byte)MAVLink.MAVLINK_MSG_ID.GPS_STATUS] != null)
                        {
                            message.GPS_STATUS = new Message2()
                            {
                                index = MainV2.comPort.MAV.packetseencount[(byte)MAVLink.MAVLINK_MSG_ID.GPS_STATUS], msg = MainV2.comPort.MAV.packets[(byte)MAVLink.MAVLINK_MSG_ID.GPS_STATUS].ByteArrayToStructure <MAVLink.mavlink_gps_status_t>(6)
                            }
                        }
                        ;
                        if (MainV2.comPort.MAV.packets[(byte)MAVLink.MAVLINK_MSG_ID.STATUSTEXT] != null)
                        {
                            message.STATUSTEXT = new Message2()
                            {
                                index = MainV2.comPort.MAV.packetseencount[(byte)MAVLink.MAVLINK_MSG_ID.STATUSTEXT], msg = MainV2.comPort.MAV.packets[(byte)MAVLink.MAVLINK_MSG_ID.STATUSTEXT].ByteArrayToStructure <MAVLink.mavlink_statustext_t>(6)
                            }
                        }
                        ;
                        if (MainV2.comPort.MAV.packets[(byte)MAVLink.MAVLINK_MSG_ID.SYS_STATUS] != null)
                        {
                            message.SYS_STATUS = new Message2()
                            {
                                index = MainV2.comPort.MAV.packetseencount[(byte)MAVLink.MAVLINK_MSG_ID.SYS_STATUS], msg = MainV2.comPort.MAV.packets[(byte)MAVLink.MAVLINK_MSG_ID.SYS_STATUS].ByteArrayToStructure <MAVLink.mavlink_sys_status_t>(6)
                            }
                        }
                        ;

                        message.META_LINKQUALITY = message.SYS_STATUS = new Message2()
                        {
                            index = packetindex, time_usec = 0, msg = new META_LINKQUALITY()
                            {
                                master_in = (int)MainV2.comPort.packetsnotlost, mavpackettype = "META_LINKQUALITY", master_out = MainV2.comPort.packetcount, packet_loss = 100 - MainV2.comPort.MAV.cs.linkqualitygcs, mav_loss = 0
                            }
                        };

                        packetindex++;

                        string output = serializer.Serialize(message);

                        string header = "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: " + output.Length + "\r\n\r\n";
                        byte[] temp   = asciiEncoding.GetBytes(header);
                        stream.Write(temp, 0, temp.Length);

                        temp = asciiEncoding.GetBytes(output);
                        stream.Write(temp, 0, temp.Length);

                        goto again;

                        //stream.Close();
                    }
                    /////////////////////////////////////////////////////////////////
                    else if (url.ToLower().Contains("/mav/"))
                    {
                        //C:\Users\hog\Desktop\DIYDrones\mavelous\modules\lib\mavelous_web


                        Regex rex = new Regex(@"([^\s]+)\s(.+)\sHTTP/1", RegexOptions.IgnoreCase);

                        Match match = rex.Match(url);

                        if (match.Success)
                        {
                            string fileurl = match.Groups[2].Value;

                            fileurl = fileurl.Replace("/mav/", "");

                            if (fileurl == "" || fileurl == "/")
                            {
                                fileurl = "index.html";
                            }

                            string header = "HTTP/1.1 200 OK\r\n";
                            if (fileurl.Contains(".html"))
                            {
                                header += "Content-Type: text/html\r\n\r\n";
                            }
                            else if (fileurl.Contains(".js"))
                            {
                                header += "Content-Type: application/x-javascript\r\n\r\n";
                            }
                            else if (fileurl.Contains(".css"))
                            {
                                header += "Content-Type: text/css\r\n\r\n";
                            }
                            else
                            {
                                header += "Content-Type: text/plain\r\n\r\n";
                            }
                            byte[] temp = asciiEncoding.GetBytes(header);
                            stream.Write(temp, 0, temp.Length);


                            BinaryReader file   = new BinaryReader(File.Open(mavelous_web + fileurl, FileMode.Open, FileAccess.Read, FileShare.Read));
                            byte[]       buffer = new byte[1024];
                            while (file.BaseStream.Position < file.BaseStream.Length)
                            {
                                int leng = file.Read(buffer, 0, buffer.Length);

                                stream.Write(buffer, 0, leng);
                            }
                            file.Close();
                            stream.Close();
                        }
                        /////////////////////////////////////////////////////////////////
                        else
                        {
                            string header = "HTTP/1.1 404 not found\r\nContent-Type: image/jpg\r\n\r\n";
                            byte[] temp   = asciiEncoding.GetBytes(header);
                            stream.Write(temp, 0, temp.Length);

                            stream.Close();
                        }
                    }
                    /////////////////////////////////////////////////////////////////
                    else
                    {
                        Console.WriteLine(url);
                        string header = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n";
                        byte[] temp   = asciiEncoding.GetBytes(header);
                        stream.Write(temp, 0, temp.Length);

                        string content = @"
                <a href=/mav/>Mavelous</a>
<a href=/mavlink/>Mavelous traffic</a>
<a href=/hud.jpg>Hud image</a>
<a href=/map.jpg>Map image </a>
<a href=/both.jpg>Map & hud image</a>
<a href=/hud.html>hud html5</a>
<a href=/network.kml>network kml</a>

";
                        temp = asciiEncoding.GetBytes(content);
                        stream.Write(temp, 0, temp.Length);
                    }

                    stream.Close();
                }
                catch (Exception ee)
                {
                    log.Error("Failed http ", ee);
                }
            }
        }
        TreeViewItem ProcessPlacemark(Placemark placemark)
        {
            string name = placemark.Name;
            StackPanel pan = new StackPanel();
            pan.Orientation = System.Windows.Controls.Orientation.Horizontal;

            Style style = FindStyleByStyleURL(placemark.StyleUrl.OriginalString);

            if (placemark.Geometry is Point)
            {
                Uri uri = null;
                if (style != null && style.Icon != null && style.Icon.Icon != null && style.Icon.Icon.Href != null)
                {
                    uri = style.Icon.Icon.Href;
                }

                Image image = new Image();
                image.Height = 16;
                image.Source = FindImageByUri(uri);
                pan.Children.Add(image);
            }
            else if (placemark.Geometry is LineString)
            {
                GeometryGroup Lines = new GeometryGroup();

                Color32 styleColor = new Color32();
                if (style != null && style.Line != null && style.Line.Color != null)
                {
                    styleColor = (Color32)style.Line.Color;
                }

                // Line
                LineGeometry line = new LineGeometry();
                line.StartPoint = new System.Windows.Point(0, 5);
                line.EndPoint = new System.Windows.Point(10, 5);
                Lines.Children.Add(line);
                GeometryDrawing MyGeometryDrawing = new GeometryDrawing();
                MyGeometryDrawing.Geometry = Lines;
                MyGeometryDrawing.Brush = new SolidColorBrush(Color.FromArgb(styleColor.Alpha, styleColor.Red, styleColor.Green, styleColor.Blue));
                MyGeometryDrawing.Pen = new Pen(MyGeometryDrawing.Brush, 1);
                DrawingImage drawingImage = new DrawingImage(MyGeometryDrawing);
                drawingImage.Freeze();
                Image image = new Image();
                image.Height = 16;
                image.Width = 16;
                image.Source = drawingImage;
                pan.Children.Add(image);
            }

            TextBlock textBlock = new TextBlock();
            textBlock.Text = name;
            textBlock.Margin = new System.Windows.Thickness(4, 0, 0, 0);
            pan.Children.Add(textBlock);

            KMLFeatureTreeViewItem item = new KMLFeatureTreeViewItem()
            {
                Header = pan,
                Feature = placemark
            };
            return item;
        }
Example #40
0
        private void btnReadKMLPoly_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                /* Get kml filename */

                string kml_file = openFileDialog1.FileName;

                if (kml_file.Contains(".kml"))
                {
                    System.IO.TextReader    stream = System.IO.File.OpenText(kml_file);
                    SharpKml.Engine.KmlFile file   = KmlFile.Load(stream);
                    Kml _kml = file.Root as Kml;

                    SharpKml.Dom.Placemark[] tempPlaceMarks = new SharpKml.Dom.Placemark[1000];
                    SharpKml.Dom.Placemark   tmp_placemark  = new SharpKml.Dom.Placemark();
                    CoordinateCollection     coordinates    = new CoordinateCollection();
                    Form1.Globals.poly_point_count = 0;

                    if (_kml != null)
                    {
                        SharpKml.Base.Vector vector;
                        double lat;
                        double lon;
                        double alt;
                        string name = "";

                        foreach (var placemark in _kml.Flatten().OfType <SharpKml.Dom.Placemark>())
                        {
                            name = placemark.Name;
                        }

                        Models.Shape shape = new Models.Shape();
                        shape.name = name;

                        foreach (var linering in _kml.Flatten().OfType <LinearRing>())
                        {
                            coordinates = linering.Coordinates;
                            int num = coordinates.Count;

                            LinkedList <PolyPoint> shape_points = new LinkedList <PolyPoint>();

                            for (int i = 0; i < num; i++)
                            {
                                PolyPoint point = new PolyPoint();
                                vector    = coordinates.ElementAt(i);
                                lat       = vector.Latitude;
                                lon       = vector.Longitude;
                                alt       = (double)vector.Altitude;
                                point.lat = lat;
                                point.lon = lon;
                                point.alt = alt;
                                shape_points.AddLast(point);
                                //dgvWaypoints.Rows.Add(Globals.waypoint_count, Convert.ToString(lat), Convert.ToString(lon), Convert.ToString(30));
                            }
                            shape.points  = shape_points;
                            shape.visible = true;
                            _wpg.AddShape(shape);
                            _gmap.Add_gMapPoly(shape, true);
                        }
                    }
                }
                GMAPTree.Update_GMapTree(_wpg, _treeview);
                this.Close();
            }
        }
Example #41
0
        private static void processKML(SharpKml.Dom.Element Element)
        {
            try
            {
                //  log.Info(Element.ToString() + " " + Element.Parent);
            }
            catch
            {
            }

            SharpKml.Dom.Document   doc     = Element as SharpKml.Dom.Document;
            SharpKml.Dom.Placemark  pm      = Element as SharpKml.Dom.Placemark;
            SharpKml.Dom.Folder     folder  = Element as SharpKml.Dom.Folder;
            SharpKml.Dom.Polygon    polygon = Element as SharpKml.Dom.Polygon;
            SharpKml.Dom.LineString ls      = Element as SharpKml.Dom.LineString;
            MultipleGeometry        geom    = Element as MultipleGeometry;

            if (doc != null)
            {
                foreach (var feat in doc.Features)
                {
                    //Console.WriteLine("feat " + feat.GetType());
                    //processKML((Element)feat);
                }
            }
            else if (folder != null)
            {
                foreach (SharpKml.Dom.Feature feat in folder.Features)
                {
                    //Console.WriteLine("feat "+feat.GetType());
                    //processKML(feat);
                }
            }
            else if (pm != null)
            {
            }
            else if (polygon != null)
            {
                GMapPolygon kmlpolygon = new GMapPolygon(new List <PointLatLng>(), polygon.Id);

                kmlpolygon.Stroke.Color = Color.Purple;

                kmlpolygon.Fill = new SolidBrush(Color.FromArgb(30, Color.Blue));

                foreach (var loc in polygon.OuterBoundary.LinearRing.Coordinates)
                {
                    kmlpolygon.Points.Add(new PointLatLng(loc.Latitude, loc.Longitude));
                }

                kmlpolygonsoverlay.Polygons.Add(kmlpolygon);
            }
            else if (ls != null)
            {
                GMapRoute kmlroute = new GMapRoute(new List <PointLatLng>(), "kmlroute");

                kmlroute.Stroke.Color = Color.Purple;

                foreach (var loc in ls.Coordinates)
                {
                    kmlroute.Points.Add(new PointLatLng(loc.Latitude, loc.Longitude));
                }

                kmlpolygonsoverlay.Routes.Add(kmlroute);
            }
            else if (geom != null)
            {
                foreach (var geometry in geom.Geometry)
                {
                    processKML(geometry);
                }
            }
        }
Example #42
0
        public void ProcessClient(object clientobj)
        {
            var client = clientobj as TcpClient;

            using (client)
            {
                try
                {
                    // Get a stream object for reading and writing
                    log.Info("Accepted Client " + client.Client.RemoteEndPoint.ToString());
                    //client.SendBufferSize = 100 * 1024; // 100kb
                    //client.LingerState.Enabled = true;
                    //client.NoDelay = true;

                    // makesure we have valid image
                    GCSViews.FlightData.myhud.streamjpgenable = true;

                    NetworkStream stream = client.GetStream();

                    // 5 seconds - default for httpd 2.2+
                    stream.ReadTimeout = 5000;

                    goto skipagain;

again:
                    log.Info("doing Again");

skipagain:

                    var asciiEncoding = new ASCIIEncoding();

                    var request = new byte[1024 * 4];
                    int len     = 0;

                    // handle header
                    try
                    {
                        len = stream.Read(request, 0, request.Length);
                    }
                    catch
                    {
                        return;
                    }

                    string head = System.Text.Encoding.ASCII.GetString(request, 0, len);
                    log.Info(head);

                    int index = head.IndexOf('\n');

                    if (index == -1)
                    {
                        return;
                    }

                    string url = head.Substring(0, index - 1);
                    //url = url.Replace("\r", "");
                    //url = url.Replace("GET ","");
                    //url = url.Replace(" HTTP/1.0", "");
                    //url = url.Replace(" HTTP/1.1", "");

                    //Tracking.AddEvent("HTTPServer", "Get", url, "");
/////////////////////////////////////////////////////////////////
                    if (url.Contains(" /websocket/server"))
                    {
                        using (var writer = new StreamWriter(stream, Encoding.Default))
                        {
                            writer.WriteLine("HTTP/1.1 101 WebSocket Protocol Handshake");
                            writer.WriteLine("Upgrade: WebSocket");
                            writer.WriteLine("Connection: Upgrade");
                            //writer.WriteLine("WebSocket-Location: ws://localhost:56781/websocket/server");

                            int start = head.IndexOf("Sec-WebSocket-Key:") + 19;
                            int end   = head.IndexOf('\r', start);
                            if (end == -1)
                            {
                                end = head.IndexOf('\n', start);
                            }
                            string accept = ComputeWebSocketHandshakeSecurityHash09(head.Substring(start, end - start));

                            writer.WriteLine("Sec-WebSocket-Accept: " + accept);
                            writer.WriteLine("Server: Mission Planner");
                            writer.WriteLine("");
                            writer.Flush();

                            while (client.Connected)
                            {
                                while (client.Available > 0)
                                {
                                    var bydata = stream.ReadByte();
                                    Console.Write(bydata.ToString("X2"));

                                    if (bydata == 0x88)
                                    {
                                        return;
                                    }
                                }

                                byte[] packet = new byte[1024 * 32];

                                var cs  = JsonConvert.SerializeObject(MainV2.comPort.MAV.cs);
                                var wps = JsonConvert.SerializeObject(MainV2.comPort.MAV.wps);

                                foreach (var sendme in new[] { cs, wps })
                                {
                                    int i      = 0;
                                    var tosend = sendme.Length;
                                    packet[i++] = 0x81; // fin - utf

                                    if (tosend <= 125)
                                    {
                                        packet[i++] = (byte)(tosend);
                                    }
                                    else
                                    {
                                        packet[i++] = 126; // nomask -  2 byte length
                                        packet[i++] = (byte)(tosend >> 8);
                                        packet[i++] = (byte)(tosend & 0xff);
                                    }

                                    foreach (char ch in sendme)
                                    {
                                        packet[i++] = (byte)ch;
                                    }

                                    stream.Write(packet, 0, i);
                                    stream.Flush();
                                }

                                Thread.Sleep(200);
                            }
                        }
                    }
                    /////////////////////////////////////////////////////////////////
                    else if (url.Contains(" /websocket/raw"))
                    {
                        using (var writer = new StreamWriter(stream, Encoding.Default))
                        {
                            writer.WriteLine("HTTP/1.1 101 WebSocket Protocol Handshake");
                            writer.WriteLine("Upgrade: WebSocket");
                            writer.WriteLine("Connection: Upgrade");
                            writer.WriteLine("WebSocket-Location: ws://localhost:56781/websocket/raw");

                            int start = head.IndexOf("Sec-WebSocket-Key:") + 19;
                            int end   = head.IndexOf('\r', start);
                            if (end == -1)
                            {
                                end = head.IndexOf('\n', start);
                            }
                            string accept = ComputeWebSocketHandshakeSecurityHash09(head.Substring(start, end - start));

                            writer.WriteLine("Sec-WebSocket-Accept: " + accept);
                            if (head.Contains("Sec-WebSocket-Protocol:"))
                            {
                                writer.WriteLine("Sec-WebSocket-Protocol: binary");
                            }
                            writer.WriteLine("Server: Mission Planner");
                            writer.WriteLine("");
                            writer.Flush();

                            EventHandler <MAVLink.MAVLinkMessage> action = null;
                            action = (sender, message) =>
                            {
                                var sendme = message.buffer;
                                try
                                {
                                    byte[] packet = new byte[1024 * 32];

                                    int i      = 0;
                                    var tosend = sendme.Length;
                                    packet[i++] = 0x82; // fin - data

                                    if (tosend <= 125)
                                    {
                                        packet[i++] = (byte)(tosend);
                                    }
                                    else
                                    {
                                        packet[i++] = 126; // nomask -  2 byte length
                                        packet[i++] = (byte)(tosend >> 8);
                                        packet[i++] = (byte)(tosend & 0xff);
                                    }

                                    foreach (char ch in sendme)
                                    {
                                        packet[i++] = (byte)ch;
                                    }

                                    stream.WriteAsync(packet, 0, i);
                                    stream.FlushAsync();
                                }
                                catch
                                {
                                    ((MAVLinkInterface)sender).OnPacketReceived -= action;
                                    stream.Close();
                                    client.Close();
                                }
                            };

                            MainV2.comPort.OnPacketReceived += action;

                            while (client.Connected)
                            {
                                while (client.Available > 0)
                                {
                                    var bydata = stream.ReadByte();
                                    Console.Write(bydata.ToString("X2"));

                                    if (bydata == 0x88)
                                    {
                                        return;
                                    }
                                }

                                Thread.Sleep(200);
                            }

                            MainV2.comPort.OnPacketReceived -= action;
                        }
                    }
                    /////////////////////////////////////////////////////////////////
                    else if (url.Contains(" /georefnetwork.kml"))
                    {
                        byte[] buffer = Encoding.ASCII.GetBytes(georefkml);

                        string header =
                            "HTTP/1.1 200 OK\r\nServer: here\r\nKeep-Alive: timeout=15, max=100\r\nConnection: Keep-Alive\r\nCache-Control: no-cache\r\nContent-Type: application/vnd.google-earth.kml+xml\r\nX-Pad: avoid browser bug\r\nContent-Length: " +
                            buffer.Length + "\r\n\r\n";
                        byte[] temp = asciiEncoding.GetBytes(header);
                        stream.Write(temp, 0, temp.Length);

                        stream.Write(buffer, 0, buffer.Length);

                        stream.Flush();

                        goto again;

                        //stream.Close();
                    }
                    /////////////////////////////////////////////////////////////////
                    else if (url.Contains(" /location.kml"))
                    {
                        SharpKml.Dom.Document kml = new SharpKml.Dom.Document();

                        foreach (var mavLinkInterface in MainV2.Comports)
                        {
                            foreach (var MAV in mavLinkInterface.MAVlist)
                            {
                                SharpKml.Dom.Placemark pmplane = new SharpKml.Dom.Placemark();
                                pmplane.Name = "P/Q " + MAV.cs.altasl;

                                pmplane.Visibility = true;

                                SharpKml.Dom.Location loc = new SharpKml.Dom.Location();
                                loc.Latitude  = MAV.cs.lat;
                                loc.Longitude = MAV.cs.lng;
                                loc.Altitude  = MAV.cs.altasl;

                                if (loc.Altitude < 0)
                                {
                                    loc.Altitude = 0.01;
                                }

                                SharpKml.Dom.Orientation ori = new SharpKml.Dom.Orientation();
                                ori.Heading = MAV.cs.yaw;
                                ori.Roll    = -MAV.cs.roll;
                                ori.Tilt    = -MAV.cs.pitch;

                                SharpKml.Dom.Scale sca = new SharpKml.Dom.Scale();

                                sca.X = 2;
                                sca.Y = 2;
                                sca.Z = 2;

                                SharpKml.Dom.Model model = new SharpKml.Dom.Model();
                                model.Location     = loc;
                                model.Orientation  = ori;
                                model.AltitudeMode = SharpKml.Dom.AltitudeMode.Absolute;
                                model.Scale        = sca;

                                SharpKml.Dom.Link link = new SharpKml.Dom.Link();
                                link.Href = new Uri("block_plane_0.dae", UriKind.Relative);

                                model.Link = link;

                                pmplane.Geometry = model;

                                kml.AddFeature(pmplane);
                            }
                        }

                        SharpKml.Dom.LookAt la = new SharpKml.Dom.LookAt()
                        {
                            Altitude     = MainV2.comPort.MAV.cs.altasl,
                            Latitude     = MainV2.comPort.MAV.cs.lat,
                            Longitude    = MainV2.comPort.MAV.cs.lng,
                            Tilt         = 80,
                            Heading      = MainV2.comPort.MAV.cs.yaw,
                            AltitudeMode = SharpKml.Dom.AltitudeMode.Absolute,
                            Range        = 50
                        };

                        if (la.Latitude.Value != 0 && la.Longitude.Value != 0)
                        {
                            kml.Viewpoint = la;
                        }

                        SharpKml.Base.Serializer serializer = new SharpKml.Base.Serializer();
                        serializer.Serialize(kml);

                        byte[] buffer = Encoding.ASCII.GetBytes(serializer.Xml);

                        string header =
                            "HTTP/1.1 200 OK\r\nContent-Type: application/vnd.google-earth.kml+xml\r\nContent-Length: " +
                            buffer.Length + "\r\n\r\n";
                        byte[] temp = asciiEncoding.GetBytes(header);
                        stream.Write(temp, 0, temp.Length);

                        stream.Write(buffer, 0, buffer.Length);

                        goto again;
                    }
                    else if (url.Contains(" /network.kml"))
                    {
                        byte[] buffer = Encoding.ASCII.GetBytes(@"<?xml version=""1.0"" encoding=""UTF-8""?>
<kml xmlns=""http://www.opengis.net/kml/2.2"" xmlns:gx=""http://www.google.com/kml/ext/2.2"" xmlns:kml=""http://www.opengis.net/kml/2.2"" xmlns:atom=""http://www.w3.org/2005/Atom"">
    <Folder>
        <name> Network Links </name>
        <open> 1 </open>
        <NetworkLink>
            <name> View Centered Placemark</name> 
            <open> 1 </open>
            <refreshVisibility> 0 </refreshVisibility>
            <flyToView> 1 </flyToView>
            <Link>
                <href> http://127.0.0.1:56781/location.kml</href>
                <refreshMode> onInterval </refreshMode>
                <refreshInterval> 1 </refreshInterval>
                <viewRefreshTime> 1 </viewRefreshTime>
            </Link>
        </NetworkLink>
        <NetworkLink>
            <name> View Centered Placemark</name> 
            <open> 1 </open>
            <refreshVisibility> 0 </refreshVisibility>
            <flyToView> 0 </flyToView>
            <Link>
                <href> http://127.0.0.1:56781/wps.kml</href>
            </Link>
        </NetworkLink>
    </Folder>
</kml>");

                        string header =
                            "HTTP/1.1 200 OK\r\nContent-Type: application/vnd.google-earth.kml+xml\r\nContent-Length: " +
                            buffer.Length + "\r\n\r\n";
                        byte[] temp = asciiEncoding.GetBytes(header);
                        stream.Write(temp, 0, temp.Length);

                        stream.Write(buffer, 0, buffer.Length);

                        stream.Flush();

                        goto again;
                    }
                    else if (url.Contains(" /wps.kml"))
                    {
                        SharpKml.Dom.Document kml = new SharpKml.Dom.Document();

                        SharpKml.Dom.CoordinateCollection coords = new SharpKml.Dom.CoordinateCollection();

                        PointLatLngAlt home = null;
                        // draw track
                        try
                        {
                            foreach (var point in GCSViews.FlightPlanner.instance.pointlist)
                            {
                                if (point == null)
                                {
                                    continue;
                                }

                                if (point.Tag.ToLower().Contains("home"))
                                {
                                    home = point;
                                }

                                coords.Add(new SharpKml.Base.Vector(point.Lat, point.Lng, point.Alt));
                            }
                        }
                        catch
                        {
                        }

                        var altmode = SharpKml.Dom.AltitudeMode.Absolute;

                        foreach (var point in GCSViews.FlightPlanner.instance.pointlist)
                        {
                            if (point == null)
                            {
                                continue;
                            }

                            SharpKml.Dom.Placemark wp = new SharpKml.Dom.Placemark();
                            wp.Name = "WP " + point.Tag + " Alt: " + point.Alt;
                            SharpKml.Dom.Point wppoint = new SharpKml.Dom.Point();
                            wppoint.AltitudeMode = altmode;
                            wppoint.Coordinate   = new Vector()
                            {
                                Latitude  = point.Lat,
                                Longitude = point.Lng,
                                Altitude  = point.Alt
                            };
                            wp.Geometry = wppoint;
                            kml.AddFeature(wp);
                        }

                        SharpKml.Dom.LineString ls = new SharpKml.Dom.LineString();
                        ls.AltitudeMode = altmode;
                        ls.Coordinates  = coords;
                        ls.Extrude      = false;
                        ls.Tessellate   = true;

                        Style style = new Style();
                        style.Id = "yellowLineGreenPoly";
                        unchecked {
                            style.Line = new LineStyle(new Color32((int)0xff00ffff), 4);
                        }
                        Style style2 = new Style();
                        style2.Id   = "yellowLineGreenPoly";
                        style2.Line = new LineStyle(new Color32((int)0x7f00ffff), 4);

                        // above ground
                        SharpKml.Dom.Placemark pm = new SharpKml.Dom.Placemark()
                        {
                            Geometry      = ls,
                            Name          = "WPs",
                            StyleSelector = style
                        };

                        kml.AddFeature(pm);

                        // on ground
                        SharpKml.Dom.LineString ls2 = new SharpKml.Dom.LineString();
                        ls2.Coordinates  = coords;
                        ls2.Extrude      = false;
                        ls2.Tessellate   = true;
                        ls2.AltitudeMode = SharpKml.Dom.AltitudeMode.ClampToGround;

                        SharpKml.Dom.Placemark pm2 = new SharpKml.Dom.Placemark()
                        {
                            Geometry      = ls2,
                            Name          = "onground",
                            StyleSelector = style2
                        };

                        kml.AddFeature(pm2);

                        SharpKml.Base.Serializer serializer = new SharpKml.Base.Serializer();
                        serializer.Serialize(kml);

                        byte[] buffer = Encoding.ASCII.GetBytes(serializer.Xml);

                        string header =
                            "HTTP/1.1 200 OK\r\nContent-Type: application/vnd.google-earth.kml+xml\r\nContent-Length: " +
                            buffer.Length + "\r\n\r\n";
                        byte[] temp = asciiEncoding.GetBytes(header);
                        stream.Write(temp, 0, temp.Length);

                        stream.Write(buffer, 0, buffer.Length);

                        stream.Flush();

                        goto again;

                        //stream.Close();
                    }

                    /////////////////////////////////////////////////////////////////
                    else if (url.Contains(" /hud.html"))
                    {
                        var    file   = Xamarin.Properties.Resources.hud;
                        string header = "HTTP/1.1 200 OK\r\nConnection: close\r\nContent-Type: text/html\r\nContent-Length: " + file.Length + "\r\n\r\n";
                        byte[] temp   = asciiEncoding.GetBytes(header);
                        stream.Write(temp, 0, temp.Length);

                        byte[] buffer = ASCIIEncoding.ASCII.GetBytes(file);

                        stream.Write(buffer, 0, buffer.Length);
                        stream.Close();
                    }

                    /////////////////////////////////////////////////////////////////
                    else if (url.Contains(" /guided?"))
                    {
                        //http://127.0.0.1:56781/guided?lat=-34&lng=117.8&alt=30

                        Regex rex = new Regex(@"lat=([\-\.0-9]+)&lng=([\-\.0-9]+)&alt=([\.0-9]+)",
                                              RegexOptions.IgnoreCase);

                        Match match = rex.Match(url);

                        if (match.Success)
                        {
                            Locationwp gwp = new Locationwp()
                            {
                                lat = double.Parse(match.Groups[1].Value),
                                lng = double.Parse(match.Groups[2].Value),
                                alt = float.Parse(match.Groups[3].Value)
                            };
                            try
                            {
                                MainV2.comPort.setGuidedModeWP(gwp);
                            }
                            catch
                            {
                            }

                            string header = "HTTP/1.1 200 OK\r\n\r\nSent Guide Mode Wp";
                            byte[] temp   = asciiEncoding.GetBytes(header);
                            stream.Write(temp, 0, temp.Length);
                        }
                        else
                        {
                            string header = "HTTP/1.1 200 OK\r\n\r\nFailed Guide Mode Wp";
                            byte[] temp   = asciiEncoding.GetBytes(header);
                            stream.Write(temp, 0, temp.Length);
                        }
                        stream.Close();
                    }
                    /////////////////////////////////////////////////////////////////
                    else if (url.ToLower().Contains("post /guide"))
                    {
                        Regex rex = new Regex(@"lat"":([\-\.0-9]+),""lon"":([\-\.0-9]+),""alt"":([\.0-9]+)",
                                              RegexOptions.IgnoreCase);

                        Match match = rex.Match(head);

                        if (match.Success)
                        {
                            Locationwp gwp = new Locationwp()
                            {
                                lat = double.Parse(match.Groups[1].Value),
                                lng = double.Parse(match.Groups[2].Value),
                                alt = float.Parse(match.Groups[3].Value)
                            };
                            try
                            {
                                MainV2.comPort.setGuidedModeWP(gwp);
                            }
                            catch
                            {
                            }

                            string header = "HTTP/1.1 200 OK\r\n\r\nSent Guide Mode Wp";
                            byte[] temp   = asciiEncoding.GetBytes(header);
                            stream.Write(temp, 0, temp.Length);
                        }
                        else
                        {
                            string header = "HTTP/1.1 200 OK\r\n\r\nFailed Guide Mode Wp";
                            byte[] temp   = asciiEncoding.GetBytes(header);
                            stream.Write(temp, 0, temp.Length);
                        }
                        stream.Close();
                    }
                    /////////////////////////////////////////////////////////////////
                    else if (url.ToLower().Contains(" /command_long"))
                    {
                        string header = "HTTP/1.1 404 not found\r\nContent-Type: image/jpg\r\n\r\n";
                        byte[] temp   = asciiEncoding.GetBytes(header);
                        stream.Write(temp, 0, temp.Length);

                        stream.Close();
                    }
                    /////////////////////////////////////////////////////////////////
                    else if (url.ToLower().Contains(" /rcoverride"))
                    {
                        string header = "HTTP/1.1 404 not found\r\nContent-Type: image/jpg\r\n\r\n";
                        byte[] temp   = asciiEncoding.GetBytes(header);
                        stream.Write(temp, 0, temp.Length);

                        stream.Close();
                    }
                    /////////////////////////////////////////////////////////////////
                    else if (url.ToLower().Contains(" /get_mission"))
                    {
                        string header = "HTTP/1.1 404 not found\r\nContent-Type: image/jpg\r\n\r\n";
                        byte[] temp   = asciiEncoding.GetBytes(header);
                        stream.Write(temp, 0, temp.Length);

                        stream.Close();
                    }
                    /////////////////////////////////////////////////////////////////
                    else if (url.ToLower().Contains(" /mavlink/"))
                    {
                        /*
                         * GET /mavlink/ATTITUDE+VFR_HUD+NAV_CONTROLLER_OUTPUT+META_WAYPOINT+GPS_RAW_INT+HEARTBEAT+META_LINKQUALITY+GPS_STATUS+STATUSTEXT+SYS_STATUS?_=1355828718540 HTTP/1.1
                         * Host: ubuntu:9999
                         * Connection: keep-alive
                         * X-Requested-With: XMLHttpRequest
                         * User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11
                         * Accept:
                         * Referer: http://ubuntu:9999/index.html
                         * Accept-Encoding: gzip,deflate,sdch
                         * Accept-Language: en-GB,en-US;q=0.8,en;q=0.6
                         * Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
                         *
                         * HTTP/1.1 200 OK
                         * Content-Type: application/json
                         * Content-Length: 2121
                         * Date: Thu, 29 Nov 2012 12:13:38 GMT
                         * Server: ubuntu
                         *
                         * {
                         * "VFR_HUD": {"msg": {"throttle": 0, "groundspeed": 0.0, "airspeed": 0.0, "climb": 0.0, "mavpackettype": "VFR_HUD", "alt": -0.47999998927116394, "heading": 108}, "index": 687, "time_usec": 0},
                         * "STATUSTEXT": {"msg": {"mavpackettype": "STATUSTEXT", "severity": 1, "text": "Initialising APM..."}, "index": 2, "time_usec": 0},
                         * "SYS_STATUS": {"msg": {"onboard_control_sensors_present": 4294966287, "load": 0, "battery_remaining": -1, "errors_count4": 0, "drop_rate_comm": 0, "errors_count2": 0, "errors_count3": 0, "errors_comm": 0, "current_battery": -1, "errors_count1": 0, "onboard_control_sensors_health": 4294966287, "mavpackettype": "SYS_STATUS", "onboard_control_sensors_enabled": 4294945807, "voltage_battery": 10080}, "index": 693, "time_usec": 0},
                         * "META_LINKQUALITY": {"msg": {"master_in": 11110, "mav_loss": 0, "mavpackettype": "META_LINKQUALITY", "master_out": 194, "packet_loss": 0.0}, "index": 194, "time_usec": 0},
                         * "ATTITUDE": {"msg": {"pitchspeed": -0.000976863200776279, "yaw": 1.8878594636917114, "rollspeed": -0.0030046366155147552, "time_boot_ms": 194676, "pitch": -0.09986469894647598, "mavpackettype": "ATTITUDE", "yawspeed": -0.0015030358918011189, "roll": -0.029391441494226456}, "index": 687, "time_usec": 0},
                         * "GPS_RAW_INT": {"msg": {"fix_type": 1, "cog": 0, "epv": 65535, "lon": 0, "time_usec": 0, "eph": 9999, "satellites_visible": 0, "lat": 0, "mavpackettype": "GPS_RAW_INT", "alt": 137000, "vel": 0}, "index": 687, "time_usec": 0},
                         * "HEARTBEAT": {"msg": {"custom_mode": 0, "system_status": 4, "base_mode": 81, "autopilot": 3, "mavpackettype": "HEARTBEAT", "type": 2, "mavlink_version": 3}, "index": 190, "time_usec": 0},
                         * "GPS_STATUS": {"msg": {"satellite_snr": "", "satellite_azimuth": "", "satellite_prn": "", "satellite_elevation": "", "satellites_visible": 0, "satellite_used": "", "mavpackettype": "GPS_STATUS"}, "index": 2, "time_usec": 0},
                         * "NAV_CONTROLLER_OUTPUT": {"msg": {"wp_dist": 0, "nav_pitch": 0.0, "target_bearing": 0, "nav_roll": 0.0, "aspd_error": 0.0, "alt_error": 0.0, "mavpackettype": "NAV_CONTROLLER_OUTPUT", "xtrack_error": 0.0, "nav_bearing": 0}, "index": 687, "time_usec": 0}}
                         */

                        object[] data = new object[20];

                        if (MainV2.comPort.MAV.getPacket((byte)MAVLink.MAVLINK_MSG_ID.ATTITUDE) != null)
                        {
                            var tmsg = MainV2.comPort.MAV.getPacket((uint)MAVLink.MAVLINK_MSG_ID.ATTITUDE)
                                       .ToStructure <MAVLink.mavlink_attitude_t>();

                            var json = JsonConvert.SerializeObject(tmsg);

                            var name = MAVLink.MAVLINK_MESSAGE_INFOS.GetMessageInfo((uint)MAVLink.MAVLINK_MSG_ID.ATTITUDE).name;
                        }

                        Messagejson message = new Messagejson();

                        if (MainV2.comPort.MAV.getPacket((byte)MAVLink.MAVLINK_MSG_ID.ATTITUDE) != null)
                        {
                            message.ATTITUDE = new Message2()
                            {
                                index = 1,
                                msg   =
                                    MainV2.comPort.MAV.getPacket((byte)MAVLink.MAVLINK_MSG_ID.ATTITUDE)
                                    .ToStructure <MAVLink.mavlink_attitude_t>()
                            }
                        }
                        ;
                        if (MainV2.comPort.MAV.getPacket((byte)MAVLink.MAVLINK_MSG_ID.VFR_HUD) != null)
                        {
                            message.VFR_HUD = new Message2()
                            {
                                index = 1,
                                msg   =
                                    MainV2.comPort.MAV.getPacket((byte)MAVLink.MAVLINK_MSG_ID.VFR_HUD)
                                    .ToStructure <MAVLink.mavlink_vfr_hud_t>()
                            }
                        }
                        ;
                        if (MainV2.comPort.MAV.getPacket((byte)MAVLink.MAVLINK_MSG_ID.NAV_CONTROLLER_OUTPUT) != null)
                        {
                            message.NAV_CONTROLLER_OUTPUT = new Message2()
                            {
                                index = 1,
                                msg   =
                                    MainV2.comPort.MAV.getPacket((byte)MAVLink.MAVLINK_MSG_ID.NAV_CONTROLLER_OUTPUT)
                                    .ToStructure <MAVLink.mavlink_nav_controller_output_t>()
                            }
                        }
                        ;
                        if (MainV2.comPort.MAV.getPacket((byte)MAVLink.MAVLINK_MSG_ID.GPS_RAW_INT) != null)
                        {
                            message.GPS_RAW_INT = new Message2()
                            {
                                index = 1,
                                msg   =
                                    MainV2.comPort.MAV.getPacket((byte)MAVLink.MAVLINK_MSG_ID.GPS_RAW_INT)
                                    .ToStructure <MAVLink.mavlink_gps_raw_int_t>()
                            }
                        }
                        ;
                        if (MainV2.comPort.MAV.getPacket((byte)MAVLink.MAVLINK_MSG_ID.HEARTBEAT) != null)
                        {
                            message.HEARTBEAT = new Message2()
                            {
                                index = 1,
                                msg   =
                                    MainV2.comPort.MAV.getPacket((byte)MAVLink.MAVLINK_MSG_ID.HEARTBEAT)
                                    .ToStructure <MAVLink.mavlink_heartbeat_t>()
                            }
                        }
                        ;
                        if (MainV2.comPort.MAV.getPacket((byte)MAVLink.MAVLINK_MSG_ID.GPS_STATUS) != null)
                        {
                            message.GPS_STATUS = new Message2()
                            {
                                index = 1,
                                msg   =
                                    MainV2.comPort.MAV.getPacket((byte)MAVLink.MAVLINK_MSG_ID.GPS_STATUS)
                                    .ToStructure <MAVLink.mavlink_gps_status_t>()
                            }
                        }
                        ;
                        if (MainV2.comPort.MAV.getPacket((byte)MAVLink.MAVLINK_MSG_ID.STATUSTEXT) != null)
                        {
                            message.STATUSTEXT = new Message2()
                            {
                                index = 1,
                                msg   =
                                    MainV2.comPort.MAV.getPacket((byte)MAVLink.MAVLINK_MSG_ID.STATUSTEXT)
                                    .ToStructure <MAVLink.mavlink_statustext_t>()
                            }
                        }
                        ;
                        if (MainV2.comPort.MAV.getPacket((byte)MAVLink.MAVLINK_MSG_ID.SYS_STATUS) != null)
                        {
                            message.SYS_STATUS = new Message2()
                            {
                                index = 1,
                                msg   =
                                    MainV2.comPort.MAV.getPacket((byte)MAVLink.MAVLINK_MSG_ID.SYS_STATUS)
                                    .ToStructure <MAVLink.mavlink_sys_status_t>()
                            }
                        }
                        ;

                        message.META_LINKQUALITY =
                            message.SYS_STATUS   =
                                new Message2()
                        {
                            index     = packetindex,
                            time_usec = 0,
                            msg       =
                                new META_LINKQUALITY()
                            {
                                master_in     = (int)MainV2.comPort.MAV.packetsnotlost,
                                mavpackettype = "META_LINKQUALITY",
                                master_out    = MainV2.comPort.packetcount,
                                packet_loss   = 100 - MainV2.comPort.MAV.cs.linkqualitygcs,
                                mav_loss      = 0
                            }
                        };

                        packetindex++;

                        string output = JsonConvert.SerializeObject(message);

                        string header = "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: " +
                                        output.Length + "\r\n\r\n";
                        byte[] temp = asciiEncoding.GetBytes(header);
                        stream.Write(temp, 0, temp.Length);

                        temp = asciiEncoding.GetBytes(output);
                        stream.Write(temp, 0, temp.Length);

                        stream.Flush();

                        goto again;

                        //stream.Close();
                    }
                    /////////////////////////////////////////////////////////////////
                    else if (url.ToLower().Contains(" /mav/"))
                    {
                        //C:\Users\hog\Desktop\DIYDrones\mavelous\modules\lib\mavelous_web


                        Regex rex = new Regex(@"([^\s]+)\s(.+)\sHTTP/1", RegexOptions.IgnoreCase);

                        Match match = rex.Match(url);

                        if (match.Success)
                        {
                            string fileurl = WebUtility.UrlDecode(match.Groups[2].Value);

                            fileurl = fileurl.Replace("/mav/", "");

                            if (fileurl == "" || fileurl == "/")
                            {
                                fileurl = "index.html";
                            }

                            if (File.Exists(mavelous_web + fileurl))
                            {
                                string header = "HTTP/1.1 200 OK\r\n";
                                if (fileurl.Contains(".htm"))
                                {
                                    header += "Content-Type: text/html\r\n";
                                }
                                else if (fileurl.Contains(".js"))
                                {
                                    header += "Content-Type: application/x-javascript\r\n";
                                }
                                else if (fileurl.Contains(".css"))
                                {
                                    header += "Content-Type: text/css\r\n";
                                }
                                else
                                {
                                    header += "Content-Type: text/plain\r\n";
                                }

                                var fileinfo = new FileInfo(mavelous_web + fileurl);

                                var filetime = fileinfo.LastWriteTimeUtc.ToString("ddd, dd MMM yyyy HH:mm:ss") + " GMT";
                                var modified = Regex.Match(head, "If-Modified-Since:(.*)", RegexOptions.IgnoreCase);
                                if (modified.Success && modified.Groups[1].Value.Trim().ToLower() == filetime.ToLower())
                                {
                                    string header2 = "HTTP/1.1 304 not modified\r\nConnection: Keep-Alive\r\n\r\n";
                                    byte[] temp2   = asciiEncoding.GetBytes(header2);
                                    stream.Write(temp2, 0, temp2.Length);

                                    stream.Flush();

                                    goto again;
                                }

                                header += "Connection: keep-alive\r\nLast-Modified: " + filetime + "\r\nContent-Length: " + fileinfo.Length + "\r\n\r\n";


                                byte[] temp = asciiEncoding.GetBytes(header);
                                stream.Write(temp, 0, temp.Length);

                                BinaryReader file =
                                    new BinaryReader(File.Open(mavelous_web + fileurl, FileMode.Open, FileAccess.Read,
                                                               FileShare.Read));
                                byte[] buffer = new byte[1024];
                                while (file.BaseStream.Position < file.BaseStream.Length)
                                {
                                    int leng = file.Read(buffer, 0, buffer.Length);

                                    stream.Write(buffer, 0, leng);
                                }
                                file.Close();

                                stream.Flush();

                                goto again;
                            }
                        }

                        /////////////////////////////////////////////////////////////////
                        {
                            string header = "HTTP/1.1 404 not found\r\nConnection: Keep-Alive\r\nContent-Length: 0\r\nContent -Type: text/plain\r\n\r\n";
                            byte[] temp   = asciiEncoding.GetBytes(header);
                            stream.Write(temp, 0, temp.Length);

                            stream.Flush();

                            goto again;
                        }
                    }

                    /////////////////////////////////////////////////////////////////
                    else if (url.ToLower().Contains(" / "))
                    {
                        Console.WriteLine(url);
                        string header = "HTTP/1.1 200 OK\r\nConnection: close\r\nContent-Type: text/html\r\n\r\n";
                        byte[] temp   = asciiEncoding.GetBytes(header);
                        stream.Write(temp, 0, temp.Length);

                        string content = @"
                <a href=/mav/>Mavelous</a>
<a href=/mavlink/>Mavelous traffic</a>
<a href=/hud.jpg>Hud image</a>
<a href=/map.jpg>Map image </a>
<a href=/both.jpg>Map & hud image</a>
<a href=/hud.html>hud html5</a>
<a href=/network.kml>network kml</a>
<a href=/georefnetwork.kml>georef kml</a>

";
                        temp = asciiEncoding.GetBytes(content);
                        stream.Write(temp, 0, temp.Length);
                    }
                    /////////////////////////////////////////////////////////////////
                    else
                    {
                        string header = "HTTP/1.1 404 not found\r\nContent-Type: text/plain\r\n\r\n";
                        byte[] temp   = asciiEncoding.GetBytes(header);
                        stream.Write(temp, 0, temp.Length);
                    }

                    stream.Close();
                    log.Info("Close http " + url);
                    client.Close();
                }
                catch (Exception ee)
                {
                    log.Error("Failed http ", ee);
                }
            }
        }
        private void btnOutputKML_Click(object sender, EventArgs e)
        {
            LinkedList <WayPoints> wp_list = _path.waypoints;

            int pcount      = 0;
            int point_count = wp_list.Count;

            if (point_count > 0)
            {
                //double lat_center = Convert.ToDouble(txtCenterLat.Text);
                //double lon_center = Convert.ToDouble(txtCenterLon.Text);
                double lat, new_lat, start_lat;
                double lon, new_lon, start_lon;
                double image_len;
                double image_wid;

                image_len = (Math.Tan(GPS.DegreesToRadians(_options.focal_angle_hor / 2)) * 30.0);
                image_wid = (Math.Tan(GPS.DegreesToRadians(_options.focal_angle_ver / 2)) * 30.0);
                double alt;
                double bear;
                string location_name = txtKMLPath.Text;
                string filename      = txtKMLFilePath.Text;

                Kml kml = new Kml();

                Folder folder = new Folder();
                SharpKml.Dom.Placemark placemark  = new SharpKml.Dom.Placemark();
                LineString             linestring = new LineString();
                var vector = new Vector();
                CoordinateCollection coordinates = new CoordinateCollection();

                Style path_style = new Style();
                path_style.Polygon = new PolygonStyle();
                path_style.Line    = new LineStyle();
                // Color32( alpha, blue, green, red
                path_style.Polygon.Color = new Color32(128, 255, 255, 0);
                path_style.Line.Color    = new Color32(255, 255, 255, 0);
                linestring.AltitudeMode  = AltitudeMode.RelativeToGround;
                linestring.Extrude       = true;
                WayPoints point = new WayPoints();

                do
                {
                    point = wp_list.ElementAt(pcount);
                    lat   = point.lat;
                    lon   = point.lon;
                    alt   = point.alt;
                    if (!_options.units_metric)
                    {
                        alt = GPS.FeetToMeters(alt);
                    }

                    vector = new Vector(lat, lon, alt);

                    coordinates.Add(vector);
                    pcount++;
                } while (pcount < point_count);

                linestring.Coordinates = coordinates;
                placemark.Geometry     = linestring;
                placemark.AddStyle(path_style);
                placemark.Name = location_name;
                folder.AddFeature(placemark);
                // kml.Feature = placemark;

                /* Generate camera rectangles */

                if (chkGenCamRect.Checked)
                {
                    //image_len = 25;
                    //image_wid = 50;
                    double diag_ang = GPS.RadiansToDegrees(Math.Atan(image_len / image_wid));
                    double diag_len = Math.Sqrt((image_len * image_len) + (image_wid * image_wid));
                    double gps_radius;

                    for (int i = 0; i < wp_list.Count; i++)
                    {
                        Style poly_style = new Style();
                        poly_style.Polygon = new PolygonStyle();
                        poly_style.Line    = new LineStyle();
                        // Color32( alpha, blue, green, red
                        poly_style.Polygon.Color = new Color32(128, 0, 255, 255);
                        poly_style.Line.Color    = new Color32(255, 0, 255, 255);
                        Kml kml_rect = new Kml();
                        SharpKml.Dom.Placemark rect_placemark = new SharpKml.Dom.Placemark();
                        Polygon              poly             = new Polygon();
                        OuterBoundary        outer            = new OuterBoundary();
                        LinearRing           line             = new LinearRing();
                        CoordinateCollection coor             = new CoordinateCollection();
                        poly.AltitudeMode = AltitudeMode.RelativeToGround;
                        poly.Extrude      = false;

                        point      = wp_list.ElementAt(i);
                        lat        = point.lat;
                        lon        = point.lon;
                        alt        = point.alt;
                        gps_radius = _options.earth_radius + _options.def_elevation + alt;
                        alt        = 2;
                        bear       = point.head;
                        coor.Clear();
                        new_lat   = GPS.GPS_Lat_BearDist(lat, lon, diag_ang + bear, diag_len, gps_radius);
                        new_lon   = GPS.GPS_Lon_BearDist(lat, lon, new_lat, diag_ang + bear, diag_len, gps_radius);
                        start_lat = new_lat;
                        start_lon = new_lon;
                        vector    = new Vector(new_lat, new_lon, alt);
                        coor.Add(vector);
                        new_lat = GPS.GPS_Lat_BearDist(lat, lon, 180 - diag_ang + bear, diag_len, gps_radius);
                        new_lon = GPS.GPS_Lon_BearDist(lat, lon, new_lat, 180 - diag_ang + bear, diag_len, gps_radius);
                        vector  = new Vector(new_lat, new_lon, alt);
                        coor.Add(vector);
                        new_lat = GPS.GPS_Lat_BearDist(lat, lon, 180 + diag_ang + bear, diag_len, gps_radius);
                        new_lon = GPS.GPS_Lon_BearDist(lat, lon, new_lat, 180 + diag_ang + bear, diag_len, gps_radius);
                        vector  = new Vector(new_lat, new_lon, alt);
                        coor.Add(vector);
                        new_lat = GPS.GPS_Lat_BearDist(lat, lon, 360 - diag_ang + bear, diag_len, gps_radius);
                        new_lon = GPS.GPS_Lon_BearDist(lat, lon, new_lat, 360 - diag_ang + bear, diag_len, gps_radius);
                        vector  = new Vector(new_lat, new_lon, alt);
                        coor.Add(vector);
                        vector = new Vector(start_lat, start_lon, alt);
                        coor.Add(vector);

                        line.Coordinates   = coor;
                        outer.LinearRing   = line;
                        poly.OuterBoundary = outer;

                        rect_placemark.Geometry = poly;
                        rect_placemark.AddStyle(poly_style);
                        rect_placemark.Name = "WP " + Convert.ToString(i);
                        folder.AddFeature(rect_placemark);
                    }
                }

                kml.Feature = folder;
                Serializer serializer = new Serializer();
                serializer.Serialize(kml);


                System.IO.File.WriteAllText(filename, serializer.Xml);
            }
            this.Close();
        }
        /// <summary>
        /// Converts a dictionary representing JSON layer definitions to KML.
        /// </summary>
        /// <param name="layers">A dictionary representing ArcGIS JSON Layers.</param>
        /// <returns><see cref="Kml"/></returns>
        public static Kml LayersDictionaryToKml(this Dictionary<string, object> layers)
        {
            var kmlDocument = new SharpKml.Dom.Document();

            foreach (var kvp in layers)
            {
                var folder = new Folder { Name = kvp.Key };
                kmlDocument.AddFeature(folder);
                var graphics = kvp.Value as ArrayList;
                foreach (Dictionary<string, object> graphic in graphics)
                {
                    var placemark = new Placemark();
                    folder.AddFeature(placemark);
                    placemark.Geometry = JsonToKmlGeometry(graphic["geometry"] as Dictionary<string, object>);
                    var attributesJson = (Dictionary<string, object>)graphic["attributes"];
                    attributesJson.Remove("RouteGeometry");
                    placemark.ExtendedData = ToExtendedData(attributesJson);
                }
            }

            var kml = new Kml();
            kml.Feature = kmlDocument;
            return kml;
        }
        private void btnSelectKMLFile_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                /* Get kml filename */

                string kml_file = openFileDialog1.FileName;

                if (kml_file.Contains(".kml"))
                {
                    Form1.Globals.kml_filename = kml_file;
                    rtbKMLRead.AppendText("KML File : " + kml_file + "\n");
                    rtbKMLRead.AppendText("\n");

                    /* Open KML File */

                    System.IO.TextReader    stream = System.IO.File.OpenText(kml_file);
                    SharpKml.Engine.KmlFile file   = KmlFile.Load(stream);
                    Kml _kml = file.Root as Kml;

                    SharpKml.Dom.Placemark[] tempPlaceMarks = new SharpKml.Dom.Placemark[1000];
                    SharpKml.Dom.Placemark   tmp_placemark  = new SharpKml.Dom.Placemark();
                    CoordinateCollection     coordinates    = new CoordinateCollection();


                    Form1.Globals.kml_point_count = 0;

                    //rtbKMLRead.AppendText("Waypoint Count : " + Convert.ToString(Globals.waypoint_count) + "\n");

                    int numOfPlaceMarks = 0;

                    if (_kml != null)
                    {
                        foreach (var placemark in _kml.Flatten().OfType <SharpKml.Dom.Placemark>())
                        {
                            string placename = placemark.Name;
                            rtbKMLRead.AppendText("Placemark Name : " + placename + "\n");
                            tmp_placemark.Name = placename;
                            numOfPlaceMarks++;
                        }
                        rtbKMLRead.AppendText("Number of Placemarks : " + Convert.ToString(numOfPlaceMarks) + "\n");


                        int num_linestring = 0;
                        SharpKml.Base.Vector vector;
                        double lat;
                        double lon;
                        double alt;

                        foreach (var linestring in _kml.Flatten().OfType <LineString>())
                        {
                            coordinates = linestring.Coordinates;
                            int num = coordinates.Count;
                            rtbKMLRead.AppendText("Num Coordinates : " + Convert.ToString(num) + "\n");
                            for (int i = 0; i < num; i++)
                            {
                                vector = coordinates.ElementAt(i);
                                lat    = vector.Latitude;
                                lon    = vector.Longitude;
                                alt    = (double)vector.Altitude;
                                rtbKMLRead.AppendText("Lat/Lon : " + Convert.ToString(lat));
                                rtbKMLRead.AppendText(", " + Convert.ToString(lon) + "Altitude : " + Convert.ToString(alt) + "\n");
                                _kml_points[_kml_point_count, 0] = lat;
                                _kml_points[_kml_point_count, 1] = lon;
                                _kml_points[_kml_point_count, 2] = alt;
                                _kml_point_count++;
                                //dgvWaypoints.Rows.Add(Globals.waypoint_count, Convert.ToString(lat), Convert.ToString(lon), Convert.ToString(30));
                            }
                            num_linestring++;
                        }
                        rtbKMLRead.AppendText("Number of Linestrings : " + Convert.ToString(num_linestring) + "\n");

                        BuildKMLPath();
                    }
                }
                else
                {
                    MessageBox.Show("Wrong file type!", "GPS Grid:", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
                }
            }
        }
Example #46
0
        public void DoAcceptTcpClientCallback(IAsyncResult ar)
        {
            // Get the listener that handles the client request.
            TcpListener listener = (TcpListener) ar.AsyncState;

            // End the operation and display the received data on  
            // the console.
            using (
                TcpClient client = listener.EndAcceptTcpClient(ar))
            {
                // Signal the calling thread to continue.
                tcpClientConnected.Set();


                try
                {
                    // Get a stream object for reading and writing          
                    log.Info("Accepted Client " + client.Client.RemoteEndPoint.ToString());
                    //client.SendBufferSize = 100 * 1024; // 100kb
                    //client.LingerState.Enabled = true;
                    //client.NoDelay = true;

                    // makesure we have valid image
                    GCSViews.FlightData.myhud.streamjpgenable = true;

                    NetworkStream stream = client.GetStream();

                    // 5 seconds - default for httpd 2.2+
                    stream.ReadTimeout = 5000;

                    goto skipagain;

                    again:
                    log.Info("doing Again");

                    skipagain:

                    var asciiEncoding = new ASCIIEncoding();

                    var request = new byte[1024*4];
                    int len = 0;

                    // handle header
                    try
                    {
                        len = stream.Read(request, 0, request.Length);
                    }
                    catch
                    {
                        return;
                    }

                    string head = System.Text.Encoding.ASCII.GetString(request, 0, len);
                    log.Info(head);

                    int index = head.IndexOf('\n');

                    string url = head.Substring(0, index - 1);
                    //url = url.Replace("\r", "");
                    //url = url.Replace("GET ","");
                    //url = url.Replace(" HTTP/1.0", "");
                    //url = url.Replace(" HTTP/1.1", "");

                    Tracking.AddEvent("HTTPServer", "Get", url, "");
/////////////////////////////////////////////////////////////////
                    if (url.Contains("websocket"))
                    {
                        using (var writer = new StreamWriter(stream, Encoding.Default))
                        {
                            writer.WriteLine("HTTP/1.1 101 WebSocket Protocol Handshake");
                            writer.WriteLine("Upgrade: WebSocket");
                            writer.WriteLine("Connection: Upgrade");
                            writer.WriteLine("WebSocket-Location: ws://localhost:56781/websocket/server");

                            int start = head.IndexOf("Sec-WebSocket-Key:") + 19;
                            int end = head.IndexOf('\r', start);
                            if (end == -1)
                                end = head.IndexOf('\n', start);
                            string accept = ComputeWebSocketHandshakeSecurityHash09(head.Substring(start, end - start));

                            writer.WriteLine("Sec-WebSocket-Accept: " + accept);

                            writer.WriteLine("Server: Mission Planner");

                            writer.WriteLine("");

                            writer.Flush();

                            while (client.Connected)
                            {
                                Thread.Sleep(200);
                                log.Debug(stream.DataAvailable + " " + client.Available);

                                while (client.Available > 0)
                                {
                                    Console.Write(stream.ReadByte());
                                }

                                byte[] packet = new byte[1024];

                                string sendme = MainV2.comPort.MAV.cs.roll + "," + MainV2.comPort.MAV.cs.pitch + "," + MainV2.comPort.MAV.cs.yaw
                                                + "," + MainV2.comPort.MAV.cs.lat + "," + MainV2.comPort.MAV.cs.lng + "," + MainV2.comPort.MAV.cs.alt;

                                packet[0] = 0x81; // fin - binary
                                packet[1] = (byte) sendme.Length;

                                int i = 2;
                                foreach (char ch in sendme)
                                {
                                    packet[i++] = (byte) ch;
                                }

                                stream.Write(packet, 0, i);

                                //break;
                            }
                        }
                    }
                    /////////////////////////////////////////////////////////////////
                    else if (url.Contains("georefnetwork.kml"))
                    {
                        byte[] buffer = Encoding.ASCII.GetBytes(georefkml);

                        string header =
                            "HTTP/1.1 200 OK\r\nServer: here\r\nKeep-Alive: timeout=15, max=100\r\nConnection: Keep-Alive\r\nCache-Control: no-cache\r\nContent-Type: application/vnd.google-earth.kml+xml\r\nX-Pad: avoid browser bug\r\nContent-Length: " +
                            buffer.Length + "\r\n\r\n";
                        byte[] temp = asciiEncoding.GetBytes(header);
                        stream.Write(temp, 0, temp.Length);

                        stream.Write(buffer, 0, buffer.Length);

                        goto again;

                        //stream.Close();
                    }
                    /////////////////////////////////////////////////////////////////
                    else if (url.Contains("network.kml"))
                    {
                        SharpKml.Dom.Document kml = new SharpKml.Dom.Document();

                        SharpKml.Dom.Placemark pmplane = new SharpKml.Dom.Placemark();
                        pmplane.Name = "P/Q " + MainV2.comPort.MAV.cs.altasl;

                        pmplane.Visibility = true;

                        SharpKml.Dom.Location loc = new SharpKml.Dom.Location();
                        loc.Latitude = MainV2.comPort.MAV.cs.lat;
                        loc.Longitude = MainV2.comPort.MAV.cs.lng;
                        loc.Altitude = MainV2.comPort.MAV.cs.altasl;

                        if (loc.Altitude < 0)
                            loc.Altitude = 0.01;

                        SharpKml.Dom.Orientation ori = new SharpKml.Dom.Orientation();
                        ori.Heading = MainV2.comPort.MAV.cs.yaw;
                        ori.Roll = -MainV2.comPort.MAV.cs.roll;
                        ori.Tilt = -MainV2.comPort.MAV.cs.pitch;

                        SharpKml.Dom.Scale sca = new SharpKml.Dom.Scale();

                        sca.X = 2;
                        sca.Y = 2;
                        sca.Z = 2;

                        SharpKml.Dom.Model model = new SharpKml.Dom.Model();
                        model.Location = loc;
                        model.Orientation = ori;
                        model.AltitudeMode = SharpKml.Dom.AltitudeMode.Absolute;
                        model.Scale = sca;

                        SharpKml.Dom.Link link = new SharpKml.Dom.Link();
                        link.Href = new Uri("block_plane_0.dae", UriKind.Relative);

                        model.Link = link;

                        pmplane.Geometry = model;

                        SharpKml.Dom.LookAt la = new SharpKml.Dom.LookAt()
                        {
                            Altitude = loc.Altitude.Value,
                            Latitude = loc.Latitude.Value,
                            Longitude = loc.Longitude.Value,
                            Tilt = 80,
                            Heading = MainV2.comPort.MAV.cs.yaw,
                            AltitudeMode = SharpKml.Dom.AltitudeMode.Absolute,
                            Range = 50
                        };

                        if (loc.Latitude.Value != 0 && loc.Longitude.Value != 0)
                        {
                            kml.Viewpoint = la;
                            kml.AddFeature(pmplane);
                        }

                        SharpKml.Dom.CoordinateCollection coords = new SharpKml.Dom.CoordinateCollection();

                        //if (loc.Latitude.Value != 0 && loc.Longitude.Value != 0)
                        {
                            //foreach (var point in MainV2.comPort.MAV.wps.Values)
                            {
                                //    coords.Add(new SharpKml.Base.Vector(point.x, point.y, point.z));
                            }
                        }
                        //else
                        {
                            PointLatLngAlt home = null;
                            // draw track
                            try
                            {
                                foreach (var point in GCSViews.FlightPlanner.instance.fullpointlist)
                                {
                                    if (point.Tag.ToLower().Contains("home"))
                                        home = point;

                                    if (point != null)
                                        coords.Add(new SharpKml.Base.Vector(point.Lat, point.Lng, point.Alt));
                                }
                            }
                            catch
                            {
                            }

                            foreach (var point in GCSViews.FlightPlanner.instance.fullpointlist)
                            {
                                if (point == null)
                                    continue;

                                SharpKml.Dom.Placemark wp = new SharpKml.Dom.Placemark();
                                wp.Name = "WP " + point.Tag + " Alt: " + point.Alt;
                                SharpKml.Dom.Point wppoint = new SharpKml.Dom.Point();
                                var altmode = SharpKml.Dom.AltitudeMode.RelativeToGround;
                                wppoint.AltitudeMode = altmode;
                                wppoint.Coordinate = new Vector()
                                {
                                    Latitude = point.Lat,
                                    Longitude = point.Lng,
                                    Altitude = point.Alt
                                };
                                wp.Geometry = wppoint;
                                kml.AddFeature(wp);
                            }
                        }

                        SharpKml.Dom.LineString ls = new SharpKml.Dom.LineString();
                        ls.AltitudeMode = SharpKml.Dom.AltitudeMode.RelativeToGround;
                        ls.Coordinates = coords;
                        ls.Extrude = false;
                        ls.Tessellate = true;

                        Style style = new Style();
                        style.Id = "yellowLineGreenPoly";
                        style.Line = new LineStyle(new Color32(HexStringToColor("ff00ffff")), 4);

                        Style style2 = new Style();
                        style2.Id = "yellowLineGreenPoly";
                        style2.Line = new LineStyle(new Color32(HexStringToColor("7f00ffff")), 4);

                        // above ground
                        SharpKml.Dom.Placemark pm = new SharpKml.Dom.Placemark()
                        {
                            Geometry = ls,
                            Name = "WPs",
                            StyleSelector = style
                        };

                        kml.AddFeature(pm);

                        // on ground
                        SharpKml.Dom.LineString ls2 = new SharpKml.Dom.LineString();
                        ls2.Coordinates = coords;
                        ls2.Extrude = false;
                        ls2.Tessellate = true;
                        ls2.AltitudeMode = SharpKml.Dom.AltitudeMode.ClampToGround;

                        SharpKml.Dom.Placemark pm2 = new SharpKml.Dom.Placemark()
                        {
                            Geometry = ls2,
                            Name = "onground",
                            StyleSelector = style2
                        };

                        kml.AddFeature(pm2);

                        SharpKml.Base.Serializer serializer = new SharpKml.Base.Serializer();
                        serializer.Serialize(kml);

                        byte[] buffer = Encoding.ASCII.GetBytes(serializer.Xml);

                        string header =
                            "HTTP/1.1 200 OK\r\nContent-Type: application/vnd.google-earth.kml+xml\r\nContent-Length: " +
                            buffer.Length + "\r\n\r\n";
                        byte[] temp = asciiEncoding.GetBytes(header);
                        stream.Write(temp, 0, temp.Length);

                        stream.Write(buffer, 0, buffer.Length);

                        goto again;

                        //stream.Close();
                    }
                    /////////////////////////////////////////////////////////////////
                    else if (url.Contains("block_plane_0.dae"))
                    {
                        string header = "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n\r\n";
                        byte[] temp = asciiEncoding.GetBytes(header);
                        stream.Write(temp, 0, temp.Length);

                        BinaryReader file =
                            new BinaryReader(File.Open("block_plane_0.dae", FileMode.Open, FileAccess.Read,
                                FileShare.Read));
                        byte[] buffer = new byte[1024];
                        while (file.PeekChar() != -1)
                        {
                            int leng = file.Read(buffer, 0, buffer.Length);

                            stream.Write(buffer, 0, leng);
                        }
                        file.Close();
                        stream.Close();
                    }
                    /////////////////////////////////////////////////////////////////
                    else if (url.Contains("hud.html"))
                    {
                        string header = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n";
                        byte[] temp = asciiEncoding.GetBytes(header);
                        stream.Write(temp, 0, temp.Length);

                        BinaryReader file =
                            new BinaryReader(File.Open("hud.html", FileMode.Open, FileAccess.Read, FileShare.Read));
                        byte[] buffer = new byte[1024];
                        while (file.PeekChar() != -1)
                        {
                            int leng = file.Read(buffer, 0, buffer.Length);

                            stream.Write(buffer, 0, leng);
                        }
                        file.Close();
                        stream.Close();
                    }
                    /////////////////////////////////////////////////////////////////
                    else if (url.ToLower().Contains("hud.jpg") || url.ToLower().Contains("map.jpg") ||
                             url.ToLower().Contains("both.jpg"))
                    {
                        refreshmap();

                        string header =
                            "HTTP/1.1 200 OK\r\nContent-Type: multipart/x-mixed-replace;boundary=PLANNER\r\n\r\n--PLANNER\r\n";
                        byte[] temp = asciiEncoding.GetBytes(header);
                        stream.Write(temp, 0, temp.Length);

                        while (client.Connected)
                        {
                            System.Threading.Thread.Sleep(200); // 5hz
                            byte[] data = null;

                            if (url.ToLower().Contains("hud"))
                            {
                                GCSViews.FlightData.myhud.streamjpgenable = true;
                                data = GCSViews.FlightData.myhud.streamjpg.ToArray();
                            }
                            else if (url.ToLower().Contains("map"))
                            {
                                data = GetControlJpegRaw(GCSViews.FlightData.mymap);
                            }
                            else
                            {
                                GCSViews.FlightData.myhud.streamjpgenable = true;
                                Image img1 = Image.FromStream(GCSViews.FlightData.myhud.streamjpg);
                                Image img2 = GetControlJpeg(GCSViews.FlightData.mymap);
                                int bigger = img1.Height > img2.Height ? img1.Height : img2.Height;
                                Image imgout = new Bitmap(img1.Width + img2.Width, bigger);

                                Graphics grap = Graphics.FromImage(imgout);

                                grap.DrawImageUnscaled(img1, 0, 0);
                                grap.DrawImageUnscaled(img2, img1.Width, 0);

                                MemoryStream streamjpg = new MemoryStream();
                                imgout.Save(streamjpg, System.Drawing.Imaging.ImageFormat.Jpeg);
                                data = streamjpg.ToArray();
                            }

                            header = "Content-Type: image/jpeg\r\nContent-Length: " + data.Length + "\r\n\r\n";
                            temp = asciiEncoding.GetBytes(header);
                            stream.Write(temp, 0, temp.Length);

                            stream.Write(data, 0, data.Length);

                            header = "\r\n--PLANNER\r\n";
                            temp = asciiEncoding.GetBytes(header);
                            stream.Write(temp, 0, temp.Length);
                        }
                        GCSViews.FlightData.myhud.streamjpgenable = false;
                        stream.Close();
                    }
                    /////////////////////////////////////////////////////////////////
                    else if (url.Contains("/guided?"))
                    {
                        //http://127.0.0.1:56781/guided?lat=-34&lng=117.8&alt=30

                        Regex rex = new Regex(@"lat=([\-\.0-9]+)&lng=([\-\.0-9]+)&alt=([\.0-9]+)",
                            RegexOptions.IgnoreCase);

                        Match match = rex.Match(url);

                        if (match.Success)
                        {
                            Locationwp gwp = new Locationwp()
                            {
                                lat = double.Parse(match.Groups[1].Value),
                                lng = double.Parse(match.Groups[2].Value),
                                alt = float.Parse(match.Groups[3].Value)
                            };
                            try
                            {
                                MainV2.comPort.setGuidedModeWP(gwp);
                            }
                            catch
                            {
                            }

                            string header = "HTTP/1.1 200 OK\r\n\r\nSent Guide Mode Wp";
                            byte[] temp = asciiEncoding.GetBytes(header);
                            stream.Write(temp, 0, temp.Length);
                        }
                        else
                        {
                            string header = "HTTP/1.1 200 OK\r\n\r\nFailed Guide Mode Wp";
                            byte[] temp = asciiEncoding.GetBytes(header);
                            stream.Write(temp, 0, temp.Length);
                        }
                        stream.Close();
                    }
                    /////////////////////////////////////////////////////////////////
                    else if (url.ToLower().Contains(".jpg"))
                    {
                        Regex rex = new Regex(@"([^\s]+)\s(.+)\sHTTP/1", RegexOptions.IgnoreCase);

                        Match match = rex.Match(url);

                        if (match.Success)
                        {
                            string fileurl = match.Groups[2].Value;

                            using (Image orig = Image.FromFile(georefimagepath + fileurl))
                            using (Image resi = ResizeImage(orig, new Size(640, 480)))
                            using (MemoryStream memstream = new MemoryStream())
                            {
                                resi.Save(memstream, System.Drawing.Imaging.ImageFormat.Jpeg);

                                memstream.Position = 0;
                                string header =
                                    "HTTP/1.1 200 OK\r\nServer: here\r\nKeep-Alive: timeout=15, max=100\r\nConnection: Keep-Alive\r\nContent-Type: image/jpg\r\nX-Pad: avoid browser bug\r\nContent-Length: " +
                                    memstream.Length + "\r\n\r\n";
                                byte[] temp = asciiEncoding.GetBytes(header);
                                stream.Write(temp, 0, temp.Length);

                                using (BinaryReader file = new BinaryReader(memstream))
                                {
                                    byte[] buffer = new byte[1024];
                                    while (file.BaseStream.Position < file.BaseStream.Length)
                                    {
                                        int leng = file.Read(buffer, 0, buffer.Length);

                                        stream.Write(buffer, 0, leng);
                                    }
                                }
                            }

                            goto again;

                            //stream.Close();
                        }
                        /////////////////////////////////////////////////////////////////
                        else
                        {
                            string header = "HTTP/1.1 404 not found\r\nContent-Type: image/jpg\r\n\r\n";
                            byte[] temp = asciiEncoding.GetBytes(header);
                            stream.Write(temp, 0, temp.Length);
                        }
                        stream.Close();
                    }
                    /////////////////////////////////////////////////////////////////
                    else if (url.ToLower().Contains("post /guide"))
                    {
                        Regex rex = new Regex(@"lat"":([\-\.0-9]+),""lon"":([\-\.0-9]+),""alt"":([\.0-9]+)",
                            RegexOptions.IgnoreCase);

                        Match match = rex.Match(head);

                        if (match.Success)
                        {
                            Locationwp gwp = new Locationwp()
                            {
                                lat = double.Parse(match.Groups[1].Value),
                                lng = double.Parse(match.Groups[2].Value),
                                alt = float.Parse(match.Groups[3].Value)
                            };
                            try
                            {
                                MainV2.comPort.setGuidedModeWP(gwp);
                            }
                            catch
                            {
                            }

                            string header = "HTTP/1.1 200 OK\r\n\r\nSent Guide Mode Wp";
                            byte[] temp = asciiEncoding.GetBytes(header);
                            stream.Write(temp, 0, temp.Length);
                        }
                        else
                        {
                            string header = "HTTP/1.1 200 OK\r\n\r\nFailed Guide Mode Wp";
                            byte[] temp = asciiEncoding.GetBytes(header);
                            stream.Write(temp, 0, temp.Length);
                        }
                        stream.Close();
                    }
                    /////////////////////////////////////////////////////////////////
                    else if (url.ToLower().Contains("/command_long"))
                    {
                        string header = "HTTP/1.1 404 not found\r\nContent-Type: image/jpg\r\n\r\n";
                        byte[] temp = asciiEncoding.GetBytes(header);
                        stream.Write(temp, 0, temp.Length);

                        stream.Close();
                    }
                    /////////////////////////////////////////////////////////////////
                    else if (url.ToLower().Contains("/rcoverride"))
                    {
                        string header = "HTTP/1.1 404 not found\r\nContent-Type: image/jpg\r\n\r\n";
                        byte[] temp = asciiEncoding.GetBytes(header);
                        stream.Write(temp, 0, temp.Length);

                        stream.Close();
                    }
                    /////////////////////////////////////////////////////////////////
                    else if (url.ToLower().Contains("/get_mission"))
                    {
                        string header = "HTTP/1.1 404 not found\r\nContent-Type: image/jpg\r\n\r\n";
                        byte[] temp = asciiEncoding.GetBytes(header);
                        stream.Write(temp, 0, temp.Length);

                        stream.Close();
                    }
                    /////////////////////////////////////////////////////////////////
                    else if (url.ToLower().Contains("/mavlink/"))
                    {
                        /*
        GET /mavlink/ATTITUDE+VFR_HUD+NAV_CONTROLLER_OUTPUT+META_WAYPOINT+GPS_RAW_INT+HEARTBEAT+META_LINKQUALITY+GPS_STATUS+STATUSTEXT+SYS_STATUS?_=1355828718540 HTTP/1.1
        Host: ubuntu:9999
        Connection: keep-alive
        X-Requested-With: XMLHttpRequest
        User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11
        Accept: 
        Referer: http://ubuntu:9999/index.html
        Accept-Encoding: gzip,deflate,sdch
        Accept-Language: en-GB,en-US;q=0.8,en;q=0.6
        Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3

        HTTP/1.1 200 OK
        Content-Type: application/json
        Content-Length: 2121
        Date: Thu, 29 Nov 2012 12:13:38 GMT
        Server: ubuntu

        {
        "VFR_HUD": {"msg": {"throttle": 0, "groundspeed": 0.0, "airspeed": 0.0, "climb": 0.0, "mavpackettype": "VFR_HUD", "alt": -0.47999998927116394, "heading": 108}, "index": 687, "time_usec": 0},
        "STATUSTEXT": {"msg": {"mavpackettype": "STATUSTEXT", "severity": 1, "text": "Initialising APM..."}, "index": 2, "time_usec": 0}, 
        "SYS_STATUS": {"msg": {"onboard_control_sensors_present": 4294966287, "load": 0, "battery_remaining": -1, "errors_count4": 0, "drop_rate_comm": 0, "errors_count2": 0, "errors_count3": 0, "errors_comm": 0, "current_battery": -1, "errors_count1": 0, "onboard_control_sensors_health": 4294966287, "mavpackettype": "SYS_STATUS", "onboard_control_sensors_enabled": 4294945807, "voltage_battery": 10080}, "index": 693, "time_usec": 0}, 
        "META_LINKQUALITY": {"msg": {"master_in": 11110, "mav_loss": 0, "mavpackettype": "META_LINKQUALITY", "master_out": 194, "packet_loss": 0.0}, "index": 194, "time_usec": 0},
        "ATTITUDE": {"msg": {"pitchspeed": -0.000976863200776279, "yaw": 1.8878594636917114, "rollspeed": -0.0030046366155147552, "time_boot_ms": 194676, "pitch": -0.09986469894647598, "mavpackettype": "ATTITUDE", "yawspeed": -0.0015030358918011189, "roll": -0.029391441494226456}, "index": 687, "time_usec": 0}, 
        "GPS_RAW_INT": {"msg": {"fix_type": 1, "cog": 0, "epv": 65535, "lon": 0, "time_usec": 0, "eph": 9999, "satellites_visible": 0, "lat": 0, "mavpackettype": "GPS_RAW_INT", "alt": 137000, "vel": 0}, "index": 687, "time_usec": 0}, 
        "HEARTBEAT": {"msg": {"custom_mode": 0, "system_status": 4, "base_mode": 81, "autopilot": 3, "mavpackettype": "HEARTBEAT", "type": 2, "mavlink_version": 3}, "index": 190, "time_usec": 0},
        "GPS_STATUS": {"msg": {"satellite_snr": "", "satellite_azimuth": "", "satellite_prn": "", "satellite_elevation": "", "satellites_visible": 0, "satellite_used": "", "mavpackettype": "GPS_STATUS"}, "index": 2, "time_usec": 0}, 
        "NAV_CONTROLLER_OUTPUT": {"msg": {"wp_dist": 0, "nav_pitch": 0.0, "target_bearing": 0, "nav_roll": 0.0, "aspd_error": 0.0, "alt_error": 0.0, "mavpackettype": "NAV_CONTROLLER_OUTPUT", "xtrack_error": 0.0, "nav_bearing": 0}, "index": 687, "time_usec": 0}}
                      */

                        JavaScriptSerializer serializer = new JavaScriptSerializer();

                        object[] data = new object[20];


                        Messagejson message = new Messagejson();

                        if (MainV2.comPort.MAV.getPacket((byte) MAVLink.MAVLINK_MSG_ID.ATTITUDE) != null)
                            message.ATTITUDE = new Message2()
                            {
                                index = 1,
                                msg =
                                    MainV2.comPort.MAV.getPacket((byte)MAVLink.MAVLINK_MSG_ID.ATTITUDE)
                                        .ToStructure<MAVLink.mavlink_attitude_t>()
                            };
                        if (MainV2.comPort.MAV.getPacket((byte)MAVLink.MAVLINK_MSG_ID.VFR_HUD) != null)
                            message.VFR_HUD = new Message2()
                            {
                                index = 1,
                                msg =
                                    MainV2.comPort.MAV.getPacket((byte)MAVLink.MAVLINK_MSG_ID.VFR_HUD)
                                        .ToStructure<MAVLink.mavlink_vfr_hud_t>()
                            };
                        if (MainV2.comPort.MAV.getPacket((byte)MAVLink.MAVLINK_MSG_ID.NAV_CONTROLLER_OUTPUT) != null)
                            message.NAV_CONTROLLER_OUTPUT = new Message2()
                            {
                                index = 1,
                                msg =
                                    MainV2.comPort.MAV.getPacket((byte)MAVLink.MAVLINK_MSG_ID.NAV_CONTROLLER_OUTPUT)
                                        .ToStructure<MAVLink.mavlink_nav_controller_output_t>()
                            };
                        if (MainV2.comPort.MAV.getPacket((byte)MAVLink.MAVLINK_MSG_ID.GPS_RAW_INT) != null)
                            message.GPS_RAW_INT = new Message2()
                            {
                                index = 1,
                                msg =
                                    MainV2.comPort.MAV.getPacket((byte)MAVLink.MAVLINK_MSG_ID.GPS_RAW_INT)
                                        .ToStructure<MAVLink.mavlink_gps_raw_int_t>()
                            };
                        if (MainV2.comPort.MAV.getPacket((byte) MAVLink.MAVLINK_MSG_ID.HEARTBEAT) != null)
                            message.HEARTBEAT = new Message2()
                            {
                                index = 1,
                                msg =
                                    MainV2.comPort.MAV.getPacket((byte) MAVLink.MAVLINK_MSG_ID.HEARTBEAT)
                                        .ToStructure<MAVLink.mavlink_heartbeat_t>()
                            };
                        if (MainV2.comPort.MAV.getPacket((byte) MAVLink.MAVLINK_MSG_ID.GPS_STATUS) != null)
                            message.GPS_STATUS = new Message2()
                            {
                                index = 1,
                                msg =
                                    MainV2.comPort.MAV.getPacket((byte) MAVLink.MAVLINK_MSG_ID.GPS_STATUS)
                                        .ToStructure<MAVLink.mavlink_gps_status_t>()
                            };
                        if (MainV2.comPort.MAV.getPacket((byte) MAVLink.MAVLINK_MSG_ID.STATUSTEXT) != null)
                            message.STATUSTEXT = new Message2()
                            {
                                index = 1,
                                msg =
                                    MainV2.comPort.MAV.getPacket((byte) MAVLink.MAVLINK_MSG_ID.STATUSTEXT)
                                        .ToStructure<MAVLink.mavlink_statustext_t>()
                            };
                        if (MainV2.comPort.MAV.getPacket((byte) MAVLink.MAVLINK_MSG_ID.SYS_STATUS) != null)
                            message.SYS_STATUS = new Message2()
                            {
                                index = 1,
                                msg =
                                    MainV2.comPort.MAV.getPacket((byte)MAVLink.MAVLINK_MSG_ID.SYS_STATUS)
                                        .ToStructure<MAVLink.mavlink_sys_status_t>()
                            };

                        message.META_LINKQUALITY =
                            message.SYS_STATUS =
                                new Message2()
                                {
                                    index = packetindex,
                                    time_usec = 0,
                                    msg =
                                        new META_LINKQUALITY()
                                        {
                                            master_in = (int) MainV2.comPort.MAV.packetsnotlost,
                                            mavpackettype = "META_LINKQUALITY",
                                            master_out = MainV2.comPort.packetcount,
                                            packet_loss = 100 - MainV2.comPort.MAV.cs.linkqualitygcs,
                                            mav_loss = 0
                                        }
                                };

                        packetindex++;

                        string output = serializer.Serialize(message);

                        string header = "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: " +
                                        output.Length + "\r\n\r\n";
                        byte[] temp = asciiEncoding.GetBytes(header);
                        stream.Write(temp, 0, temp.Length);

                        temp = asciiEncoding.GetBytes(output);
                        stream.Write(temp, 0, temp.Length);

                        goto again;

                        //stream.Close();
                    }
                    /////////////////////////////////////////////////////////////////
                    else if (url.ToLower().Contains("/mav/"))
                    {
                        //C:\Users\hog\Desktop\DIYDrones\mavelous\modules\lib\mavelous_web


                        Regex rex = new Regex(@"([^\s]+)\s(.+)\sHTTP/1", RegexOptions.IgnoreCase);

                        Match match = rex.Match(url);

                        if (match.Success)
                        {
                            string fileurl = match.Groups[2].Value;

                            fileurl = fileurl.Replace("/mav/", "");

                            if (fileurl == "" || fileurl == "/")
                                fileurl = "index.html";

                            string header = "HTTP/1.1 200 OK\r\n";
                            if (fileurl.Contains(".html"))
                                header += "Content-Type: text/html\r\n\r\n";
                            else if (fileurl.Contains(".js"))
                                header += "Content-Type: application/x-javascript\r\n\r\n";
                            else if (fileurl.Contains(".css"))
                                header += "Content-Type: text/css\r\n\r\n";
                            else
                                header += "Content-Type: text/plain\r\n\r\n";
                            byte[] temp = asciiEncoding.GetBytes(header);
                            stream.Write(temp, 0, temp.Length);


                            BinaryReader file =
                                new BinaryReader(File.Open(mavelous_web + fileurl, FileMode.Open, FileAccess.Read,
                                    FileShare.Read));
                            byte[] buffer = new byte[1024];
                            while (file.BaseStream.Position < file.BaseStream.Length)
                            {
                                int leng = file.Read(buffer, 0, buffer.Length);

                                stream.Write(buffer, 0, leng);
                            }
                            file.Close();
                            stream.Close();
                        }
                        /////////////////////////////////////////////////////////////////
                        else
                        {
                            string header = "HTTP/1.1 404 not found\r\nContent-Type: image/jpg\r\n\r\n";
                            byte[] temp = asciiEncoding.GetBytes(header);
                            stream.Write(temp, 0, temp.Length);

                            stream.Close();
                        }
                    }
                    /////////////////////////////////////////////////////////////////
                    else
                    {
                        Console.WriteLine(url);
                        string header = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n";
                        byte[] temp = asciiEncoding.GetBytes(header);
                        stream.Write(temp, 0, temp.Length);

                        string content = @"
                <a href=/mav/>Mavelous</a>
<a href=/mavlink/>Mavelous traffic</a>
<a href=/hud.jpg>Hud image</a>
<a href=/map.jpg>Map image </a>
<a href=/both.jpg>Map & hud image</a>
<a href=/hud.html>hud html5</a>
<a href=/network.kml>network kml</a>
<a href=/georefnetwork.kml>georef kml</a>

";
                        temp = asciiEncoding.GetBytes(content);
                        stream.Write(temp, 0, temp.Length);
                    }

                    stream.Close();
                    log.Info("Close http " + url);
                }
                catch (Exception ee)
                {
                    log.Error("Failed http ", ee);
                }
            }
        }
        public void generateParcour(List <List <Vector> > listOfRoutes, List <string> ListOfRouteNames, List <List <Vector> > listOfNBL, List <string> listOfNBLNames, bool hasMarkers, bool showForbiddenArea, bool isStandardOrder, double channelWidth, double altitude, bool hasRoundedCorners)
        {
            string[] styleNames = { @"PolygonAndLine", @"PolygonAndLineNoFill" };

            // Document document = new Document();
            KMLPolygonStyle.AddStylesForPolygon(document, styleNames);

            GeoData        gc = new GeoData();
            List <Feature> lstFeaturesPROHPolygon = new List <Feature>();
            List <Feature> lstFeaturesSP          = new List <Feature>();
            List <Feature> lstFeaturesFP          = new List <Feature>();
            List <Feature> lstFeaturesNBLine      = new List <Feature>();
            List <Feature> lstFeaturesChannel     = new List <Feature>();

            Folder folderGeneral = new Folder();

            folderGeneral.Name = "General";

            Folder folderTKOFLines = new Folder();

            folderTKOFLines.Name = "TakeOffLines";
            // add a description
            SharpKml.Dom.Description descr = new SharpKml.Dom.Description();
            descr.Text = "Add manually one or multiple take-off line(s) for your airfield<br/>into this folder for later use/import. Read more...<br/><b>Naming convention:</b>Take-off line names must start with the word <b>TKOF</b>.<br/><b>Examples:</b>TKOF_RWY21, TKOF_WEST";
            folderTKOFLines.Description = descr;
            folderGeneral.AddFeature(folderTKOFLines);

            Folder folderLiveTracking = new Folder();

            folderLiveTracking.Name = "LiveTracking";
            // folderLiveTracking.Description = "This folder can be used for LiveTracking. Andjust the PROH areas manually.</br> Then (using a text editor) set 'clampToGround' to 'relativeToGround'.</br>";

            List <Vector> lstOldRightBorder = new List <Vector>();

            for (int j = 0; j < listOfRoutes.Count(); j++)
            {
                List <Vector> routePoints     = listOfRoutes[j];
                List <Vector> lstOrigNBLine   = new List <Vector>();
                Vector        NBLPointOnRoute = new Vector();
                string        routeName       = ListOfRouteNames[j];
                Folder        folderBorders   = new Folder();
                folderBorders.Name = routeName + "_RouteBorders";

                // calculate headings and left/right borders
                List <double> lstHeadings       = gc.CalculateHeadings(routePoints);
                List <Vector> lstLeftBorder     = gc.CalculateCurvePoint(routePoints, lstHeadings, channelWidth, false, 1, hasRoundedCorners);
                List <Vector> lstRightBorder    = gc.CalculateCurvePoint(routePoints, lstHeadings, channelWidth, true, 1, hasRoundedCorners);
                List <Vector> lstRightBorderMod = lstRightBorder; // used in PROH area calcs
                List <Vector> lstChannel        = combineBorderVectorsForPolygon(lstLeftBorder, lstRightBorder);
                if (lstChannel.Count > 1)
                {  // remove duplicate point at the end
                    lstChannel.RemoveAt(lstChannel.Count - 1);
                }
                setAltitude(lstChannel, altitude);


                // shift start and end points of border inwards
                lstLeftBorder  = gc.BorderModification(lstLeftBorder, SHIFT_DIST);
                lstRightBorder = gc.BorderModification(lstRightBorder, SHIFT_DIST);

                // calculate the gate points for start and end point gate. Fixed width 0.6 NM
                // we will use later on only the first two/ last two points
                List <Vector> lstGateLeft  = gc.CalculateCurvePoint(routePoints, lstHeadings, GATE_WIDTH, false, 1, false);
                List <Vector> lstGateRight = gc.CalculateCurvePoint(routePoints, lstHeadings, GATE_WIDTH, true, 1, false);

                // SP line and FP line (use first/last points of left/right borders)
                List <Vector> lstSP, lstFP, lstNBLine;
                lstSP = new List <Vector>();
                lstSP.Add(new Vector(lstGateRight[0].Latitude, lstGateRight[0].Longitude, altitude));
                lstSP.Add(new Vector(lstGateLeft[0].Latitude, lstGateLeft[0].Longitude, altitude));
                lstFP = new List <Vector>();
                lstFP.Add(new Vector(lstGateRight[lstGateRight.Count - 1].Latitude, lstGateRight[lstGateRight.Count - 1].Longitude, altitude));
                lstFP.Add(new Vector(lstGateLeft[lstGateLeft.Count - 1].Latitude, lstGateLeft[lstGateLeft.Count - 1].Longitude, altitude));


                lstNBLine = new List <Vector>();
                // check if we have a NBLINE for this route
                if (listOfNBLNames.IndexOf(String.Format("NBLINE-{0}", routeName)) >= 0)
                {
                    int idx = listOfNBLNames.IndexOf(String.Format("NBLINE-{0}", routeName));
                    int idxRoutePointBeforeNBL = -1;
                    lstOrigNBLine   = listOfNBL[idx];
                    NBLPointOnRoute = gc.NBLPointOnRouteLine(routePoints, lstOrigNBLine, out idxRoutePointBeforeNBL);
                    if (idxRoutePointBeforeNBL > -1)
                    {
                        List <Vector> lstNBLSegm = new List <Vector>();
                        // create a short segment with the NBL point on the route line, and  the first route point after the NBL point
                        lstNBLSegm.Add(NBLPointOnRoute);
                        lstNBLSegm.Add(routePoints[idxRoutePointBeforeNBL + 1]);

                        // calculate borders
                        List <double> lstNBLHdg       = gc.CalculateHeadings(lstNBLSegm);
                        List <Vector> lstNBLGateLeft  = gc.CalculateCurvePoint(lstNBLSegm, lstNBLHdg, channelWidth, false, 1, false);
                        List <Vector> lstNBLGateRight = gc.CalculateCurvePoint(lstNBLSegm, lstNBLHdg, channelWidth, true, 1, false);
                        lstNBLine.Clear();
                        lstNBLine.Add(new Vector(lstNBLGateRight[0].Latitude, lstNBLGateRight[0].Longitude, altitude));
                        lstNBLine.Add(new Vector(lstNBLGateLeft[0].Latitude, lstNBLGateLeft[0].Longitude, altitude));
                    }
                }


                List <Vector> lstLeftBorderForbiddenArea  = new List <Vector>();
                List <Vector> lstRightBorderForbiddenArea = new List <Vector>();

                if (isStandardOrder)
                {
                    if (j == 0)
                    {
                        // calculate LeftBorder PROH for first route
                        List <Vector> lstLeftBorderPROH = gc.CalculateCurvePoint(routePoints, lstHeadings, channelWidth * 10, false, 1, false);
                        //TODO: add Gate Point as first/last point to lstLeftBorderPROH
                        lstLeftBorderPROH.Insert(0, lstGateLeft[0]);
                        lstLeftBorderPROH.Add(lstGateLeft[lstGateLeft.Count - 1]);
                        lstLeftBorderForbiddenArea = combineBorderVectorsForPolygon(lstLeftBorderPROH, lstLeftBorder);
                        setAltitude(lstLeftBorderForbiddenArea, altitude);

                        //TODO: add Gate Point as first/last point to lstRightBorderMod
                        lstRightBorderMod.Add(lstGateRight[0]);
                        lstRightBorderMod.Insert(0, lstGateRight[lstGateRight.Count - 1]);
                    }
                    else
                    {
                        // calculate LeftBorder PROH area from LeftBorder[j] and RightBorder[j-1]
                        lstOldRightBorder.Add(lstGateLeft[0]);
                        lstOldRightBorder.Insert(0, lstGateLeft[lstGateLeft.Count - 1]);
                        lstLeftBorderForbiddenArea = combineBorderVectorsForPolygon(lstOldRightBorder, lstLeftBorder);
                        setAltitude(lstLeftBorderForbiddenArea, altitude);
                    }

                    // for the last route, also calculate right border PROH
                    if (j == listOfRoutes.Count - 1)
                    {
                        List <Vector> lstRightBorderPROH = gc.CalculateCurvePoint(routePoints, lstHeadings, channelWidth * 10, true, 1, false);
                        //TODO: add Gate Point as first/last point to lstRightBorderPROH
                        lstRightBorderPROH.Insert(0, lstGateRight[0]);
                        lstRightBorderPROH.Add(lstGateRight[lstGateRight.Count - 1]);
                        lstRightBorderForbiddenArea = combineBorderVectorsForPolygon(lstRightBorderPROH, lstRightBorder);
                        setAltitude(lstRightBorderForbiddenArea, altitude);
                    }
                }
                else
                {   // not standard order, calculate right and left PROH areas for each channel
                    List <Vector> lstLeftBorderPROH  = gc.CalculateCurvePoint(routePoints, lstHeadings, channelWidth * 10, false, 1, false);
                    List <Vector> lstRightBorderPROH = gc.CalculateCurvePoint(routePoints, lstHeadings, channelWidth * 10, true, 1, false);
                    lstLeftBorderForbiddenArea  = combineBorderVectorsForPolygon(lstLeftBorderPROH, lstLeftBorder);
                    lstRightBorderForbiddenArea = combineBorderVectorsForPolygon(lstRightBorderPROH, lstRightBorder);
                    setAltitude(lstLeftBorderForbiddenArea, altitude);
                    setAltitude(lstRightBorderForbiddenArea, altitude);
                }

                lstOldRightBorder = lstRightBorderMod;

                #region Creation of KML objects

                var lineStrRoute       = new SharpKml.Dom.LineString();
                var lineStrRightBorder = new SharpKml.Dom.LineString();
                var lineStrLeftBorder  = new SharpKml.Dom.LineString();
                var lineStrSP          = new SharpKml.Dom.LineString();
                var lineStrFP          = new SharpKml.Dom.LineString();
                var lineStrNBLine      = new SharpKml.Dom.LineString();
                var lineStrOrigNBLine  = new SharpKml.Dom.LineString();
                var lineStrChannel     = new SharpKml.Dom.LineString();


                lineStrRoute.Coordinates       = new CoordinateCollection(routePoints);
                lineStrRoute.Tessellate        = true;
                lineStrRightBorder.Coordinates = new CoordinateCollection(lstRightBorder);
                lineStrLeftBorder.Coordinates  = new CoordinateCollection(lstLeftBorder);
                lineStrSP.Coordinates          = new CoordinateCollection(lstSP);
                lineStrFP.Coordinates          = new CoordinateCollection(lstFP);
                lineStrNBLine.Coordinates      = new CoordinateCollection(lstNBLine);
                lineStrOrigNBLine.Coordinates  = new CoordinateCollection(lstOrigNBLine);
                lineStrChannel.Coordinates     = new CoordinateCollection(lstChannel);

                var polygLeftBorderForbiddenArea  = makeSimplePolygon(lstLeftBorderForbiddenArea, AltitudeMode.ClampToGround);
                var polygRightBorderForbiddenArea = makeSimplePolygon(lstRightBorderForbiddenArea, AltitudeMode.ClampToGround);
                var polySP      = makeSimplePolygon(lineStrSP, AltitudeMode.RelativeToGround);
                var polyFP      = makeSimplePolygon(lineStrFP, AltitudeMode.RelativeToGround);
                var polyChannel = makeSimplePolygon(lineStrChannel, AltitudeMode.ClampToGround);
                var polyNBLine  = new Polygon();

                if (lstNBLine.Count > 0)
                {
                    polyNBLine = makeSimplePolygon(lineStrNBLine, AltitudeMode.RelativeToGround);
                }

                // Route itself
                var plm = new SharpKml.Dom.Placemark();
                plm = makeSimplePlacemark(lineStrRoute, routeName);
                folderGeneral.AddFeature(plm);

                plm = makeSimplePlacemark(polyChannel, "CHANNEL-" + routeName, styleNames[1]);
                lstFeaturesChannel.Add(plm);

                // original hand-made NBLine
                if (lstNBLine.Count > 0)
                {
                    plm = new SharpKml.Dom.Placemark();
                    plm = makeSimplePlacemark(lineStrOrigNBLine, "NBLINE-" + routeName + " (orig)");
                    folderGeneral.AddFeature(plm);
                }

                // Right border line
                plm = makeSimplePlacemark(lineStrRightBorder, routeName + "_RightBorder");
                folderBorders.AddFeature(plm);

                // Left border line
                plm = makeSimplePlacemark(lineStrLeftBorder, routeName + "_LeftBorder");
                folderBorders.AddFeature(plm);

                // SP line
                plm = makeSimplePlacemark(lineStrSP, "STARTPOINT-" + routeName);
                folderBorders.AddFeature(plm);

                // FP line
                plm = makeSimplePlacemark(lineStrFP, "ENDPOINT-" + routeName);
                folderBorders.AddFeature(plm);

                // calculated NB line
                if (lstNBLine.Count > 0)
                {
                    plm = makeSimplePlacemark(lineStrNBLine, "NBLINE-" + routeName);
                    folderBorders.AddFeature(plm);
                }

                plm = makeSimplePlacemark(polySP, "STARTPOINT-" + routeName, styleNames[0]);
                lstFeaturesSP.Add(plm);

                plm = makeSimplePlacemark(polyFP, "ENDPOINT-" + routeName, styleNames[0]);
                lstFeaturesFP.Add(plm);

                if (lstNBLine.Count > 0)
                {
                    plm = makeSimplePlacemark(polyNBLine, "NBLINE-" + routeName, styleNames[0]);
                    lstFeaturesNBLine.Add(plm);
                }

                folderGeneral.AddFeature(folderBorders);

                if (showForbiddenArea)
                {
                    //Folder folder = new Folder();
                    //folder.Name = "PROH-Areas " + routeName;

                    // add forbidden Area (Polygon area)
                    if (lstRightBorderForbiddenArea.Count > 0)
                    {
                        var placemarkPolyg = makeSimplePlacemark(polygRightBorderForbiddenArea, "PROH " + routeName + " Right", styleNames[0]);
                        lstFeaturesPROHPolygon.Add(placemarkPolyg);
                    }

                    if (lstLeftBorderForbiddenArea.Count > 0)
                    {
                        var placemarkPolyg = makeSimplePlacemark(polygLeftBorderForbiddenArea, "PROH " + routeName + " Left", styleNames[0]);
                        lstFeaturesPROHPolygon.Add(placemarkPolyg);
                    }
                }

                if (hasMarkers)
                {
                    // OPTIONAL: add markers if required for all route points
                    Folder folder = new Folder();
                    folder.Name = routeName + "_RouteMarkers";
                    for (int i = 0; i < routePoints.Count; i++)
                    {
                        Placemark          pm = new Placemark();
                        SharpKml.Dom.Point pt = new SharpKml.Dom.Point();
                        pt.Coordinate = new Vector(routePoints[i].Latitude, routePoints[i].Longitude);
                        pm.Geometry   = pt;
                        pm.Name       = String.Format("TP_{0}_{1}", i.ToString().PadLeft(2, '0'), routeName);
                        if (i == 0)
                        {
                            pm.Name = String.Format("SP_{0}", routeName);
                        }
                        if (i == routePoints.Count - 1)
                        {
                            pm.Name = String.Format("FP_{0}", routeName);
                        }
                        folder.AddFeature(pm);
                    }
                    if (lstNBLine.Count > 0)
                    {
                        Placemark          pm = new Placemark();
                        SharpKml.Dom.Point pt = new SharpKml.Dom.Point();
                        pt.Coordinate = new Vector(NBLPointOnRoute.Latitude, NBLPointOnRoute.Longitude);
                        pm.Geometry   = pt;
                        pm.Name       = String.Format("NBLINE_{0}", routeName);
                        folder.AddFeature(pm);
                    }
                    folderGeneral.AddFeature(folder);
                }

                #endregion
            }

            #region Create Kml document

            for (int i = 0; i < lstFeaturesPROHPolygon.Count; i++)
            {
                folderLiveTracking.AddFeature(lstFeaturesPROHPolygon[i].Clone());
            }
            for (int i = 0; i < lstFeaturesSP.Count; i++)
            {
                folderLiveTracking.AddFeature(lstFeaturesSP[i].Clone());
            }
            for (int i = 0; i < lstFeaturesFP.Count; i++)
            {
                folderLiveTracking.AddFeature(lstFeaturesFP[i].Clone());
            }
            for (int i = 0; i < lstFeaturesChannel.Count; i++)
            {
                folderLiveTracking.AddFeature(lstFeaturesChannel[i].Clone());
            }
            for (int i = 0; i < lstFeaturesNBLine.Count; i++)
            {
                folderLiveTracking.AddFeature(lstFeaturesNBLine[i].Clone());
            }

            document.AddFeature(folderGeneral);
            document.AddFeature(folderLiveTracking);
            #endregion
        }
Example #48
0
        protected void GenerateKml()
        {
            var id = Convert.ToInt32(Server.HtmlEncode(Request.QueryString["Code"]));
            var document = new Document();
            document.Id = "Document";
            document.Name = "Document";

            Description dsc = new Description();
            dsc.Text = @"<h1>Car's Tracking</h1> ";

            CoordinateCollection coordinates = new CoordinateCollection();

            DataTable dt = new DataTable();

            try
            {
                DataSet ds = FieldAreaViewMethof.getfieldAreaValue(id);
                dt = ds.Tables[0];

                string isreference = ds.Tables[0].Rows[0]["isReferencePoint"].ToString();
                if (isreference == "True")
                {
                    dt.Rows[0].Delete();
                }

                foreach (DataRow dr in dt.Rows)
                {
                    double lon = double.Parse(ParseDMS(dr["Longitude"].ToString()).ToString());
                    double lat = double.Parse(ParseDMS(dr["Latitude"].ToString()).ToString());
                    coordinates.Add(new Vector(lat, lon, 0));
                }

                OuterBoundary outerBoundary = new OuterBoundary();
                outerBoundary.LinearRing = new LinearRing();
                outerBoundary.LinearRing.Coordinates = coordinates;

                // Polygon Setting:
                Polygon polygon = new Polygon();
                polygon.Extrude = true;
                polygon.AltitudeMode = AltitudeMode.ClampToGround;
                polygon.OuterBoundary = outerBoundary;

                //Color Style Setting:
                byte byte_Color_R = 150, byte_Color_G = 150, byte_Color_B = 150, byte_Color_A = 100; //you may get your own color by other method
                var style = new SharpKml.Dom.Style();

                style.Polygon = new PolygonStyle();
                style.Polygon.ColorMode = SharpKml.Dom.ColorMode.Normal;
                style.Polygon.Color = new Color32(byte_Color_A, byte_Color_B, byte_Color_G, byte_Color_R);

                //Set the polygon and style to the Placemark:
                Placemark placemark = new Placemark();
                placemark.Name = "Kukrail";
                placemark.Geometry = polygon;
                placemark.AddStyle(style);

                //Finally to the document and save it
                document.AddFeature(placemark);

                var kml = new Kml();
                kml.Feature = document;

                KmlFile kmlFile = KmlFile.Create(kml, true);
                if (File.Exists(Server.MapPath("~") + "MAP.kml"))
                {
                    File.Delete(Server.MapPath("~") + "MAP.kml");
                }
                using (var stream = System.IO.File.OpenWrite(Server.MapPath("~") + "MAP.kml"))
                {
                    kmlFile.Save(stream);
                }

            }
            catch (Exception exc)
            {
                Response.Write(exc.Message);
            }
            finally
            {
            }
        }
Example #49
0
        private static Feature CreateFeature(int index, bool id)
        {
            Feature output;
            int type = index % 7;
            switch (type)
            {
                case 0:
                    output = new Placemark();
                    break;
                case 1:
                    output = new Folder();
                    break;
                case 2:
                    output = new Document();
                    break;
                case 3:
                    output = new NetworkLink();
                    break;
                case 4:
                    output = new GroundOverlay();
                    break;
                case 5:
                    output = new ScreenOverlay();
                    break;
                default:
                    output = new PhotoOverlay();
                    break;
            }

            if (id)
            {
                output.Id = "i" + index;
            }
            else
            {
                output.TargetId = "i" + index;
            }
            return output;
        }
Example #50
0
        private void CreateReportFiles(Dictionary<string, PictureInformation> listPhotosWithInfo, string dirWithImages, float offset)
        {
            // Write report files
            Document kml = new Document();

            // Clear Stations IDs
            JXL_StationIDs.Clear();

            using (StreamWriter swlogloccsv = new StreamWriter(dirWithImages + Path.DirectorySeparatorChar + "loglocation.csv")) 
            using (StreamWriter swlockml = new StreamWriter(dirWithImages + Path.DirectorySeparatorChar + "location.kml"))
            using (StreamWriter swloctxt = new StreamWriter(dirWithImages + Path.DirectorySeparatorChar + "location.txt"))
            using (StreamWriter swloctel = new StreamWriter(dirWithImages + Path.DirectorySeparatorChar + "location.tel"))
            using (XmlTextWriter swloctrim = new XmlTextWriter(dirWithImages + Path.DirectorySeparatorChar + "location.jxl", Encoding.ASCII))
            {
                swloctrim.Formatting = Formatting.Indented;
                swloctrim.WriteStartDocument(false);
                swloctrim.WriteStartElement("JOBFile");
                swloctrim.WriteAttributeString("jobName", "MPGeoRef");
                swloctrim.WriteAttributeString("product", "Gatewing");
                swloctrim.WriteAttributeString("productVersion", "1.0");
                swloctrim.WriteAttributeString("version", "5.6");
                // enviro
                swloctrim.WriteStartElement("Environment");
                swloctrim.WriteStartElement("CoordinateSystem");
                swloctrim.WriteElementString("SystemName", "Default");
                swloctrim.WriteElementString("ZoneName", "Default");
                swloctrim.WriteElementString("DatumName", "WGS 1984");
                swloctrim.WriteStartElement("Ellipsoid");
                swloctrim.WriteElementString("EarthRadius", "6378137");
                swloctrim.WriteElementString("Flattening", "0.00335281067183");
                swloctrim.WriteEndElement();
                swloctrim.WriteStartElement("Projection");
                swloctrim.WriteElementString("Type", "NoProjection");
                swloctrim.WriteElementString("Scale", "1");
                swloctrim.WriteElementString("GridOrientation", "IncreasingNorthEast");
                swloctrim.WriteElementString("SouthAzimuth", "false");
                swloctrim.WriteElementString("ApplySeaLevelCorrection", "true");
                swloctrim.WriteEndElement();
                swloctrim.WriteStartElement("LocalSite");
                swloctrim.WriteElementString("Type", "Grid");
                swloctrim.WriteElementString("ProjectLocationLatitude", "");
                swloctrim.WriteElementString("ProjectLocationLongitude", "");
                swloctrim.WriteElementString("ProjectLocationHeight", "");
                swloctrim.WriteEndElement();
                swloctrim.WriteStartElement("Datum");
                swloctrim.WriteElementString("Type", "ThreeParameter");
                swloctrim.WriteElementString("GridName", "WGS 1984");
                swloctrim.WriteElementString("Direction", "WGS84ToLocal");
                swloctrim.WriteElementString("EarthRadius", "6378137");
                swloctrim.WriteElementString("Flattening", "0.00335281067183");
                swloctrim.WriteElementString("TranslationX", "0");
                swloctrim.WriteElementString("TranslationY", "0");
                swloctrim.WriteElementString("TranslationZ", "0");
                swloctrim.WriteEndElement();
                swloctrim.WriteStartElement("HorizontalAdjustment");
                swloctrim.WriteElementString("Type", "NoAdjustment");
                swloctrim.WriteEndElement();
                swloctrim.WriteStartElement("VerticalAdjustment");
                swloctrim.WriteElementString("Type", "NoAdjustment");
                swloctrim.WriteEndElement();
                swloctrim.WriteStartElement("CombinedScaleFactor");
                swloctrim.WriteStartElement("Location");
                swloctrim.WriteElementString("Latitude", "");
                swloctrim.WriteElementString("Longitude", "");
                swloctrim.WriteElementString("Height", "");
                swloctrim.WriteEndElement();
                swloctrim.WriteElementString("Scale", "");
                swloctrim.WriteEndElement();

                swloctrim.WriteEndElement();
                swloctrim.WriteEndElement();

                // fieldbook
                swloctrim.WriteStartElement("FieldBook");

                swloctrim.WriteRaw(@"   <CameraDesignRecord ID='00000001'>
                                      <Type>GoPro   </Type>
                                      <HeightPixels>2400</HeightPixels>
                                      <WidthPixels>3200</WidthPixels>
                                      <PixelSize>0.0000022</PixelSize>
                                      <LensModel>Rectilinear</LensModel>
                                      <NominalFocalLength>0.002</NominalFocalLength>
                                    </CameraDesignRecord>
                                    <CameraRecord2 ID='00000002'>
                                      <CameraDesignID>00000001</CameraDesignID>
                                      <CameraPosition>01</CameraPosition>
                                      <Optics>
                                        <IdealAngularMagnification>1.0</IdealAngularMagnification>
                                        <AngleSymmetricDistortion>
                                          <Order3>-0.35</Order3>
                                          <Order5>0.15</Order5>
                                          <Order7>-0.033</Order7>
                                          <Order9> 0</Order9>
                                        </AngleSymmetricDistortion>
                                        <AngleDecenteringDistortion>
                                          <Column>0</Column>
                                          <Row>0</Row>
                                        </AngleDecenteringDistortion>
                                      </Optics>
                                      <Geometry>
                                        <PerspectiveCenterPixels>
                                          <PrincipalPointColumn>-1615.5</PrincipalPointColumn>
                                          <PrincipalPointRow>-1187.5</PrincipalPointRow>
                                          <PrincipalDistance>-2102</PrincipalDistance>
                                        </PerspectiveCenterPixels>
                                        <VectorOffset>
                                          <X>0</X>
                                          <Y>0</Y>
                                          <Z>0</Z>
                                        </VectorOffset>
                                        <BiVectorAngle>
                                          <XX>0</XX>
                                          <YY>0</YY>
                                          <ZZ>-1.5707963268</ZZ>
                                        </BiVectorAngle>
                                      </Geometry>
                                    </CameraRecord2>");

                // 2mm fl
                // res 2400 * 3200 = 7,680,000
                // sensor size = 1/2.5" - 5.70 × 4.28 mm
                // 2.2 μm
                // fl in pixels = fl in mm * res / sensor size

                swloctrim.WriteStartElement("PhotoInstrumentRecord");
                swloctrim.WriteAttributeString("ID", "0000000E");
                swloctrim.WriteElementString("Type", "Aerial");
                swloctrim.WriteElementString("Model", "X100");
                swloctrim.WriteElementString("Serial", "000-000");
                swloctrim.WriteElementString("FirmwareVersion", "v0.0");
                swloctrim.WriteElementString("UserDefinedName", "Prototype");
                swloctrim.WriteEndElement();

                swloctrim.WriteStartElement("AtmosphereRecord");
                swloctrim.WriteAttributeString("ID", "0000000F");
                swloctrim.WriteElementString("Pressure", "");
                swloctrim.WriteElementString("Temperature", "");
                swloctrim.WriteElementString("PPM", "");
                swloctrim.WriteElementString("ApplyEarthCurvatureCorrection", "false");
                swloctrim.WriteElementString("ApplyRefractionCorrection", "false");
                swloctrim.WriteElementString("RefractionCoefficient", "0");
                swloctrim.WriteElementString("PressureInputMethod", "ReadFromInstrument");
                swloctrim.WriteEndElement();

                swloctel.WriteLine("version=1");

                swloctel.WriteLine("#seconds offset - " + offset);
                swloctel.WriteLine("#longitude and latitude - in degrees");
                swloctel.WriteLine("#name	utc	longitude	latitude	height");

                swloctxt.WriteLine("#name longitude/X latitude/Y height/Z yaw pitch roll");

                TXT_outputlog.AppendText("Start Processing\n");

                // Dont know why but it was 10 in the past so let it be. Used to generate jxl file simulating x100 from trimble
                int lastRecordN = JXL_ID_OFFSET;

                // path
                CoordinateCollection coords = new CoordinateCollection();

                foreach (var item in vehicleLocations.Values)
                {
                    coords.Add(new SharpKml.Base.Vector(item.Lat, item.Lon, item.AltAMSL));
                }

                var ls = new LineString() { Coordinates = coords, AltitudeMode = AltitudeMode.Absolute };

                SharpKml.Dom.Placemark pm = new SharpKml.Dom.Placemark() { Geometry = ls, Name = "path" };

                kml.AddFeature(pm);


                foreach (PictureInformation picInfo in listPhotosWithInfo.Values)
                {
                    string filename = Path.GetFileName(picInfo.Path);
                    string filenameWithoutExt = Path.GetFileNameWithoutExtension(picInfo.Path);

                    SharpKml.Dom.Timestamp tstamp = new SharpKml.Dom.Timestamp();

                    tstamp.When = picInfo.Time;

                    kml.AddFeature(

                        new Placemark()
                        {
                            Time = tstamp,
                            Visibility = true,
                            Name = filenameWithoutExt,
                            Geometry = new SharpKml.Dom.Point()
                            {
                                Coordinate = new Vector(picInfo.Lat, picInfo.Lon, picInfo.AltAMSL),
                                 AltitudeMode = AltitudeMode.Absolute
                            },
                            Description = new Description()
                            {
                                Text = "<table><tr><td><img src=\"" + filename.ToLower() + "\" width=500 /></td></tr></table>"
                            },
                            StyleSelector = new Style()
                            {
                                Balloon = new BalloonStyle() { Text = "$[name]<br>$[description]" }
                            }
                        }
                    );

                    double lat = picInfo.Lat;
                    double lng = picInfo.Lon;
                    double alpha = picInfo.Yaw + (double)num_camerarotation.Value;;

                    RectangleF rect = getboundingbox(lat, lng, alpha, (double)num_hfov.Value, (double)num_vfov.Value);

                    Console.WriteLine(rect);

                    //http://en.wikipedia.org/wiki/World_file
                    /* using (StreamWriter swjpw = new StreamWriter(dirWithImages + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(filename) + ".jgw"))
                        {
                            swjpw.WriteLine((rect.Height / 2448.0).ToString("0.00000000000000000"));
                            swjpw.WriteLine((0).ToString("0.00000000000000000")); // 
                            swjpw.WriteLine((0).ToString("0.00000000000000000")); //
                            swjpw.WriteLine((rect.Width / -3264.0).ToString("0.00000000000000000")); // distance per pixel
                            swjpw.WriteLine((rect.Left).ToString("0.00000000000000000"));
                            swjpw.WriteLine((rect.Top).ToString("0.00000000000000000"));

                            swjpw.Close();
                        }*/
                    
                    kml.AddFeature(
                        new GroundOverlay()
                        {
                            Name = filenameWithoutExt,
                            Visibility = false,
                            Time = tstamp,
                            AltitudeMode = AltitudeMode.ClampToGround,
                            Bounds = new LatLonBox()
                            {
                                Rotation = -alpha % 360,
                                North = rect.Bottom,
                                East = rect.Right,
                                West = rect.Left,
                                South = rect.Top,
                            },
                            Icon = new SharpKml.Dom.Icon()
                            {
                                Href = new Uri(filename.ToLower(), UriKind.Relative),
                            },
                        }
                    );

                    swloctxt.WriteLine(filename + " " + picInfo.Lat + " " + picInfo.Lon + " " + picInfo.getAltitude(useAMSLAlt) + " " + picInfo.Yaw + " " + picInfo.Pitch + " " + picInfo.Roll);


                    swloctel.WriteLine(filename + "\t" + picInfo.Time.ToString("yyyy:MM:dd HH:mm:ss") + "\t" + picInfo.Lon + "\t" + picInfo.Lat + "\t" + picInfo.getAltitude(useAMSLAlt));
                    swloctel.Flush();
                    swloctxt.Flush();

                    lastRecordN = GenPhotoStationRecord(swloctrim, picInfo.Path, picInfo.Lat, picInfo.Lon, picInfo.getAltitude(useAMSLAlt), 0, 0, picInfo.Yaw, picInfo.Width, picInfo.Height, lastRecordN);

                    log.InfoFormat(filename + " " + picInfo.Lon + " " + picInfo.Lat + " " + picInfo.getAltitude(useAMSLAlt) + "           ");
                }

                Serializer serializer = new Serializer();
                serializer.Serialize(kml);
                swlockml.Write(serializer.Xml);

                Utilities.httpserver.georefkml = serializer.Xml;
                Utilities.httpserver.georefimagepath = dirWithImages + Path.DirectorySeparatorChar;

                writeGPX(dirWithImages + Path.DirectorySeparatorChar + "location.gpx", listPhotosWithInfo);

                // flightmission
                GenFlightMission(swloctrim, lastRecordN);

                swloctrim.WriteEndElement(); // fieldbook
                swloctrim.WriteEndElement(); // job
                swloctrim.WriteEndDocument();

                TXT_outputlog.AppendText("Done \n\n");

            }
        }
Example #51
-1
        private void addReference(Placemark placemark, SharpKml.Dom.Point point, DbGeography coordinates)
        {
            LANDMARK landmark = new LANDMARK();
            LANDMARK_KNOWN_AS knowAsLandmark;

            knowAsLandmark = new LANDMARK_KNOWN_AS();

            knowAsLandmark.Known_As_Description = placemark.Name;
            landmark.Landmark_Coordinates = coordinates;
            knowAsLandmark.LANDMARK = landmark;
            knowAsLandmark.Known_As_ID = count = count + 1;

            DBLandmarkKnownAs db = new DBLandmarkKnownAs(context);
            db.Add(knowAsLandmark);

            if (placemark.Description != null)
            {
                string[] description = placemark.Description.Text.Split(';');

                for (int i = 0; i < description.Count(); i++)
                {
                    knowAsLandmark = new LANDMARK_KNOWN_AS();

                    knowAsLandmark.Known_As_Description = description[i];
                    landmark.Landmark_Coordinates = coordinates;
                    knowAsLandmark.Known_As_ID = count = count + 1;

                    knowAsLandmark.LANDMARK = landmark;

                    db = new DBLandmarkKnownAs(context);
                    db.Add(knowAsLandmark);
                }
            }
        }