Beispiel #1
11
        public string Write(Guid listGuid)
        {
            string kml = string.Empty;
            Serializer serializer = new Serializer();
            Kml _kml = new Kml();
            Folder folder = new Folder();
            UseWeb(spWeb =>
            {
                SPList list = spWeb.Lists.GetList(listGuid, true);
                SPField field = list.GetGeoField();
                if (field != null)
                {

                    foreach (SPListItem item in list.Items)
                    {
                        string wkt = item[field.Id] as string;
                        SimpleWKTReader wktReader = new SimpleWKTReader();
                        var simpleGeometry = wktReader.Parse(wkt);

                        if (simpleGeometry.GeometryType == GeometryTypes.Point)
                        {
                            var _point = (OpenSMIL.Server.SimpleFeature.GeomtryTypes.Point)simpleGeometry;
                            SharpKml.Dom.Point point = new SharpKml.Dom.Point();
                            point.Coordinate = new Vector(_point.Lat, _point.Lon);

                            Placemark placemark = CreatePlaceMark(item.Title, point);
                            folder.AddFeature(placemark);
                        }
                        else if (simpleGeometry.GeometryType == GeometryTypes.LineString)
                        {
                            var _lineString = (OpenSMIL.Server.SimpleFeature.GeomtryTypes.LineString)simpleGeometry;
                            SharpKml.Dom.LineString line = new SharpKml.Dom.LineString();
                            line.Coordinates = CreateCoordinateCollection(_lineString.Points);
                            Placemark placeMark = CreatePlaceMark(item.Title, line);
                            folder.AddFeature(placeMark);

                        }
                        else if (simpleGeometry.GeometryType == GeometryTypes.Polygon)
                        {
                            var _polygon = (OpenSMIL.Server.SimpleFeature.GeomtryTypes.Polygon)simpleGeometry;
                            OuterBoundary outerBoundary = new OuterBoundary();
                            outerBoundary.LinearRing = new LinearRing();
                            outerBoundary.LinearRing.Coordinates = CreateCoordinateCollection(_polygon.Points);

                            SharpKml.Dom.Polygon polygon = new SharpKml.Dom.Polygon();
                            polygon.OuterBoundary = outerBoundary;
                            polygon.Extrude = true;

                            Placemark placeMark = CreatePlaceMark(item.Title, polygon);
                            folder.AddFeature(placeMark);
                        }

                    }
                    _kml.Feature = folder;
                }
            });
            serializer.Serialize(_kml);
            return serializer.Xml;
        }
Beispiel #2
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();
        }
Beispiel #3
0
        private async Task <Placemark> GetUnit(RenderEntry data)
        {
            if (!data.Entry.Where.Latitude.HasValue || !data.Entry.Where.Longtitude.HasValue)
            {
                return(null);
            }

            var latitude   = data.Entry.Where.Latitude.Value;
            var longtitude = data.Entry.Where.Longtitude.Value;

            var point = new SharpKml.Dom.Point
            {
                Coordinate = new SharpKml.Base.Vector(latitude, longtitude),
            };


            var placemark = new Placemark
            {
                Geometry    = point,
                Name        = data.Entry.ToString() + " Location",
                Time        = GetTimespan(data.Entry.When),
                Description = await GetDescription(data),
                StyleUrl    = GetStyle("location", 1.0, data.Color)
            };

            return(placemark);
        }
        private void ProcessPointGeometry(Point f)
        {
            var coords = new Coordinate(f.Coordinate.Longitude, f.Coordinate.Latitude);

            var pGeom = _geometryFactory.CreatePoint(coords);

            AddGeometryToCollection(f.GetParent <Placemark>(), pGeom);
        }
Beispiel #5
0
        public string Write(Guid listGuid)
        {
            string     kml        = string.Empty;
            Serializer serializer = new Serializer();
            Kml        _kml       = new Kml();
            Folder     folder     = new Folder();

            UseWeb(spWeb =>
            {
                SPList list   = spWeb.Lists.GetList(listGuid, true);
                SPField field = list.GetGeoField();
                if (field != null)
                {
                    foreach (SPListItem item in list.Items)
                    {
                        string wkt = item[field.Id] as string;
                        SimpleWKTReader wktReader = new SimpleWKTReader();
                        var simpleGeometry        = wktReader.Parse(wkt);

                        if (simpleGeometry.GeometryType == GeometryTypes.Point)
                        {
                            var _point = (OpenSMIL.Server.SimpleFeature.GeomtryTypes.Point)simpleGeometry;
                            SharpKml.Dom.Point point = new SharpKml.Dom.Point();
                            point.Coordinate         = new Vector(_point.Lat, _point.Lon);

                            Placemark placemark = CreatePlaceMark(item.Title, point);
                            folder.AddFeature(placemark);
                        }
                        else if (simpleGeometry.GeometryType == GeometryTypes.LineString)
                        {
                            var _lineString = (OpenSMIL.Server.SimpleFeature.GeomtryTypes.LineString)simpleGeometry;
                            SharpKml.Dom.LineString line = new SharpKml.Dom.LineString();
                            line.Coordinates             = CreateCoordinateCollection(_lineString.Points);
                            Placemark placeMark          = CreatePlaceMark(item.Title, line);
                            folder.AddFeature(placeMark);
                        }
                        else if (simpleGeometry.GeometryType == GeometryTypes.Polygon)
                        {
                            var _polygon = (OpenSMIL.Server.SimpleFeature.GeomtryTypes.Polygon)simpleGeometry;
                            OuterBoundary outerBoundary          = new OuterBoundary();
                            outerBoundary.LinearRing             = new LinearRing();
                            outerBoundary.LinearRing.Coordinates = CreateCoordinateCollection(_polygon.Points);

                            SharpKml.Dom.Polygon polygon = new SharpKml.Dom.Polygon();
                            polygon.OuterBoundary        = outerBoundary;
                            polygon.Extrude = true;

                            Placemark placeMark = CreatePlaceMark(item.Title, polygon);
                            folder.AddFeature(placeMark);
                        }
                    }
                    _kml.Feature = folder;
                }
            });
            serializer.Serialize(_kml);
            return(serializer.Xml);
        }
Beispiel #6
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);
        }
Beispiel #7
0
        [TestCase(-44.93733888888889, 169.81687222222223)]  // bayswater

        public void Should_NotFind_Intersection(double lat, double lng)
        {
            SharpKml.Dom.Point point = new SharpKml.Dom.Point()
            {
                Coordinate = new SharpKml.Base.Vector(lat, lng)
            };

            DocumentData data      = new DocumentData(@"C:\Development\KML\KML.UnitTests\National Territories v2.0.kml");
            Placemark    placemark = data.Intersects(point);

            Assert.IsNull(placemark);
        }
Beispiel #8
0
        [TestCase(-38.15322222222222, 145.31143611111114)] // Melbourne, Casey

        public void FindIntersection(double lat, double lng)
        {
            SharpKml.Dom.Point point = new SharpKml.Dom.Point()
            {
                Coordinate = new SharpKml.Base.Vector(lat, lng)
            };

            DocumentData data      = new DocumentData(@"C:\Development\KML\KML.UnitTests\National Territories v2.0.kml");
            Placemark    placemark = data.Intersects(point);

            Assert.IsNotNull(placemark);
            Console.WriteLine($"town {placemark.Name}");
        }
        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));
        }
 private static void FillPlacemarkWithGeometry(ref KmlPlaceMark placeMark, ref SharpKml.Dom.Geometry geo)
 {
     if (geo is SharpKml.Dom.Polygon)
     {
         SharpKml.Dom.Polygon polygon = geo as SharpKml.Dom.Polygon;
         if (polygon.OuterBoundary != null)
         {
             placeMark.Geometry = new GMapCommonType.Polygon(CoordinatesToPoints(polygon.OuterBoundary.LinearRing.Coordinates));
         }
     }
     if (geo is SharpKml.Dom.Point)
     {
         SharpKml.Dom.Point point = geo as SharpKml.Dom.Point;
         placeMark.Geometry = new Point2D(point.Coordinate.Longitude, point.Coordinate.Latitude);
     }
     if (geo is SharpKml.Dom.LineString)
     {
         SharpKml.Dom.LineString str = geo as SharpKml.Dom.LineString;
         placeMark.Geometry = new Polyline(CoordinatesToPoints(str.Coordinates));
     }
 }
Beispiel #11
0
        public Point GetPoint(Placemark placemark)
        {
            Point p = new Point {
                Title       = placemark.Name,
                Description = (placemark.Description != null) ? placemark.Description.Text : _documentDescription
            };

            KmlPoint point = placemark.Flatten().OfType <KmlPoint>().FirstOrDefault();

            if (point != null)
            {
                p.Position = new BasicGeoposition()
                {
                    Longitude = point.Coordinate.Longitude,
                    Latitude  = point.Coordinate.Latitude,
                    Altitude  = point.Coordinate.Altitude ?? 0d
                };

                return(p);
            }

            return(null);
        }
Beispiel #12
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);
            }
        }
Beispiel #13
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);
            }
        }
        public async Task <ResponseMessage> ExportDesign(string designId)
        {
            try
            {
                var project = await _designService.GetDesign(designId);

                string projectPath = string.Empty;

                if (project.BluePrint != null)
                {
                    List <Cable>         cables         = new List <Cable>();
                    List <MicroDuct>     microduct      = new List <MicroDuct>();
                    List <Chamber>       chambers       = new List <Chamber>();
                    List <ODF>           oDFs           = new List <ODF>();
                    List <Duct>          ducts          = new List <Duct>();
                    List <Pole>          poles          = new List <Pole>();
                    List <Splitter>      splitters      = new List <Splitter>();
                    List <SpliceClosure> spliceClosures = new List <SpliceClosure>();
                    List <FAT>           fat            = new List <FAT>();
                    List <FDT>           fdt            = new List <FDT>();


                    if (project.BluePrint.Children != null && project.BluePrint.Children.Count > 0)
                    {
                        ExtractNetwork(project.BluePrint.Children, cables, chambers, oDFs, ducts, microduct, poles, spliceClosures, splitters, fat, fdt);
                    }

                    if (cables.Count > 0 || chambers.Count > 0 || oDFs.Count > 0 || ducts.Count > 0 || poles.Count > 0 || splitters.Count > 0 || spliceClosures.Count > 0)
                    {
                        var uploadFolder = "\\Uploads\\" + LoginUser.Id + "\\" + System.Guid.NewGuid().ToString();

                        var uploadPath = _hostingEnvironment.ContentRootPath + uploadFolder;

                        Directory.CreateDirectory(uploadPath);


                        projectPath = Path.Combine(uploadPath, "DesignExport.kml");


                        Kml                kml       = new Kml();
                        Placemark          placemark = new Placemark();
                        SharpKml.Dom.Point point;

                        SharpKml.Dom.Document document1 = new SharpKml.Dom.Document();
                        var style = new Style();

                        foreach (var chamber in chambers)
                        {
                            placemark              = new Placemark();
                            placemark.Name         = chamber.EntityType;
                            placemark.ExtendedData = new ExtendedData();

                            point = new SharpKml.Dom.Point();

                            point.Coordinate   = new SharpKml.Base.Vector(Convert.ToDouble(chamber.Geometry.coordinates[1]), Convert.ToDouble(chamber.Geometry.coordinates[0]));
                            placemark.Geometry = point;

                            placemark.ExtendedData.AddData(new Data
                            {
                                Name  = "Code",
                                Value = chamber.Code
                            });
                            placemark.ExtendedData.AddData(new Data
                            {
                                Name  = "ConstructionStage",
                                Value = chamber.ConstructionStage
                            });
                            placemark.ExtendedData.AddData(new Data
                            {
                                Name  = "ActivationStage",
                                Value = chamber.ActivationStage
                            });
                            placemark.ExtendedData.AddData(new Data
                            {
                                Name  = "Accessibility",
                                Value = chamber.Accessibility
                            });
                            placemark.ExtendedData.AddData(new Data
                            {
                                Name  = "HierarchyType",
                                Value = chamber.HierarchyType
                            });

                            document1.AddFeature(placemark);
                        }

                        foreach (var chamber in oDFs)
                        {
                            placemark              = new Placemark();
                            placemark.Name         = chamber.EntityType;
                            placemark.ExtendedData = new ExtendedData();

                            point = new SharpKml.Dom.Point();

                            point.Coordinate   = new SharpKml.Base.Vector(Convert.ToDouble(chamber.Geometry.coordinates[1]), Convert.ToDouble(chamber.Geometry.coordinates[0]));
                            placemark.Geometry = point;

                            placemark.ExtendedData.AddData(new Data
                            {
                                Name  = "Code",
                                Value = chamber.Code
                            });
                            placemark.ExtendedData.AddData(new Data
                            {
                                Name  = "ConstructionStage",
                                Value = chamber.ConstructionStage
                            });
                            placemark.ExtendedData.AddData(new Data
                            {
                                Name  = "ActivationStage",
                                Value = chamber.ActivationStage
                            });
                            placemark.ExtendedData.AddData(new Data
                            {
                                Name  = "Accessibility",
                                Value = chamber.Accessibility
                            });
                            placemark.ExtendedData.AddData(new Data
                            {
                                Name  = "HierarchyType",
                                Value = chamber.HierarchyType
                            });

                            document1.AddFeature(placemark);
                        }
                        foreach (var chamber in poles)
                        {
                            placemark              = new Placemark();
                            placemark.Name         = chamber.EntityType;
                            placemark.ExtendedData = new ExtendedData();

                            point = new SharpKml.Dom.Point();

                            point.Coordinate   = new SharpKml.Base.Vector(Convert.ToDouble(chamber.Geometry.coordinates[1]), Convert.ToDouble(chamber.Geometry.coordinates[0]));
                            placemark.Geometry = point;

                            placemark.ExtendedData.AddData(new Data
                            {
                                Name  = "Code",
                                Value = chamber.Code
                            });
                            placemark.ExtendedData.AddData(new Data
                            {
                                Name  = "ConstructionStage",
                                Value = chamber.ConstructionStage
                            });
                            placemark.ExtendedData.AddData(new Data
                            {
                                Name  = "ActivationStage",
                                Value = chamber.ActivationStage
                            });
                            placemark.ExtendedData.AddData(new Data
                            {
                                Name  = "Accessibility",
                                Value = chamber.Accessibility
                            });
                            placemark.ExtendedData.AddData(new Data
                            {
                                Name  = "HierarchyType",
                                Value = chamber.HierarchyType
                            });

                            document1.AddFeature(placemark);
                        }
                        foreach (var chamber in splitters)
                        {
                            placemark              = new Placemark();
                            placemark.Name         = chamber.EntityType;
                            placemark.ExtendedData = new ExtendedData();

                            point = new SharpKml.Dom.Point();

                            point.Coordinate   = new SharpKml.Base.Vector(Convert.ToDouble(chamber.Geometry.coordinates[1]), Convert.ToDouble(chamber.Geometry.coordinates[0]));
                            placemark.Geometry = point;

                            placemark.ExtendedData.AddData(new Data
                            {
                                Name  = "Code",
                                Value = chamber.Code
                            });
                            placemark.ExtendedData.AddData(new Data
                            {
                                Name  = "ConstructionStage",
                                Value = chamber.ConstructionStage
                            });
                            placemark.ExtendedData.AddData(new Data
                            {
                                Name  = "ActivationStage",
                                Value = chamber.ActivationStage
                            });
                            placemark.ExtendedData.AddData(new Data
                            {
                                Name  = "Accessibility",
                                Value = chamber.Accessibility
                            });
                            placemark.ExtendedData.AddData(new Data
                            {
                                Name  = "HierarchyType",
                                Value = chamber.HierarchyType
                            });

                            document1.AddFeature(placemark);
                        }
                        foreach (var chamber in spliceClosures)
                        {
                            placemark              = new Placemark();
                            placemark.Name         = chamber.EntityType;
                            placemark.ExtendedData = new ExtendedData();

                            point = new SharpKml.Dom.Point();

                            point.Coordinate   = new SharpKml.Base.Vector(Convert.ToDouble(chamber.Geometry.coordinates[1]), Convert.ToDouble(chamber.Geometry.coordinates[0]));
                            placemark.Geometry = point;

                            placemark.ExtendedData.AddData(new Data
                            {
                                Name  = "Code",
                                Value = chamber.Code
                            });
                            placemark.ExtendedData.AddData(new Data
                            {
                                Name  = "ConstructionStage",
                                Value = chamber.ConstructionStage
                            });
                            placemark.ExtendedData.AddData(new Data
                            {
                                Name  = "ActivationStage",
                                Value = chamber.ActivationStage
                            });
                            placemark.ExtendedData.AddData(new Data
                            {
                                Name  = "Accessibility",
                                Value = chamber.Accessibility
                            });
                            placemark.ExtendedData.AddData(new Data
                            {
                                Name  = "HierarchyType",
                                Value = chamber.HierarchyType
                            });

                            document1.AddFeature(placemark);
                        }

                        foreach (var chamber in cables)
                        {
                            placemark              = new Placemark();
                            placemark.Name         = chamber.EntityType;
                            placemark.ExtendedData = new ExtendedData();

                            point = new SharpKml.Dom.Point();

                            SharpKml.Dom.LineString linestring = new SharpKml.Dom.LineString();

                            CoordinateCollection coordinates = new CoordinateCollection();

                            foreach (var coordinate in chamber.Geometry.coordinates)
                            {
                                coordinates.Add(new Vector(coordinate[1], coordinate[0]));
                            }
                            linestring.Coordinates = coordinates;
                            placemark.Geometry     = linestring;

                            placemark.ExtendedData = new ExtendedData();

                            placemark.ExtendedData.AddData(new Data
                            {
                                Name  = "Code",
                                Value = chamber.Code
                            });
                            placemark.ExtendedData.AddData(new Data
                            {
                                Name  = "ALocation",
                                Value = chamber.ALocation
                            });
                            placemark.ExtendedData.AddData(new Data
                            {
                                Name  = "BLocation",
                                Value = chamber.BLocation
                            });
                            if (chamber.IsUnderground.HasValue)
                            {
                                placemark.ExtendedData.AddData(new Data
                                {
                                    Name  = "IsUnderground",
                                    Value = chamber.IsUnderground.ToString()
                                });
                            }

                            placemark.ExtendedData.AddData(new Data
                            {
                                Name  = "ConstructionStage",
                                Value = chamber.ConstructionStage
                            });
                            placemark.ExtendedData.AddData(new Data
                            {
                                Name  = "ActivationStage",
                                Value = chamber.ActivationStage
                            });
                            placemark.ExtendedData.AddData(new Data
                            {
                                Name  = "Accessibility",
                                Value = chamber.Accessibility
                            });
                            placemark.ExtendedData.AddData(new Data
                            {
                                Name  = "HierarchyType",
                                Value = chamber.HierarchyType
                            });

                            document1.AddFeature(placemark);
                        }

                        foreach (var chamber in ducts)
                        {
                            placemark              = new Placemark();
                            placemark.Name         = chamber.EntityType;
                            placemark.ExtendedData = new ExtendedData();

                            point = new SharpKml.Dom.Point();

                            SharpKml.Dom.LineString linestring = new SharpKml.Dom.LineString();

                            CoordinateCollection coordinates = new CoordinateCollection();

                            foreach (var coordinate in chamber.Geometry.coordinates)
                            {
                                coordinates.Add(new Vector(coordinate[1], coordinate[0]));
                            }
                            linestring.Coordinates = coordinates;
                            placemark.Geometry     = linestring;

                            placemark.ExtendedData = new ExtendedData();

                            placemark.ExtendedData.AddData(new Data
                            {
                                Name  = "Code",
                                Value = chamber.Code
                            });
                            placemark.ExtendedData.AddData(new Data
                            {
                                Name  = "ConstructionStage",
                                Value = chamber.ConstructionStage
                            });
                            placemark.ExtendedData.AddData(new Data
                            {
                                Name  = "ActivationStage",
                                Value = chamber.ActivationStage
                            });
                            placemark.ExtendedData.AddData(new Data
                            {
                                Name  = "Accessibility",
                                Value = chamber.Accessibility
                            });
                            placemark.ExtendedData.AddData(new Data
                            {
                                Name  = "HierarchyType",
                                Value = chamber.HierarchyType
                            });

                            document1.AddFeature(placemark);
                        }


                        kml.Feature = document1;
                        KmlFile kmlfile = KmlFile.Create(kml, false);

                        System.IO.File.Create(projectPath).Dispose();

                        using (var stream1 = System.IO.File.OpenWrite(projectPath))
                        {
                            kmlfile.Save(stream1);
                        }
                    }
                }


                return(new ResponseMessage()
                {
                    Status = "ok", Data = projectPath
                });
            }
            catch (Exception ex)
            {
                _logger?.LogError(ex, "Error export design.");
                return(new ResponseMessage()
                {
                    Status = "Error", Message = "Error export design."
                });
            }
        }
Beispiel #15
0
        static async Task MainAsync(string[] args)
        {
            Console.BackgroundColor = ConsoleColor.White;
            Console.ForegroundColor = ConsoleColor.Blue;
            Console.Clear();
            Console.WriteLine("Welcome to Google Earth Automator!");
            Console.WriteLine("Allow me to handle all the Google Earth Hassle :)");


START:
            Console.WriteLine();
            Console.Write("Please enter the coordinates of the location you would like to visit > ");

            Geospatial.Location desiredLocation = null;
            while (!Geospatial.Location.TryParse(Console.ReadLine(), out desiredLocation))
            {
                Console.WriteLine("The location coordinates you provided does not seem to be in the correct format.");
                Console.WriteLine("Please try again.");

                Console.WriteLine();
                Console.Write("Please enter the coordinates of the location you would like to visit > ");
            }

            var altitude = desiredLocation.Altitude.HasValue ? desiredLocation.Altitude.Value : 0.0;

            if (!Directory.Exists(TEMP_DIR))
            {
                Directory.CreateDirectory(TEMP_DIR);
            }

            var point = new SharpKml.Dom.Point();

            point.Coordinate = new SharpKml.Base.Vector(desiredLocation.Latitude.TotalDegrees, desiredLocation.Longitude.TotalDegrees, altitude);
            Kml       kml       = new Kml();
            Placemark placemark = new Placemark();

            placemark.Geometry = point;
            kml.Feature        = placemark;

            string path = Path.Combine(TEMP_DIR, Guid.NewGuid().ToString() + ".kml");

            using (var file = new FileStream(path, FileMode.Create, FileAccess.Write))
                using (var writer = new StreamWriter(file))
                {
                    Serializer serializer = new Serializer();
                    serializer.Serialize(kml);
                    writer.WriteLine(serializer.Xml);
                    writer.Flush();
                }

            Console.WriteLine("That would be no problem...");
            Console.WriteLine("What would you name would like to save the image with?");
            Console.Write("Please enter the full path > ");



            string savePath = Console.ReadLine();
            string saveDir  = string.Empty;

            try { saveDir = Path.GetDirectoryName(savePath); } catch { saveDir = string.Empty; }
            while (!Directory.Exists((saveDir)))
            {
                if (string.IsNullOrWhiteSpace(saveDir))
                {
                    saveDir  = Directory.GetCurrentDirectory();
                    savePath = Path.Combine(saveDir, savePath);
                }
                try { Directory.CreateDirectory(saveDir); }
                catch
                {
                    Console.WriteLine("Directory you provided to save the file does not exist, cannot be created, Please input another file path.");
                    savePath = Console.ReadLine();
                    try { saveDir = Path.GetDirectoryName(savePath); } catch { saveDir = string.Empty; }
                }
            }

            if (Path.GetExtension(savePath) != ".jpg")
            {
                savePath += ".jpg";
            }


            var startInfo = new ProcessStartInfo(GoogleEarthPath)
            {
            };


            var  processes = Process.GetProcesses();
            bool foundIt   = false;

            for (int i = 0; i < processes.Length; i++)
            {
                //Console.WriteLine(processes[i].ProcessName);
                if (!processes[i].ProcessName.Contains(GoogleEarth))
                {
                    continue;
                }

                GE      = Process.GetProcessById(processes[i].Id);
                foundIt = true;

                Console.WriteLine("Google Earth is already running...");
                break;
            }

            for (int i = 0; i < 3; i++)
            {
                Console.WriteLine();
            }

            if (!foundIt)
            {
                var gePath = GoogleEarthPath;
                while (!File.Exists(gePath))
                {
                    Console.WriteLine("Google Earth was not found, Please specify the path for the application.");
                    gePath = Console.ReadLine();
                }

                //Thread.Sleep(10000);
                var info = new ProcessStartInfo(path)
                {
                    Arguments        = $"\"{path}\"",
                    UseShellExecute  = true,
                    WorkingDirectory = Path.GetDirectoryName(path),
                    FileName         = gePath,
                    Verb             = "OPEN"
                };
                GE = Process.Start(info);
            }
            else
            {
                var info = new ProcessStartInfo(path)
                {
                    Arguments        = $"\"{path}\"",
                    UseShellExecute  = true,
                    WorkingDirectory = Path.GetDirectoryName(path),
                    FileName         = GoogleEarthPath,
                    Verb             = "OPEN"
                };
                Process.Start(info);
            }



            Console.WriteLine("Waiting for Google Earth to load....");
            while (GE.MainWindowHandle == IntPtr.Zero)
            {
                Thread.Sleep(1000);
            }

            bool geLoading = true;
            //CPUStatus status = new CPUStatus(GE);

            CpuUsage usage     = new CpuUsage(GE);
            var      loadTimer = new System.Timers.Timer()
            {
                Interval  = 500,
                Enabled   = true,
                AutoReset = true
            };

            int lowCount = 0;

            loadTimer.Elapsed += (s, e) =>
            {
                Console.Write("\rGoogle Earth CPU Usage: {0}%     ", usage.Usage);
                var value = usage.GetUsage();

                if (value < 5)
                {
                    lowCount++;
                }
                else
                {
                    lowCount = 0;
                }

                if (lowCount > 7)
                {
                    geLoading = false;
                }
            };

            loadTimer.Start();


            /*
             * CPUTracker.TrackProcess(GE);
             *
             * CPUTracker.CPUValuesUpdated += (s, e) =>
             * {
             *  Console.Write("\rGoogle Earth CPU Usage: {0}    ", e.ToString());
             *
             *  if (count > 100)
             *      geLoading = false;
             *  count++;
             * };
             */

            while (geLoading)
            {
                await Task.Delay(1000);
            }

            loadTimer.Stop();
            Console.WriteLine();
            Console.WriteLine("Google Earth has loaded successfully...");


            //CPUTracker.StopTracking();

            ShowWindow(GE.MainWindowHandle, SW_SHOWMAXIMIZED);
            SetForegroundWindow(GE.MainWindowHandle);

            /*
             * // Wait for the application to become the main window...
             * while (!GE.MainWindowHandle.Equals(GetForegroundWindow()))
             * {
             *  GE.Refresh();
             *  Thread.Sleep(2000);
             * }
             */

            // Iterate through the processes windows
            foreach (ProcessThread thread in GE.Threads)
            {
                EnumThreadWindows(thread.Id
                                  , (hWnd, lParam) =>
                {
                    var msg = new StringBuilder(1000);
                    SendMessage(hWnd, WM_GETTEXT, msg.Capacity, msg);

                    // If Startup Tips is open, send a close message
                    if (msg.ToString() == "Start-up Tips")
                    {
                        SendMessage(hWnd, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
                    }

                    return(true);
                }, IntPtr.Zero);
            }


            // toolbarFrameWindow
            // earth::modules::print::PrintToolbarClassWindow
            var mainWindowHandle = GE.MainWindowHandle;
            var saveTab          = FindWindow(GE.MainWindowHandle
                                              , (ptr => GetWindowText(ptr)
                                                 == "earth::modules::print::PrintToolbarClassWindow"));


            InputSimulator simulator = new InputSimulator();
            var            keyboard  = new KeyboardSimulator(simulator);

            if (saveTab == IntPtr.Zero || !IsWindowVisible(saveTab))
            {
                keyboard.ModifiedKeyStroke(new VirtualKeyCode[] { VirtualKeyCode.LMENU, VirtualKeyCode.LCONTROL }, VirtualKeyCode.VK_S);
                saveTab = FindWindow(GE.MainWindowHandle
                                     , (ptr => GetWindowText(ptr)
                                        == "earth::modules::print::PrintToolbarClassWindow"));
            }

            //keyboard.ModifiedKeyStroke(new VirtualKeyCode[] { VirtualKeyCode.LMENU, VirtualKeyCode.LCONTROL }, VirtualKeyCode.VK_C);

            /*
             * Thread.Sleep(1000);
             * var saveButton = FindWindowEx(GE.MainWindowHandle, IntPtr.Zero, "Qt5QWindowIcon", "earth::modules::print::PrintToolbarClassWindow");
             * Console.WriteLine(saveButton);
             * SendMessage((int)saveButton, BN_CLICKED, 0, IntPtr.Zero);
             */

            Thread.Sleep(2000);
            Console.WriteLine("Searching through all windows in the process");
            //PrintAllChildWindows(GE.MainWindowHandle);


            if (!SetForegroundWindow(saveTab))
            {
                Console.WriteLine("Failed to set save tab as the foreground window");
            }

            // Press 3 tabs to navigate to the save button
            for (int i = 0; i < 3; i++)
            {
                keyboard.KeyPress(VirtualKeyCode.TAB);
            }

            keyboard.KeyPress(VirtualKeyCode.SPACE);


            Thread.Sleep(1000);
            Console.WriteLine("Searching through the process for the save dialog box");
            //PrintAllChildWindows(GE.MainWindowHandle);

            /*
             * while ((saveAsDialog = FindWindow(GE.MainWindowHandle, ptr => GetWindowText(ptr) == "Save As")) == IntPtr.Zero)
             *  Thread.Sleep(1000);
             */

            Console.WriteLine("Found the save as dialog box");
            Console.WriteLine("Waiting for it to load...");
            Thread.Sleep(3000);
            IntPtr saveAsDialog = GetForegroundWindow();

            IntPtr textBox = FindWindow(saveAsDialog, ptr => GetWindowClass(ptr) == "Edit");

            SetFocus(textBox);
            keyboard.TextEntry(savePath);
            keyboard.KeyPress(VirtualKeyCode.RETURN);

            //return;

            Thread.Sleep(3000);
            ShowWindow(GE.MainWindowHandle, SW_SHOWMINIMIZED);

            Console.WriteLine("Automation is now complete, saving image...");

            /*
             * var data = Clipboard.GetDataObject();
             *
             * if (data == null)
             * {
             *  Console.WriteLine("Failed to access clipboard data...");
             *  Console.WriteLine("Google Automator will now exit");
             *  return;
             * }
             * if (data.GetDataPresent(DataFormats.Bitmap))
             * {
             *  using (var image = (Bitmap)data.GetData(DataFormats.Bitmap, true))
             *      image.Save(savePath, ImageFormat.Png);
             * }
             * else
             * {
             *  Console.WriteLine("There does not seem to be a bitmap format in the clipboard....");
             *  Console.WriteLine("The available formats are: ");
             *  foreach (var format in data.GetFormats())
             *      Console.WriteLine("\t{0}");
             *  Console.WriteLine("Google Earth Automator will now exit...");
             * }
             */

            Console.WriteLine("The image has been successfully saved at ({0})", savePath);

            Console.Write("Would you like to view the image? (Yes/No) > ");
            var answer = Console.ReadLine();

            if (answer.ToLower() == "y" || answer.ToLower() == "yes")
            {
                try { Process.Start(savePath); } catch { }
            }

            Console.Write("Well that's it!, would you like to run another automation sequence? > ");
            answer = Console.ReadLine();

            if (answer.ToLower() == "y" || answer.ToLower() == "yes")
            {
                goto START;
            }
        }
        protected virtual Feature CreateKmlFeature(FeatureDataRow feature, StyleSelector style)
        {
            var geometry = feature.Geometry;

            geometry = ToTarget(geometry);

            switch (geometry.OgcGeometryType)
            {
                case OgcGeometryType.Point:
                    {
                        var location = geometry.Coordinate;
                        var p = new Point { Coordinate = new Vector(location.Y, location.X) };

                        return WrapPlacemark(p, style, feature);
                    }
                case OgcGeometryType.MultiPoint:
                    {
                        var multiGeometry = new MultipleGeometry();

                        foreach (var coordinate in geometry.Coordinates)
                        {
                            var p = new Point { Coordinate = new Vector(coordinate.Y, coordinate.X) };

                            multiGeometry.AddGeometry(p);
                        }

                        return WrapPlacemark(multiGeometry, style, feature);
                    }
                case OgcGeometryType.LineString:
                    {
                        var lineString = CreateLineString(geometry);

                        return WrapPlacemark(lineString, style, feature);
                    }
                case OgcGeometryType.Polygon:
                    {
                        var polygon = (IPolygon)geometry;

                        var kmlPolygon = CreateKmlPolygon(polygon);

                        return WrapPlacemark(kmlPolygon, style, feature);
                    }
                case OgcGeometryType.MultiLineString:
                    {
                        var multiGeometry = new MultipleGeometry();

                        var multiLineString = (IMultiLineString)geometry;
                        foreach (var innerGeometry in multiLineString.Geometries)
                        {
                            var lineString = CreateLineString(innerGeometry);

                            multiGeometry.AddGeometry(lineString);
                        }

                        return WrapPlacemark(multiGeometry, style, feature);
                    }
                case OgcGeometryType.MultiPolygon:
                    {
                        var multiGeometry = new MultipleGeometry();
                        var multiPoly = (IMultiPolygon)geometry;

                        foreach (var innerGeometry in multiPoly.Geometries.Cast<IPolygon>())
                        {
                            var polygon = CreateKmlPolygon(innerGeometry);

                            multiGeometry.AddGeometry(polygon);
                        }

                        return WrapPlacemark(multiGeometry, style, feature);
                    }
                default:
                    throw new InvalidOperationException("Geometry not supported");
            }
        }
Beispiel #17
0
        private void writeKML(string filename)
        {
            SharpKml.Dom.AltitudeMode altmode = SharpKml.Dom.AltitudeMode.Absolute;

            if (MainV2.cs.firmware == MainV2.Firmwares.ArduPlane)
            {
                altmode = SharpKml.Dom.AltitudeMode.Absolute;
            }
            else if (MainV2.cs.firmware == MainV2.Firmwares.ArduCopter2)
            {
                altmode = SharpKml.Dom.AltitudeMode.RelativeToGround;
            }

            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()
            {
                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);

            Style stylet = new Style();

            stylet.Id = "track";
            SharpKml.Dom.IconStyle ico = new SharpKml.Dom.IconStyle();
            LabelStyle             lst = new LabelStyle();

            lst.Scale         = 0;
            stylet.Icon       = ico;
            ico.Icon          = new IconStyle.IconLink(new Uri("http://earth.google.com/images/kml-icons/track-directional/track-none.png"));
            stylet.Icon.Scale = 0.5;
            stylet.Label      = lst;

            kml.AddStyle(stylet);

            // create sub folders
            Folder planes = new Folder();

            planes.Name = "Planes";
            kml.AddFeature(planes);

            Folder points = new Folder();

            points.Name = "Points";
            kml.AddFeature(points);


            // 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 = altmode;
                    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 = altmode;
                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 = "Point " + 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;

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

                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 = altmode;
                model.Scale        = sca;

                try
                {
                    Description desc = new Description();
                    desc.Text = @"<![CDATA[
              <table>
                <tr><td>Roll: " + model.Orientation.Roll.Value.ToString("0.00") + @" </td></tr>
                <tr><td>Pitch: " + model.Orientation.Tilt.Value.ToString("0.00") + @" </td></tr>
                <tr><td>Yaw: " + model.Orientation.Heading.Value.ToString("0.00") + @" </td></tr>
                <tr><td>Time: " + cs.datetime.ToString("HH:mm:sszzzzzz") + @" </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);

                ///

                Placemark pmt = new Placemark();

                SharpKml.Dom.Point pnt = new SharpKml.Dom.Point();
                pnt.AltitudeMode = altmode;
                pnt.Coordinate   = new Vector(cs.lat, cs.lng, cs.alt);

                pmt.Name = "" + a;

                pmt.Description = pmplane.Description;

                pmt.Time = tstamp;

                pmt.Geometry = pnt;
                pmt.StyleUrl = new Uri("#track", UriKind.Relative);

                points.AddFeature(pmt);

                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();

            flightdata.Clear();
        }
Beispiel #18
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);
                }
            }
        }
        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
        }
Beispiel #20
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);
                }
            }
        }
Beispiel #21
0
        private void ProcessPointGeometry(Point f)
        {
            var coords = new Coordinate(f.Coordinate.Longitude, f.Coordinate.Latitude);

            var pGeom = _geometryFactory.CreatePoint(coords);
            AddGeometryToCollection(f.GetParent<Placemark>(), pGeom);
        }
Beispiel #22
0
        static void Main(string[] args)
        {
            TextDatei textDatei = new TextDatei();

            int  state         = 0;
            bool exit          = false;
            bool argsFertig    = false;
            bool startWithArgs = false;

            string       file_path_gesamt = "";      // Gesamter Pfad der Datei. Zum Beispiel:           "F:\\Dropbox\\Schlapphut-Projekt\\GPS-Files\\20180628.SLP"
            string       dir_path         = "";      // Pfad zum Verzeichnis der Datei. Zum Beispiel:    "F:\\Dropbox\\Schlapphut-Projekt\\GPS-Files"
            string       file_name        = "";      // Name der Datei. Zum Beispiel:                    "20180628"
            string       file_type        = "";      // Dateityp der Datei. Zum Beispiel:                "SLP"
            const string dir_kml          = "\\KML"; // Unterverzeichnis, in welchem die konvertierte KML-Datei gespeichert wird

            SlpType slpFileType = SlpType.None;      // Der Typ der SLP-Datei

            List <String> file_lines = new List <string>();

            // Fuer KML-Dokument
            var root = new Document();

            root.Open = true;       // Bei Google-Earth das Tree-Menu ausklappen

            // Erstelle Styles
            Style         normalStyle    = CreateNormalSyle();
            Style         highlightStyle = CreateHighlightSyle();
            StyleSelector styleSelector  = createPlacemarkLineStyleMap(normalStyle, highlightStyle);

            // Weise Styles zu
            root.AddStyle(normalStyle);
            root.AddStyle(highlightStyle);
            root.AddStyle(styleSelector);


            Console.ForegroundColor = ConsoleColor.DarkGray;
            Console.WriteLine("KML Converter v1.0 (c) Axfire123, June 2018\r\n");
            Console.ResetColor();



            while (!exit)
            {
                switch (state)
                {
                case -1:        // Reset
                {
                    Console.WriteLine("\r\n\r\n");
                    state = 0;
                    break;
                }

                case 0:     // Dateipfad einlesen
                {
                    // Prüfen, ob beim Programmaufruf eine oder mehrere
                    // Zeichenfolgen übergeben worden sind
                    if ((args.Length == 0) || (argsFertig == true))
                    {
                        Console.WriteLine("Bitte ziehe eine SLP-Datei in das Fenster und bestätige mit Enter\r\n");
                        //Console.ResetColor();
                        file_path_gesamt = Console.ReadLine();
                        if (file_path_gesamt == String.Empty)
                        {
                            Console.ForegroundColor = ConsoleColor.Red;
                            Console.WriteLine("Es wurde keine Datei ausgewählt!");
                            state = -1;
                        }
                        else
                        {
                            state = 1;
                        }
                    }
                    else
                    {
                        file_path_gesamt = args[0];
                        state            = 1;
                        startWithArgs    = true;
                    }

                    break;
                }

                case 1:     // Untersuche einzulesende Datei
                {
                    dir_path  = getDirFromPath(file_path_gesamt);
                    file_name = getNameFromPath(file_path_gesamt);
                    file_type = getFileTypeFromPath(file_path_gesamt);

                    // püfe auf richtiges Dateiformat
                    if (file_type.ToLower() != "slp")
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine("Die gewählte Datei ist vom falschen Typ. Es werden nur .txt Dateien unterstützt!");
                        Console.ResetColor();
                        state = -1;
                    }
                    else
                    {
                        state = 2;
                    }
                    //
                    break;
                }

                case 2:     // Datei einlesen
                {
                    try
                    {
                        // Lese Datei ein
                        for (int i = 0; i < textDatei.getNumberOfLines(file_path_gesamt); i++)
                        {
                            file_lines.Add(textDatei.ReadLine(file_path_gesamt, i + 1));
                        }


                        if (file_lines.Count != 0)
                        {
                            Console.WriteLine("Datei \"{0}.slp\" erfolgreich eingelesen", file_name);
                            state = 6;
                        }
                        else
                        {
                            Console.WriteLine("Aus Datei \"{0}.slp\" konnte keine Zeilen gelesen werden", file_name);
                            state = -1;
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Datei \"{0}.slp\" konnte nicht gelesen werden", file_name);
                        Console.WriteLine(ex.Message);
                        state = -1;
                    }


                    break;
                }

                case 6:     // Typ der SLP-Datei prüfen. Handelt es sich um Tracks oder Points?
                {
                    // In der ersten Zeile der SLP-Datei sollte der Typ stehen
                    if (file_lines[0] == "TYPE=TRACK")
                    {
                        state       = 3;
                        slpFileType = SlpType.Track;
                        Console.WriteLine("TYPE=TRACK in \"{0}.slp\" gefunden", file_name);
                    }
                    else if (file_lines[0] == "TYPE=POINT")
                    {
                        state       = 7;
                        slpFileType = SlpType.Point;
                        Console.WriteLine("TYPE=POINT in \"{0}.slp\" gefunden", file_name);
                    }
                    else
                    {
                        state       = 3;
                        slpFileType = SlpType.Track;
                        Console.WriteLine("Keine Version in \"{0}.slp\" gefunden. Gehe von TYPE=TRACK aus", file_name);
                    }

                    break;
                }

                case 3:     // Version Track: Zeilen der Datei konvertieren und zu Track hinzufuegen
                {
                    double   lat;
                    double   lon;
                    DateTime dateTime;
                    bool     trackAnfang;
                    bool     ersterTrackGefunden = false;

                    int       placemarkNumber = 1;
                    var       track           = new SharpKml.Dom.GX.Track();
                    Placemark placemark       = new Placemark();
                    placemark.Name = "Track " + placemarkNumber;
                    placemark.Open = true;              // Bei Google-Earth das Tree-Menu ausklappen

                    for (int i = 0; i < file_lines.Count; i++)
                    {
                        if (parseLine(file_lines[i], out lat, out lon, out dateTime, out trackAnfang))
                        {
                            // Wurde ein Trackanfang gefunden
                            if (trackAnfang)
                            {
                                // Handel es sich um den ertsen Track der Datei
                                if (ersterTrackGefunden == false)
                                {
                                    // ja => mache nichts
                                    ersterTrackGefunden = true;
                                }
                                else
                                {
                                    // nein => speicher aktuellen Track ab

                                    // hat Track ueberhaupt Inhalt?
                                    if (track.Coordinates.Count() > 0)
                                    {
                                        // Weise Styleselector zu
                                        placemark.StyleUrl = new Uri(String.Format("#{0}", styleSelector.Id), UriKind.Relative);

                                        // Placemark Description
                                        DateTime start = track.When.ElementAt(0);                                 // Hole das Startdatum des Tracks
                                        DateTime ende  = track.When.ElementAt <DateTime>(track.When.Count() - 1); // Hole das Enddatum des Tracks

                                        SharpKml.Dom.Description description = new Description();
                                        description.Text      = String.Format("Start: {0}\nEnde: {1}\nZeit: {2} Minuten", start.ToLongTimeString(), ende.ToLongTimeString(), Convert.ToInt16(ende.Subtract(start).TotalMinutes));
                                        placemark.Description = description;

                                        // Placemark Geometry / Inhalt
                                        placemark.Geometry = track;

                                        // Fuege Track hinzu
                                        root.AddFeature(placemark);

                                        // Placemark Nummer erhoehen
                                        placemarkNumber++;
                                    }

                                    // Neue Instanzen bilden
                                    track          = new SharpKml.Dom.GX.Track();
                                    placemark      = new Placemark();
                                    placemark.Name = "Track " + placemarkNumber;
                                }
                            }
                            else
                            {
                                // speicher Koordinaten-Daten in Track
                                var vector = new Vector(lat, lon);
                                track.AddCoordinate(vector);
                                track.AddWhen(dateTime);
                            }
                        }
                    }

                    // speicher ggf. letzten Track ab
                    if (track.When.Count() > 0)
                    {
                        // Weise Styleselector zu
                        placemark.StyleUrl = new Uri(String.Format("#{0}", styleSelector.Id), UriKind.Relative);

                        // Placemark Description
                        DateTime start = track.When.ElementAt(0);                                 // Hole das Startdatum des Tracks
                        DateTime ende  = track.When.ElementAt <DateTime>(track.When.Count() - 1); // Hole das Enddatum des Tracks

                        SharpKml.Dom.Description description = new Description();
                        description.Text      = String.Format("Start: {0}\nEnde: {1}\nZeit: {2} Minuten", start.ToLongTimeString(), ende.ToLongTimeString(), Convert.ToInt16(ende.Subtract(start).TotalMinutes));
                        placemark.Description = description;

                        // Placemark Geometry / Inhalt
                        placemark.Geometry = track;

                        // Fuege Track hinzu
                        root.AddFeature(placemark);
                    }

                    state = 4;
                    break;
                }


                case 7:     // Type Point: Zeilen der Datei konvertieren und zu Point hinzufuegen
                {
                    double   lat;
                    double   lon;
                    DateTime dateTime;
                    bool     trackAnfang;               // Auch wenn es beim Poit keinen Trackanfang gibt, wird die Variabel fuer die Funktion gebraucht

                    int placemarkNumber = 1;



                    for (int i = 0; i < file_lines.Count; i++)
                    {
                        if (parseLine(file_lines[i], out lat, out lon, out dateTime, out trackAnfang))
                        {
                            // Wurde ein Trackanfang gefunden
                            if (trackAnfang)
                            {
                                continue;           // es gibt beim Point keinen Trackanfang...
                            }
                            else
                            {
                                var       point     = new SharpKml.Dom.Point();
                                Placemark placemark = new Placemark();
                                placemark.Name = "Point " + placemarkNumber++;
                                placemark.Open = true;              // Bei Google-Earth das Tree-Menu ausklappen

                                // Speicher Daten in Point
                                Vector vector = new Vector(lat, lon);
                                point.Coordinate = vector;

                                // Erzeuge Placemark-Beschreibung
                                SharpKml.Dom.Description description = new Description();
                                description.Text      = String.Format("Datum: {0}\nUhrzeit: {1}", dateTime.ToLongDateString(), dateTime.ToLongTimeString());
                                placemark.Description = description;
                                // Fuege den Point dem Placemark hinzu
                                placemark.Geometry = point;

                                // Fuege den Placemark dem Dokument hinzu
                                root.AddFeature(placemark);
                            }
                        }
                    }

                    state = 4;
                    break;
                }

                case 4:     // KML-File erstellen
                {
                    KmlFile kml = KmlFile.Create(root, false);

                    try
                    {
                        String kmlDirPath = dir_path + dir_kml;                                 // Pfad zum Verzeichnis

                        // KML-File Name
                        // konvertiere den "yyMMdd" Namen der SLP-Datei in das besser lesbare "yy-MM-dd" Format
                        String kml_file_name = String.Empty;
                        try
                        {
                            DateTime dateTime = DateTime.ParseExact(file_name, "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture);
                            kml_file_name = dateTime.ToString("yyyy-MM-dd");
                        }
                        catch
                        {
                            kml_file_name = file_name;
                        }
                        //

                        // SLP-Typ als Name anhaengen
                        if (slpFileType == SlpType.Track)
                        {
                            kml_file_name += " Track";
                        }
                        else if (slpFileType == SlpType.Point)
                        {
                            kml_file_name += " Point";
                        }

                        String kmlFilePath = kmlDirPath + "\\" + kml_file_name + ".kml";            // Pfad zur Datei

                        // Directory erzeugen, falls nicht vorhanden
                        if (!Directory.Exists(kmlDirPath))
                        {
                            Directory.CreateDirectory(kmlDirPath);
                        }

                        // Speicher
                        using (FileStream stream = File.OpenWrite(kmlFilePath))
                        {
                            kml.Save(stream);
                        }
                        Console.WriteLine("KML-Datei \"{0}.kml\" wurde erfolgreich gespeichert", file_name);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("KML-Datei \"{0}.kml\" konnte nicht gespeichert werden", file_name);
                        Console.WriteLine(ex.Message);
                    }

                    root      = new Document();
                    root.Open = true;               // Bei Google-Earth das Tree-Menu ausklappen

                    state = 5;
                    break;
                }

                case 5:     // Wie gehts weiter?

                    if (startWithArgs)
                    {
                        exit = true;
                        // warte x Sekunden, bis Programm geschlossen wird
                        Console.Write("Programm wird beendet ");
                        System.Threading.Thread.Sleep(100);
                        Console.Write(".");
                        System.Threading.Thread.Sleep(100);
                        Console.Write(".");
                        System.Threading.Thread.Sleep(100);
                        Console.Write(".");
                        System.Threading.Thread.Sleep(100);
                        Console.Write(".");
                        System.Threading.Thread.Sleep(100);
                        Console.Write(".");
                        System.Threading.Thread.Sleep(100);
                        Console.Write(".");
                        System.Threading.Thread.Sleep(100);
                        Console.Write(".");
                        System.Threading.Thread.Sleep(100);
                        Console.Write("\r\nBey!");
                        System.Threading.Thread.Sleep(500);
                    }
                    else
                    {
                        state = -1;
                    }
                    break;
                }
            }
        }
        protected virtual Feature CreateKmlFeature(FeatureDataRow feature, StyleSelector style)
        {
            var geometry = feature.Geometry;

            geometry = ToTarget(geometry);

            switch (geometry.OgcGeometryType)
            {
            case OgcGeometryType.Point:
            {
                var location = geometry.Coordinate;
                var p        = new Point {
                    Coordinate = new Vector(location.Y, location.X)
                };

                return(WrapPlacemark(p, style, feature));
            }

            case OgcGeometryType.MultiPoint:
            {
                var multiGeometry = new MultipleGeometry();

                foreach (var coordinate in geometry.Coordinates)
                {
                    var p = new Point {
                        Coordinate = new Vector(coordinate.Y, coordinate.X)
                    };

                    multiGeometry.AddGeometry(p);
                }

                return(WrapPlacemark(multiGeometry, style, feature));
            }

            case OgcGeometryType.LineString:
            {
                var lineString = CreateLineString(geometry);

                return(WrapPlacemark(lineString, style, feature));
            }

            case OgcGeometryType.Polygon:
            {
                var polygon = (IPolygon)geometry;

                var kmlPolygon = CreateKmlPolygon(polygon);

                return(WrapPlacemark(kmlPolygon, style, feature));
            }

            case OgcGeometryType.MultiLineString:
            {
                var multiGeometry = new MultipleGeometry();

                var multiLineString = (IMultiLineString)geometry;
                foreach (var innerGeometry in multiLineString.Geometries)
                {
                    var lineString = CreateLineString(innerGeometry);

                    multiGeometry.AddGeometry(lineString);
                }

                return(WrapPlacemark(multiGeometry, style, feature));
            }

            case OgcGeometryType.MultiPolygon:
            {
                var multiGeometry = new MultipleGeometry();
                var multiPoly     = (IMultiPolygon)geometry;

                foreach (var innerGeometry in multiPoly.Geometries.Cast <IPolygon>())
                {
                    var polygon = CreateKmlPolygon(innerGeometry);

                    multiGeometry.AddGeometry(polygon);
                }

                return(WrapPlacemark(multiGeometry, style, feature));
            }

            default:
                throw new InvalidOperationException("Geometry not supported");
            }
        }
Beispiel #24
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);
                }
            }
        }
        private void writeKML(string filename)
        {
            SharpKml.Dom.AltitudeMode altmode = SharpKml.Dom.AltitudeMode.Absolute;

            if (MainV2.cs.firmware == MainV2.Firmwares.ArduPlane)
            {
                altmode = SharpKml.Dom.AltitudeMode.Absolute;
            }
            else if (MainV2.cs.firmware == MainV2.Firmwares.ArduCopter2)
            {
                altmode = SharpKml.Dom.AltitudeMode.RelativeToGround;
            }

            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() { 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);

            Style stylet = new Style();
            stylet.Id = "track";
            SharpKml.Dom.IconStyle ico = new SharpKml.Dom.IconStyle();
            LabelStyle lst = new LabelStyle();
            lst.Scale = 0;
            stylet.Icon = ico;
            ico.Icon = new IconStyle.IconLink(new Uri("http://earth.google.com/images/kml-icons/track-directional/track-none.png"));
            stylet.Icon.Scale = 0.5;
            stylet.Label = lst;

            kml.AddStyle(stylet);

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

            Folder points = new Folder();
            points.Name = "Points";
            kml.AddFeature(points);

            // 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 = altmode;
                    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 = altmode;
                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 = "Point " + 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;

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

                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 = altmode;
                model.Scale = sca;

                try
                {
                    Description desc = new Description();
                    desc.Text = @"<![CDATA[
              <table>
                <tr><td>Roll: " + model.Orientation.Roll.Value.ToString("0.00") + @" </td></tr>
                <tr><td>Pitch: " + model.Orientation.Tilt.Value.ToString("0.00") + @" </td></tr>
                <tr><td>Yaw: " + model.Orientation.Heading.Value.ToString("0.00") + @" </td></tr>
                <tr><td>Time: " + cs.datetime.ToString("HH:mm:sszzzzzz") + @" </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);

                ///

                Placemark pmt = new Placemark();

                SharpKml.Dom.Point pnt = new SharpKml.Dom.Point();
                pnt.AltitudeMode = altmode;
                pnt.Coordinate = new Vector(cs.lat,cs.lng,cs.alt);

                pmt.Name = "" + a;

                pmt.Description = pmplane.Description;

                pmt.Time = tstamp;

                pmt.Geometry = pnt;
                pmt.StyleUrl = new Uri("#track", UriKind.Relative);

                points.AddFeature(pmt);

                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();

            flightdata.Clear();
        }