private void ProcessCommand(string command)
 {
     try
     {
         int yachtId;
         if (int.TryParse(Regex.Replace(command, " .*", ""), out yachtId))
         {
             command = Regex.Replace(command, "^" + yachtId + " ", "");
             switch (Regex.Replace(command, "(.*?) .*", "$1").ToUpperInvariant())
             {
                 case "HEADING":
                     labelHeading.Text = "Heading: " + Regex.Replace(command, "HEADING ", "", RegexOptions.IgnoreCase);
                     this.heading = (float)Convert.ToDouble(Regex.Replace(command, "HEADING ", "", RegexOptions.IgnoreCase));
                     break;
                 case "HEELING":
                     labelHeeling.Text = "Heeling: " + Regex.Replace(command, "HEELING ", "", RegexOptions.IgnoreCase);
                     break;
                 case "LOCATION":
                     try
                     {
                         Geospatial.Location location = Geospatial.Location.Parse(Regex.Replace(command, "LOCATION ", "", RegexOptions.IgnoreCase), Geospatial.LocationStyles.Iso, CultureInfo.CurrentCulture);
                         if (lastLocation != null)
                         {
                         }
                         lastLocation = location;
                         textBoxLatitude.Text = location.Latitude.ToString();
                         textBoxLongitude.Text = location.Longitude.ToString();
                     }
                     catch { }
                     break;
                 case "NAME":
                     break;
                 case "REMOVED":
                     int id = Convert.ToInt32(Regex.Replace(command, "REMOVED ", "", RegexOptions.IgnoreCase));
                     if (id == yachtId)
                     {
                         yachtId = -1;
                         timerYachtUpdater.Stop();
                         buttonAddYacht.Enabled = true;
                     }
                     break;
                 case "RUDDER":
                     labelSetRudderAngle.Text = "Rudder Angle " + Regex.Replace(command, "RUDDER ", "", RegexOptions.IgnoreCase);
                     break;
                 case "SAIL":
                     labelSetSailAngle.Text = "Sail Angle " + Regex.Replace(command, "SAIL ", "", RegexOptions.IgnoreCase);
                     break;
                 case "SAILDIRECTION":
                     labelSailDirection.Text = "Sail Angle: " + Regex.Replace(command, "SAILDIRECTION ", "", RegexOptions.IgnoreCase);
                     this.sailAngel = (float)Convert.ToDouble(Regex.Replace(command, "SAILDIRECTION ", "", RegexOptions.IgnoreCase));
                     break;
                 case "WAYPOINT":
                     break;
                 case "WAYPOINTS":
                     foreach (var waypoint in Regex.Split(Regex.Replace(command, "WAYPOINTS ", "", RegexOptions.IgnoreCase), ";"))
                     {
                         int waypointId;
                         if (int.TryParse(Regex.Replace(waypoint, "=.*", ""), out waypointId))
                         {
                             Geospatial.Location location;
                             if (Geospatial.Location.TryParse(waypoint.Replace(waypointId + "=", ""), Geospatial.LocationStyles.Iso, CultureInfo.CurrentCulture, out location))
                             {
                                 try
                                 {
                                     waypoints.Add(waypointId, location);
                                     var item = listViewWaypoints.Items.Add("");
                                     item.SubItems.Add(location.Latitude.ToString());
                                     item.SubItems.Add(location.Longitude.ToString());
                                     item.Tag = waypointId;
                                 }
                                 catch
                                 {
                                 }
                             }
                         }
                     }
                     break;
                 case "WINDANGLE":
                     labelWindAngle.Text = "Apparent Wind Angle: " + Regex.Replace(command, "WINDANGLE ", "", RegexOptions.IgnoreCase);
                     this.windAngel = (float)Convert.ToDouble(Regex.Replace(command, "WINDANGLE ", "", RegexOptions.IgnoreCase));
                     break;
                 case "WINDVELOCITY":
                     labelWindSpeed.Text = "Apparent Wind Speed: " + Regex.Replace(command, "WINDVELOCITY ", "", RegexOptions.IgnoreCase) + " m/s";
                     break;
                 case "ERROR":
                     break;
                 case "UNKNOWN":
                     break;
                 case "WAYPOINTADDED":
                     break;
                 case "WAYPOINTREMOVED":
                     break;
                 default:
                     break;
             }
         }
         else
         {
             switch (Regex.Replace(command, "(.*?) .*", "$1").ToUpperInvariant())
             {
                 case "ADDED":
                     thisYachtId = Convert.ToInt32(Regex.Replace(command, "ADDED ", "", RegexOptions.IgnoreCase));
                     if (thisYachtId != -1)
                     {
                         buttonAddYacht.Enabled = false;
                         SendToServer(yachtId + " set sail " + trackBarSailAngle.Value.ToString());
                         SendToServer(yachtId + " set rudder " + trackBarRudder.Value.ToString());
                     }
                     break;
                 case "REMOVED":
                     int id = Convert.ToInt32(Regex.Replace(command, "REMOVED ", "", RegexOptions.IgnoreCase));
                     if (id == yachtId)
                     {
                         yachtId = -1;
                         timerYachtUpdater.Stop();
                         buttonAddYacht.Enabled = true;
                     }
                     break;
                 case "SIMULATORS":
                     foreach (var simulator in Regex.Split(Regex.Replace(command, "SIMULATORS ", "", RegexOptions.IgnoreCase), ";"))
                     {
                         comboBoxYachtTypes.Items.Add(simulator);
                     }
                     if (comboBoxYachtTypes.Items.Count > 0 && comboBoxYachtTypes.SelectedIndex == -1)
                     {
                         comboBoxYachtTypes.SelectedIndex = 0;
                     }
                     break;
                 default:
                     break;
             }
         }
     }
     catch
     {
     }
 }
Exemple #2
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;
            }
        }