Example #1
0
        private void RunRateAppCheck()
        {
            var messageBox = new CustomMessageBox()
            {
                Caption = Messages.MainPage_RateHeader,
                Message = Messages.MainPage_DoYouLikeApp,
                LeftButtonContent = UILabels.Common_Yes,
                RightButtonContent = UILabels.Common_No
            };
            messageBox.Dismissed += (s1, e1) =>
            {
                switch (e1.Result)
                {
                    case CustomMessageBoxResult.LeftButton: // yes
                        InitRateRequest();                        
                        break;
                    case CustomMessageBoxResult.RightButton: // no
                        InitEmailRequest();
                        break;
                    default:
                        App.ApplicationSettings.LastCoolDownActivated = DateTime.UtcNow;
                        break;
                }
            };

            messageBox.Show();
        }
Example #2
0
        private void lstAdapters_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            lstAdapterItem selItem = ((lstAdapterItem)lstAdapters.SelectedItem);
            TextBox dnsBox = new TextBox() { Text = selItem.PrimaryDNS };

            TiltEffect.SetIsTiltEnabled(dnsBox, true);

            CustomMessageBox messageBox = new CustomMessageBox()
            {
                Caption = "Edit DNS for " + selItem.Name,
                Message = "Primary DNS Server:",
                Content = dnsBox,
                LeftButtonContent = "save",
                RightButtonContent = "cancel",
                IsFullScreen = false
            };

            messageBox.Dismissed += (s1, e1) =>
            {
                if (e1.Result == CustomMessageBoxResult.LeftButton)
                {
                    Registry.SetMultiStringValue(selItem.KeyRoot, selItem.KeyPath, "DNS", new string[] { dnsBox.Text });
                    //TODO: Clear the list first
                    refreshAdapters();
                }
                //TODO: Fix this
                //lstAdapters.SelectedIndex = -1;
            };

            messageBox.Show();
        }
        private void BasicMessageBox_Click(object sender, RoutedEventArgs e)
        {
            CustomMessageBox messageBox = new CustomMessageBox()
            {
                Caption = "Pregunta?",
                Message = "Mensaje del CustomMessageBox.",
                LeftButtonContent = "Si",
                RightButtonContent = "No",
                IsFullScreen = (bool)FullScreenCheckBox.IsChecked
            };

            messageBox.Dismissed += (s1, e1) =>
            {
                switch (e1.Result)
                {
                    case CustomMessageBoxResult.LeftButton:
                        // Acción.
                        break;
                    case CustomMessageBoxResult.RightButton:
                        // Acción.
                        break;
                    case CustomMessageBoxResult.None:
                        // Acción.
                        break;
                    default:
                        break;
                }
            };

            messageBox.Show();
        }
Example #4
0
        public MainForm(AppManager manager)
        {
            _flgLoading = true;
            InitializeComponent();

            _manager = manager;
            if (_manager == null)
            {
                CustomMessageBox cmb = new CustomMessageBox("The application manager has not been loaded for some reason.\nThe application can't work and will be closed.", "FATAL", MessageBoxDialogButtons.Ok, MessageBoxDialogIcon.Fatal, false, false);
                cmb.ShowDialog();
                cmb.Dispose();
                this.Close();
            }

            InitializeStyle();
            InitializeGUIEventsHandlers();

            categoriesTabs.Manager = _manager;

            SetupUI();
            _SelectedCategory = -1;
            _SelectedGame = -1;
            EnableMenus(false);
            if (_manager.AppSettings.ReloadLatestDB && (_manager.RecentDBs != null && _manager.RecentDBs.Count > 0))
                OpenRecentDatabase(_manager.RecentDBs.First().Value.DBPath, false);

            _flgLoading = false;
        }
 public void Show(string text, string firstOption, string secondOption, Action firstAction, Action secondAction)
 {
     Mvx.Resolve<IMvxMainThreadDispatcher>().RequestMainThreadAction(() =>
     {
         _messageBox = new CustomMessageBox
         {
             AllowDrop = false,
             Message = text,
             IsLeftButtonEnabled = true,
             IsRightButtonEnabled = true,
             LeftButtonContent = firstOption,
             RightButtonContent = secondOption
         };
         _messageBox.Dismissed += (s, e) =>
         {
             if (e.Result == CustomMessageBoxResult.LeftButton && firstAction != null)
             {
                 firstAction();
             }
             else if (e.Result == CustomMessageBoxResult.RightButton && secondAction != null)
             {
                 secondAction();
             }
         };
         _messageBox.Show();
     });
 }
        private void AddNote_Click(object sender, EventArgs e)
        {
            // let the user enter her note in a popup window

            var noteTextBox = new TextBox { Text = "My New Note" };

            var messageBox = new CustomMessageBox
            {
                Caption = "Note Text",
                Content = noteTextBox,
                LeftButtonContent = "OK",
                RightButtonContent = "Cancel"
            };

            messageBox.Dismissed += (s, args) =>
            {
                switch (args.Result)
                {
                    case CustomMessageBoxResult.LeftButton:

                        App.ViewModel.AddNote(noteTextBox.Text);

                    break;
                    case CustomMessageBoxResult.RightButton:
                    case CustomMessageBoxResult.None:
                    break;
                }
            };

            messageBox.Show();
        }
        /// <summary>
        /// Displays a CustomMessageBox with no content.
        /// </summary>
        /// <param name="sender">The event sender.</param>
        /// <param name="e">The event information.</param>
        private void BasicMessageBox_Click(object sender, RoutedEventArgs e)
        {
            CustomMessageBox messageBox = new CustomMessageBox()
            {                
                Caption = "Do you like this sample?",
                Message = "There are tons of things you can do using custom message boxes. To learn more, be sure to check out the source code at Codeplex.",
                LeftButtonContent = "yes",
                RightButtonContent = "no",
                IsFullScreen = (bool)FullScreenCheckBox.IsChecked
            };

            messageBox.Dismissed += (s1, e1) =>
                {
                    switch (e1.Result)
                    {
                        case CustomMessageBoxResult.LeftButton:
                            // Do something.
                            break;
                        case CustomMessageBoxResult.RightButton:
                            // Do something.
                            break;
                        case CustomMessageBoxResult.None:
                            // Do something.
                            break;
                        default:
                            break;
                    }
                };

            messageBox.Show();
        }
Example #8
0
 public void Prompt(string message, string title, Action<string> onPrompt, Action onCancel = null)
 {
     var textBox = new TextBox();
     var messageBox = new CustomMessageBox()
     {
         Caption = title,
         LeftButtonContent = "Подтвердить",
         RightButtonContent = "Отмена",
         Message = message,
         Content = textBox
     };
     messageBox.Dismissed += (sender, args) =>
     {
         switch (args.Result)
         {
             case CustomMessageBoxResult.LeftButton:
                 onPrompt(textBox.Text);
                 // Do something.
                 break;
             case CustomMessageBoxResult.RightButton:
                 // Do something.
                 if (onCancel != null) onCancel();
                 break;
             case CustomMessageBoxResult.None:
                 // Do something.
                 if (onCancel != null) onCancel();
                 break;
             default:
                 if (onCancel != null) onCancel();
                 break;
         }
     };
     messageBox.Show();
 }
Example #9
0
        public static void msgBuy()
        {
            CustomMessageBox messageBox = new CustomMessageBox()
            {
                Caption = "Хотите приобрести расширенную версию?",
                Message = "Функции: словарь, озвучка слов и аудиролвание предоставляются только в расширенной версии приложения. Хотите приобрести (цена: 34 руб.)? Покупая расширенную версию, Вы поддерживаете дальнейшее создание уроков.",
                LeftButtonContent = "нет",
                RightButtonContent = "да",
                IsFullScreen = false
            };

            messageBox.Dismissed += (s1, e1) =>
            {
                switch (e1.Result)
                {
                    case CustomMessageBoxResult.LeftButton:
                        // Do something.
                        break;
                    case CustomMessageBoxResult.RightButton:
                        BuyPro();
                        break;
                    case CustomMessageBoxResult.None:
                        // Do something.
                        break;
                    default:
                        break;
                }
            };

            messageBox.Show();
        }
Example #10
0
 private void btSelecionarCliente_Click(object sender, RoutedEventArgs e)
 {
     UCSelecaoCliente ucsc = new UCSelecaoCliente();
     CustomMessageBox cmb = new CustomMessageBox()
     {
         Content = ucsc,
         LeftButtonContent = "Selecionar",
         RightButtonContent = "Cancelar"
     };
     cmb.Dismissing += (s1, e1) =>
     {
         switch (e1.Result)
         {
             case CustomMessageBoxResult.LeftButton:
                 if (ucsc.listClientes.SelectedItem == null)
                     e1.Cancel = true;
                 if (ucsc.listClientes.SelectedItem != null)
                 {
                     novoPedido.IdCliente = (ucsc.listClientes.SelectedItem as Cliente).Id;
                     btSelecionarCliente.Content = (ucsc.listClientes.SelectedItem as Cliente).Nome;
                 }
                 break;
         }
     };
     cmb.Show();
 }
		/// <summary>
		/// Makes sure a message box is managed by this manager.
		/// </summary>
		/// <param name="wmb"></param>
		private CustomMessageBox Accept(WF.Player.Core.MessageBox wmb)
		{
			CustomMessageBox cmb = null;
			
			// Checks if this instance already manages this message box.
			// If not, starts to manage the box.
			KeyValuePair<CustomMessageBox, WF.Player.Core.MessageBox> pair = _WherigoMessageBoxes.SingleOrDefault(kv => kv.Value == wmb);
			if (pair.Value == wmb)
			{
				// The target message box exists already.
				cmb = pair.Key;
			}
			else
			{
				// Creates a target message box.
				cmb = new CustomMessageBox()
				{
					Caption = App.Current.Model.Core.Cartridge.Name,
					//Message = wmb.Text,
					Content = new Controls.WherigoMessageBoxContentControl() { MessageBox = wmb },
					LeftButtonContent = wmb.FirstButtonLabel ?? "OK",
					RightButtonContent = wmb.SecondButtonLabel
				};

				// Registers events.
				RegisterEventHandlers(cmb);

				// Adds the pair to the dictionary.
				_WherigoMessageBoxes.Add(cmb, wmb);
			}

			return cmb;
		}
        public Task<bool> ShowDialogBox(string caption, string message, string leftbuttonContent, string rightButtonContent, Func<Task> leftButtonAction, Func<Task> rightButtonAction)
        {
            var messagebox = new CustomMessageBox()
            {
                Caption = caption,
                Message = message,
                LeftButtonContent = leftbuttonContent,
                RightButtonContent = rightButtonContent
            };

            var tcs = new TaskCompletionSource<bool>();
            messagebox.Dismissed += async (s, e) =>
            {
                switch (e.Result)
                {
                    case CustomMessageBoxResult.LeftButton:
                         await leftButtonAction();
                        tcs.SetResult(true);
                        break;
                    case CustomMessageBoxResult.RightButton:
                        await rightButtonAction();

                        tcs.SetResult(true);
                        break;
                    case CustomMessageBoxResult.None:

                        tcs.SetResult(false);
                        break;
                };
            };

            messagebox.Show();

            return tcs.Task;
        }
        public override void Login(LoginConfig config) {
            var prompt = new CustomMessageBox {
                Caption = config.Title,
                Message = config.Message,
                LeftButtonContent = config.OkText,
                RightButtonContent = config.CancelText
            };

            var txtUser = new PhoneTextBox {
                Hint = config.LoginPlaceholder,
                Text = config.LoginValue ?? String.Empty
            };
            var txtPass = new PasswordBox();
            var stack = new StackPanel();
            stack.Children.Add(txtUser);
            stack.Children.Add(txtPass);
            prompt.Content = stack;

            prompt.Dismissed += (sender, args) => config.OnResult(new LoginResult(
                txtUser.Text, 
                txtPass.Password, 
                args.Result == CustomMessageBoxResult.LeftButton
            ));
            this.Dispatch(prompt.Show);
        }
        //添加分类
        private void appbar_buttonAdd_Click(object sender, EventArgs e)
        {
            string kind = pivot.SelectedIndex > 0 ? "收入" : "支出";
            TextBox txtBox = new TextBox();
            CustomMessageBox msgBox = new CustomMessageBox()
            {
                Caption = "添加" + kind + "分类",
                LeftButtonContent = "保存",
                RightButtonContent = "取消",
                Content = txtBox
            };

            msgBox.Dismissing += (s1, e1) =>
            {
                switch(e1.Result)
                {
                    case CustomMessageBoxResult.LeftButton:
                        SaveCategory(txtBox.Text.Trim());
                        FreshList();
                        break;
                    case CustomMessageBoxResult.RightButton:
                        break;
                    case CustomMessageBoxResult.None:
                        break;
                    default: break;
                }
            };
            msgBox.Show();
        }
Example #15
0
        private void appbar_buttonDelete_Click(object sender, EventArgs e)
        {
            CustomMessageBox msgBox = new CustomMessageBox()
            {
                Caption = "删除流水",
                Message = "确定要删除这条流水吗?",
                LeftButtonContent = "确定",
                RightButtonContent = "取消"
            };

            msgBox.Dismissing += (s1, e1) =>
            {
                switch (e1.Result)
                {
                    case CustomMessageBoxResult.LeftButton:
                        App.voucherHelper.Remove(item);
                        App.voucherHelper.SaveToFile();
                        //删掉就相当于转回去
                        App.accountHelper.UpdateBalanceTrans(item.Account2, item.Account1, item.Money);
                        App.accountHelper.SaveToFile();
                        NavigationService.GoBack();
                        break;
                    case CustomMessageBoxResult.RightButton:
                        break;
                    case CustomMessageBoxResult.None:
                        break;
                    default: break;
                }
            };
            msgBox.Show();    
        }
Example #16
0
        public MainPage()
        {
            InitializeComponent();

            messageBox = new CustomMessageBox()
            {
                Message = "Приложение может использовать данные о вашем местоположении для отображения их на карте (эти данные никуда не передаются и не хранятся). Вы можете отключить это в настройках программы.",
                Caption = "Разрешить использовать сведения о местоположении?",
                LeftButtonContent = "Разрешить",
                RightButtonContent = "Запретить",
            };

            messageBox.Dismissed += (s1, e1) =>
            {
                switch (e1.Result)
                {
                    case CustomMessageBoxResult.LeftButton:
                        Settings.IsNavigationEnabled = true;
                        break;
                    case CustomMessageBoxResult.RightButton:
                    case CustomMessageBoxResult.None:
                        Settings.IsNavigationEnabled = false;
                        break;
                    default:
                        break;
                }
            };

            this.Loaded += (s, e) =>
            {
                if(!IsolatedStorageSettings.ApplicationSettings.Contains("IsNavigationEnabled"))
                    messageBox.Show();
            };
        }
Example #17
0
        internal static void CheckForPreviousException(bool isFirstRun)
        {
            try
            {
                string contents = null;
                using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    if (store.FileExists(filename))
                    {
                        using (TextReader reader = new StreamReader(store.OpenFile(filename, FileMode.Open, FileAccess.Read, FileShare.None)))
                        {
                            contents = reader.ReadToEnd();
                        }
                        SafeDeleteFile(store);
                    }
                }

                if (contents != null)
                {
                    string messageBoxText = null;
                    if (isFirstRun)
                        messageBoxText = "An unhandled error occurred the last time you ran this application. Would you like to send an email to report it?";
                    else
                        messageBoxText = "An unhandled error has just occurred. Would you like to send an email to report it?";

                    CustomMessageBox messageBox = new CustomMessageBox()
                    {
                        Caption = "Error Report",
                        Message = messageBoxText,
                        LeftButtonContent = "yes",
                        RightButtonContent = "no",
                        IsFullScreen = false
                    };

                    messageBox.Dismissed += (s1, e1) =>
                    {
                        switch (e1.Result)
                        {
                            case CustomMessageBoxResult.LeftButton:
                                FeedbackHelper.Default.Feedback(contents, true);

                                SafeDeleteFile(IsolatedStorageFile.GetUserStoreForApplication());

                                break;
                            default:
                                break;
                        }
                    };

                    messageBox.Show();
                }
            }
            catch (Exception)
            {
            }
            finally
            {
                SafeDeleteFile(IsolatedStorageFile.GetUserStoreForApplication());
            }
        }
Example #18
0
        public void ShowDialogBox(string caption, string message, string leftbuttonContent, string rightButtonContent, Action leftButtonAction, Action rightButtonAction)
        {
            var messagebox = new CustomMessageBox()
            {
                Caption = caption,
                Message = message,
                LeftButtonContent = leftbuttonContent,
                RightButtonContent = rightButtonContent
            };

            messagebox.Dismissed += (s,e) =>
            {
                switch (e.Result)
                {
                    case CustomMessageBoxResult.LeftButton:
                        leftButtonAction();
                        break;
                    case CustomMessageBoxResult.RightButton:
                        rightButtonAction();
                        break;
                    case CustomMessageBoxResult.None:
                        break;
                };
            };

            messagebox.Show();
        }
Example #19
0
        private void Use_Zip_Code(object sender, System.Windows.RoutedEventArgs e)
        {
            TextBox textBox = new TextBox();
            // restrict input to digits:
            InputScope inputScope = new InputScope();
            InputScopeName inputScopeName = new InputScopeName();
            inputScopeName.NameValue = InputScopeNameValue.Digits;
            inputScope.Names.Add(inputScopeName);
            textBox.InputScope = inputScope;

            CustomMessageBox messageBox = new CustomMessageBox()
            {
                Message = "Enter your US zip code:",
                LeftButtonContent = "okay",
                RightButtonContent = "cancel",
                Content = textBox
            };
            messageBox.Loaded += (a, b) =>
            {
                textBox.Focus();
            };
            messageBox.Show();
            messageBox.Dismissed += (s, args) =>
            {
                if (args.Result == CustomMessageBoxResult.LeftButton)
                {
                    if (textBox.Text.Length >= 5)
                    {
                        geocodeUsingString(textBox.Text);
                    }
                }
            };
        }
        //添加商家
        private void appbar_buttonAdd_Click(object sender, EventArgs e)
        {
            TextBox txtBox = new TextBox();
            CustomMessageBox msgBox = new CustomMessageBox()
            {
                Caption = "添加商家",
                LeftButtonContent = "保存",
                RightButtonContent = "取消",
                Content = txtBox
            };

            msgBox.Dismissing += (s1, e1) =>
            {
                switch (e1.Result)
                {
                    case CustomMessageBoxResult.LeftButton:
                        SaveStore(txtBox.Text.Trim());
                        StoreListBox.ItemsSource = Common.GetAllStore();
                        break;
                    case CustomMessageBoxResult.RightButton:
                        break;
                    case CustomMessageBoxResult.None:
                        break;
                    default: break;
                }
            };
            msgBox.Show();
        }
Example #21
0
        void CreateTaskList_Click(object sender, EventArgs e)
        {
            CustomMessageBox messageBox = new CustomMessageBox()
            {
                Caption = "Create tasklist?",
                Message = "Give a name of a new list.",
                LeftButtonContent = "OK",
                RightButtonContent = "Cancel",
                ContentTemplate = (DataTemplate)Resources["CreateTaskListContentTemplate"]
            };

            messageBox.Dismissed += (s1, e1) =>
                {
                    switch (e1.Result)
                    {
                        case CustomMessageBoxResult.LeftButton:
                        {
                            if (_vm.CreateTaskListCommand.CanExecute(null))
                            {
                                _vm.CreateTaskListCommand.Execute(null);
                            }
                            break;
                        }
                    }
                };
            messageBox.Show();
        }
 public Task<PhotoSelectionModeEnum> SelectMode()
 {
     var taskSource = new TaskCompletionSource<PhotoSelectionModeEnum>();
     var messageBox = new CustomMessageBox
         {
             Caption = "Photo selection",
             Message = "Specify the source of the photos please.",
             LeftButtonContent = "My photos",
             RightButtonContent = "Astral photos"
         };
     messageBox.Dismissed += (s, e) =>
         {
             switch (e.Result)
             {
                 case CustomMessageBoxResult.LeftButton:
                     taskSource.TrySetResult(PhotoSelectionModeEnum.MyPhotos);
                     break;
                 case CustomMessageBoxResult.RightButton:
                     taskSource.TrySetResult(PhotoSelectionModeEnum.BuiltinPhotos);
                     break;
                 default:
                     taskSource.TrySetResult(PhotoSelectionModeEnum.None);
                     break;
             }
         };
     messageBox.Show();
     return taskSource.Task;
 }
 public override void ActionSheet(ActionSheetConfig config) {
     var sheet = new CustomMessageBox {
         Caption = config.Title,
         IsLeftButtonEnabled = false,
         IsRightButtonEnabled = false
     };
     var list = new ListBox {
         FontSize = 36,
         Margin = new Thickness(12.0),
         SelectionMode = SelectionMode.Single,
         ItemsSource = config.Options
             .Select(x => new TextBlock {
                 Text = x.Text,
                 Margin = new Thickness(0.0, 12.0, 0.0, 12.0),
                 DataContext = x
             })
     };
     list.SelectionChanged += (sender, args) => sheet.Dismiss();
     sheet.Content = list;
     sheet.Dismissed += (sender, args) => {
         var txt = (TextBlock)list.SelectedValue;
         var action = (ActionSheetOption)txt.DataContext;
         if (action.Action != null)
             action.Action();
     };
     this.Dispatch(sheet.Show);
 }
        public static DialogResult Show(string message, string type)
        {
            msgForm = new CustomMessageBox();
            msgForm.txtMessage.Text = message;
            msgForm.ActiveControl = msgForm.btnOk;

            if (type.Equals(Constant.MSG_ERROR))
            {
                msgForm.txtMessage.ForeColor = Color.Red;
                msgForm.btnCancel.Visible = false;
            }
            else if (type.Equals(Constant.MSG_WARNING))
            {
                msgForm.txtMessage.ForeColor = Color.Black;
                msgForm.btnCancel.Visible = true;
            }
            else
            {
                msgForm.txtMessage.ForeColor = Color.Black;
                msgForm.btnOk.Visible = false;
                msgForm.btnCancel.Visible = false;
                msgForm.lblCounter.Visible = true;
                msgForm.countDownTimer.Start();
            }
            msgForm.ShowDialog();
            return result;
        }
Example #25
0
        private void btConfirmar_Click(object sender, RoutedEventArgs e)
        {
            if (txtQnt.Text == "")
            {
                cmb = new CustomMessageBox("Campos obrigatórios: Quantidade");
                cmb.ShowDialog();
                return;
            }
            else
            {
                try
                {
                    info.cod_prod_item = Int32.Parse(((DataRowView)dtGridProd.SelectedItem).Row[0].ToString());
                    info.vlr_ven_item = ((DataRowView)dtGridProd.SelectedItem).Row[3].ToString().Replace(",", ".");
                    info.qtd_item = Int32.Parse(txtQnt.Text);
                    info.est_item = "Em aberto";

                    DataTable dtitem = opr.selectItemCombyProd(info);
                    if (dtitem.Rows.Count > 0)
                    {
                        info.qtd_item = int.Parse(dtitem.Rows[0][2].ToString()) + info.qtd_item;
                        int row = opr.updateItemCom(info);
                        if (row != 0)
                        {
                            cmb = new CustomMessageBox("Item cadastrado com sucesso!");
                            cmb.ShowDialog();
                            this.Close();
                        }
                        else
                        {
                            cmb = new CustomMessageBox("Erro na inserção!");
                            cmb.ShowDialog();
                        }
                    }
                    else
                    {


                        int rows = opr.insertItemCom(info);
                        if (rows != 0)
                        {
                            cmb = new CustomMessageBox("Item cadastrado com sucesso!");
                            cmb.ShowDialog();
                            this.Close();
                        }
                        else
                        {
                            cmb = new CustomMessageBox("Erro na inserção!");
                            cmb.ShowDialog();
                        }
                    }
                }
                catch
                {
                    cmb = new CustomMessageBox("Erro interno do SQL.");
                    cmb.ShowDialog();
                }
            }
        }
Example #26
0
        private void btCalcular_Click(object sender, RoutedEventArgs e)
        {
            DataTable dtitem = new DataTable();
            try 
            { 
                dtitem = opr.selectItemCombyCom(info);
                if (dtitem.Rows.Count > 0)
                {
                    double totalcom = 0;
                    for (int i = 0; i <= dtitem.Rows.Count-1; i++)
                    {
                        if (dtitem.Rows[i][4].ToString() == "Em aberto")
                        {
                            cmb = new CustomMessageBox("Existem itens em aberto na comanda. Acuse a prontidão e tente novamente.");
                            cmb.ShowDialog();
                            return;
                        }
                        double vlr = 0;
                        vlr = double.Parse(dtitem.Rows[i][2].ToString()) * double.Parse(dtitem.Rows[i][3].ToString());
                        totalcom = totalcom + vlr;
                    }
                    info.vlrPag_com = totalcom.ToString();
                }
            }
            catch
            {
                cmb = new CustomMessageBox("Erro ao calcular total.");
                cmb.ShowDialog();
                return;
            }
            try
            {
                dtitem.Clear();
                dtitem = opr.PorcFunc(info);
                if (dtitem.Rows.Count > 0)
                {
                    info.comissao_com = (double.Parse(dtitem.Rows[0][0].ToString()) / 100 * double.Parse(info.vlrPag_com)).ToString();
                }
                else
                {
                    info.comissao_com = "0";
                }
            }
            catch
            {
                cmb = new CustomMessageBox("Erro ao aplicar porcentagem de serviço.");
                cmb.ShowDialog();
                return;
            }

            info.dataPag_com = DateTime.Now;
            info.est_com = "Fechada";
            btConfirma.IsEnabled = true;
            txtComissão.Text = info.comissao_com.Replace(",", ".");
            txtTotal.Text = info.vlrPag_com.Replace(",", ".");
            btConfirma.IsEnabled = true;
            cmb = new CustomMessageBox("Cálculo feito. Pressione Confirmar.");
            cmb.ShowDialog();
        }
 public static void ShowError(string message, string caption)
 {
     var box = new CustomMessageBox();
     box.Button_OK.Visibility = Visibility.Visible;
     box.TextBlock_Message.Text = message;
     box.Title = caption;
     box.ShowDialog();
 }
        private void AdvancedMessageBox_Click(object sender, RoutedEventArgs e)
        {
            HyperlinkButton hyperlinkButton = new HyperlinkButton()
            {
                Content = "Más información.",
                HorizontalAlignment = HorizontalAlignment.Left,
                NavigateUri = new Uri("http://javiersuarezruiz.wordpress.com/", UriKind.Absolute)
            };

            TiltEffect.SetIsTiltEnabled(hyperlinkButton, true);

            ListPicker listPicker = new ListPicker()
            {
                Header = "Recordar en:",
                ItemsSource = new string[] { "5 minutos", "10 minutos", "15 minutos" }
            };

            StackPanel stackPanel = new StackPanel();
            stackPanel.Children.Add(hyperlinkButton);
            stackPanel.Children.Add(listPicker);

            CustomMessageBox messageBox = new CustomMessageBox()
            {
                Title = "Recordatorio",
                Caption = "Programar Windows Phone",
                Message = "Realizar ejemplo del control CustomMessageBox",
                Content = stackPanel,
                LeftButtonContent = "Aceptar",
                RightButtonContent = "Cancelar",
                IsFullScreen = (bool)FullScreenCheckBox.IsChecked
            };

            messageBox.Dismissing += (s1, e1) =>
            {
                if (listPicker.ListPickerMode == ListPickerMode.Expanded)
                {
                    e1.Cancel = true;
                }
            };

            messageBox.Dismissed += (s2, e2) =>
            {
                switch (e2.Result)
                {
                    case CustomMessageBoxResult.LeftButton:
                        // Acción.
                        break;
                    case CustomMessageBoxResult.RightButton:
                    case CustomMessageBoxResult.None:
                        // Acción.
                        break;
                    default:
                        break;
                }
            };

            messageBox.Show();
        }
 public override void Confirm(ConfirmConfig config) {
     var confirm = new CustomMessageBox {
         Caption = config.Title,
         Message = config.Message,
         LeftButtonContent = config.OkText,
         RightButtonContent = config.CancelText
     };
     confirm.Dismissed += (sender, args) => config.OnConfirm(args.Result == CustomMessageBoxResult.LeftButton);
     this.Dispatch(confirm.Show);
 }
Example #30
0
        private void btRemProd_Click(object sender, RoutedEventArgs e)
        {
            if (dtGriditCom.SelectedItem != null)
            {
                CustomMessageBox cmb = new CustomMessageBox("Tem certeza que deseja excluir ? ", "Atenção", "YesNo");
                cmb.ShowDialog();
                if (cmb.DialogResult.HasValue && cmb.DialogResult.Value)
                {
                    try
                    {
                        int ID = Int32.Parse(((DataRowView)dtGriditCom.SelectedItem).Row[0].ToString());
                        int ID2 = Int32.Parse(((DataRowView)dtGriditCom.SelectedItem).Row[5].ToString());

                        info.cod_com_item = ID;
                        info.cod_prod_item = ID2;
                        if (ID.ToString() == "" && ID2.ToString()=="")
                        {
                            cmb = new CustomMessageBox("Selecione um item para excluir.");
                            cmb.ShowDialog();
                        }
                        else
                        {

                            int rows = opr.deleteItemCom(info);
                            if (rows != 0)
                            {
                                cmb = new CustomMessageBox("Item excluído com sucesso!");
                                cmb.ShowDialog();
                                dtGriditCom.DataContext = opr.selectItemCombyCom(info);
                            }
                            else
                            {
                                cmb = new CustomMessageBox("Erro na operação");
                                cmb.ShowDialog();
                            }
                        }
                    }
                    catch
                    {
                        cmb = new CustomMessageBox("Erro interno no SQL.");
                        cmb.ShowDialog();
                    }
                }
                else
                {
                    return;
                }
            }
            else
            {
                cmb = new CustomMessageBox("Não há itens para excluir.");
                cmb.ShowDialog();
                return;
            }
}
        public void Message(string type, string msg)
        {
            CustomMessageBox msgBox = new CustomMessageBox(type, msg);

            msgBox.ShowDialog();
        }
        private async void SaveBtn_Click(object sender, EventArgs e)
        {
            var messageBox = new CustomMessageBox();

            if (string.IsNullOrWhiteSpace(MovieTitle.Text) || MovieTitle.Text.Length < 4)
            {
                messageBox.Show("The title field requires 4 letters!", "error");
                return;
            }

            if (string.IsNullOrWhiteSpace(Description.Text) || Description.Text.Length < 5)
            {
                messageBox.Show("The description field requires 5 letters!", "error");
                return;
            }

            if (string.IsNullOrWhiteSpace(Cast.Text) || Cast.Text.Length < 15)
            {
                messageBox.Show("The cast field requires 15 letters!", "error");
                return;
            }
            if (string.IsNullOrWhiteSpace(ImageLink.Text) || !ImageLink.Text.Contains(".jpg"))
            {
                messageBox.Show("Enter a valid '.jpg' image link!", "error");
                return;
            }
            if (string.IsNullOrWhiteSpace(TrailerLink.Text))
            {
                messageBox.Show("Enter a trailer id", "error");
                return;
            }

            if (string.IsNullOrWhiteSpace(Rating.Text) || !decimal.TryParse(Rating.Text, out decimal n))
            {
                messageBox.Show("Enter a valid rating (0-10)!", "error");
                return;
            }
            decimal rating = decimal.Parse(Rating.Text);

            if (rating < 0 || rating > 10)
            {
                messageBox.Show("Enter a valid rating (0-10)!", "error");
                return;
            }

            if (string.IsNullOrWhiteSpace(Price.Text) || !decimal.TryParse(Price.Text, out decimal m))
            {
                messageBox.Show("Enter a valid price (1-200)!", "error");
                return;
            }
            decimal price = decimal.Parse(Price.Text);

            if (price < 1 || price > 200)
            {
                messageBox.Show("Enter a valid price (1-200)!", "error");
                return;
            }
            if (Year.Value < Year.Minimum || Year.Value > Year.Maximum)
            {
                messageBox.Show("Enter a valid year (1800-2025)!", "error");
                return;
            }
            var hours = Duration.Value.Hour;

            if (hours < 0 || hours > 4)
            {
                messageBox.Show("Enter a valid duration (up to 5 hours)!", "error");
                return;
            }

            if (string.IsNullOrWhiteSpace(Genre.Text) || Genre.Text.Length < 4)
            {
                messageBox.Show("The genre field requires 4 letters!", "error");
                return;
            }

            Model.Requests.InsertMovieRequest request = new Model.Requests.InsertMovieRequest()
            {
                Title       = MovieTitle.Text,
                Year        = (int)Year.Value,
                Duration    = Duration.Value.ToString("HH:mm"),
                Rating      = decimal.Parse(Rating.Text),
                Description = Description.Text,
                Cast        = Cast.Text,
                ImageLink   = ImageLink.Text,
                Standalone  = Standalone.Checked,
                Price       = decimal.Parse(Price.Text),
                TrailerLink = $"https://www.youtube.com/embed/{TrailerLink.Text}",
                Genre       = Genre.Text
            };

            if (_movieId.HasValue)
            {
                await _apiService.Update <Model.Movie>(_movieId, request);
            }
            else
            {
                await _apiService.Insert <Model.Movie>(request);
            }

            this.Close();
            foreach (Form frm in _menuForm.MdiChildren)
            {
                frm.Close();
            }
            MoviesForm form = new MoviesForm {
                MdiParent = _menuForm,
                Dock      = DockStyle.Fill
            };

            form.Show();
            if (_movieId.HasValue)
            {
                messageBox.Show("Movie updated successfully!", "success");
            }
            else
            {
                messageBox.Show("Movie added successfully!", "success");
            }
        }
        private void Joystick_Load(object sender, EventArgs e)
        {
            try
            {
                var joysticklist = Joystick.getDevices();

                foreach (DeviceInstance device in joysticklist)
                {
                    CMB_joysticks.Items.Add(device.ProductName.TrimUnPrintable());
                }
            }
            catch
            {
                CustomMessageBox.Show("Error geting joystick list: do you have the directx redist installed?");
                this.Close();
                return;
            }

            if (CMB_joysticks.Items.Count > 0 && CMB_joysticks.SelectedIndex == -1)
            {
                CMB_joysticks.SelectedIndex = 0;
            }

            try
            {
                if (Settings.Instance.ContainsKey("joystick_name") && Settings.Instance["joystick_name"].ToString() != "")
                {
                    CMB_joysticks.Text = Settings.Instance["joystick_name"].ToString();
                }
            }
            catch
            {
            }

            CMB_CH1.DataSource = (Enum.GetValues(typeof(Joystick.joystickaxis)));
            CMB_CH2.DataSource = (Enum.GetValues(typeof(Joystick.joystickaxis)));
            CMB_CH3.DataSource = (Enum.GetValues(typeof(Joystick.joystickaxis)));
            CMB_CH4.DataSource = (Enum.GetValues(typeof(Joystick.joystickaxis)));
            CMB_CH5.DataSource = (Enum.GetValues(typeof(Joystick.joystickaxis)));
            CMB_CH6.DataSource = (Enum.GetValues(typeof(Joystick.joystickaxis)));
            CMB_CH7.DataSource = (Enum.GetValues(typeof(Joystick.joystickaxis)));
            CMB_CH8.DataSource = (Enum.GetValues(typeof(Joystick.joystickaxis)));

            try
            {
                if (Settings.Instance.ContainsKey("joy_elevons"))
                {
                    CHK_elevons.Checked = bool.Parse(Settings.Instance["joy_elevons"].ToString());
                }
            }
            catch
            {
            } // IF 1 DOESNT EXIST NONE WILL

            var tempjoystick = new Joystick();

            label14.Text += " " + MainV2.comPort.MAV.cs.firmware.ToString();

            for (int a = 1; a <= 8; a++)
            {
                var config = tempjoystick.getChannel(a);

                findandsetcontrol("CMB_CH" + a, config.axis.ToString());
                findandsetcontrol("revCH" + a, config.reverse.ToString());
                findandsetcontrol("expo_ch" + a, config.expo.ToString());
            }

            if (MainV2.joystick != null && MainV2.joystick.enabled)
            {
                timer1.Start();
                BUT_enable.Text = "Disable";
            }

            startup = false;
        }
Example #34
0
        /// <summary>
        /// Do full update - get firmware from internet
        /// </summary>
        /// <param name="temp"></param>
        /// <param name="historyhash"></param>
        public bool update(string comport, software temp, string historyhash)
        {
            BoardDetect.boards board = BoardDetect.boards.none;

            try
            {
                updateProgress(-1, "Detecting Board Version");

                board = BoardDetect.DetectBoard(comport);

                if (board == BoardDetect.boards.none)
                {
                    CustomMessageBox.Show("Cant detect your Board version. Please check your cabling");
                    return(false);
                }

                int apmformat_version = -1; // fail continue

                if (board != BoardDetect.boards.px4 && board != BoardDetect.boards.px4v2)
                {
                    try
                    {
                        apmformat_version = BoardDetect.decodeApVar(comport, board);
                    }
                    catch { }

                    if (apmformat_version != -1 && apmformat_version != temp.k_format_version)
                    {
                        if (DialogResult.No == CustomMessageBox.Show("Epprom changed, all your setting will be lost during the update,\nDo you wish to continue?", "Epprom format changed (" + apmformat_version + " vs " + temp.k_format_version + ")", MessageBoxButtons.YesNo))
                        {
                            CustomMessageBox.Show("Please connect and backup your config in the configuration tab.");
                            return(false);
                        }
                    }
                }


                log.Info("Detected a " + board);

                updateProgress(-1, "Detected a " + board);

                string baseurl = "";
                if (board == BoardDetect.boards.b2560)
                {
                    baseurl = temp.url2560.ToString();
                }
                else if (board == BoardDetect.boards.b1280)
                {
                    baseurl = temp.url.ToString();
                }
                else if (board == BoardDetect.boards.b2560v2)
                {
                    baseurl = temp.url2560_2.ToString();
                }
                else if (board == BoardDetect.boards.px4)
                {
                    baseurl = temp.urlpx4v1.ToString();
                }
                else if (board == BoardDetect.boards.px4v2)
                {
                    baseurl = temp.urlpx4v2.ToString();
                }
                else
                {
                    CustomMessageBox.Show("Invalid Board Type");
                    return(false);
                }

                if (historyhash != "")
                {
                    baseurl = getUrl(historyhash, baseurl);
                }

                log.Info("Using " + baseurl);

                // Create a request using a URL that can receive a post.
                WebRequest request = WebRequest.Create(baseurl);
                request.Timeout = 10000;
                // Set the Method property of the request to POST.
                request.Method = "GET";
                // Get the request stream.
                Stream dataStream; //= request.GetRequestStream();
                // Get the response.
                WebResponse response = request.GetResponse();
                // Display the status.
                log.Info(((HttpWebResponse)response).StatusDescription);
                // Get the stream containing content returned by the server.
                dataStream = response.GetResponseStream();

                long bytes   = response.ContentLength;
                long contlen = bytes;

                byte[] buf1 = new byte[1024];

                FileStream fs = new FileStream(Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar + @"firmware.hex", FileMode.Create);

                updateProgress(0, "Downloading from Internet");

                dataStream.ReadTimeout = 30000;

                while (dataStream.CanRead)
                {
                    try
                    {
                        updateProgress(50, "Downloading from Internet");
                    }
                    catch { }
                    int len = dataStream.Read(buf1, 0, 1024);
                    if (len == 0)
                    {
                        break;
                    }
                    bytes -= len;
                    fs.Write(buf1, 0, len);
                }

                fs.Close();
                dataStream.Close();
                response.Close();

                updateProgress(100, "Downloaded from Internet");
                log.Info("Downloaded");
            }
            catch (Exception ex) { updateProgress(50, "Failed download"); CustomMessageBox.Show("Failed to download new firmware : " + ex.ToString()); return(false); }

            MissionPlanner.Utilities.Tracking.AddFW(temp.name, board.ToString());

            return(UploadFlash(comport, Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar + @"firmware.hex", board));
        }
Example #35
0
        /// <summary>
        /// upload to arduino standalone
        /// </summary>
        /// <param name="filename"></param>
        /// <param name="board"></param>
        public bool UploadFlash(string comport, string filename, BoardDetect.boards board)
        {
            if (board == BoardDetect.boards.px4 || board == BoardDetect.boards.px4v2)
            {
                return(UploadPX4(filename));
            }

            byte[] FLASH = new byte[1];
            try
            {
                updateProgress(0, "Reading Hex File");
                using (StreamReader sr = new StreamReader(filename))
                {
                    FLASH = readIntelHEXv2(sr);
                }
                log.InfoFormat("\n\nSize: {0}\n\n", FLASH.Length);
            }
            catch (Exception ex)
            {
                updateProgress(0, "Failed read HEX");
                CustomMessageBox.Show("Failed to read firmware.hex : " + ex.Message);
                return(false);
            }
            IArduinoComms port = new ArduinoSTK();

            if (board == BoardDetect.boards.b1280)
            {
                if (FLASH.Length > 126976)
                {
                    CustomMessageBox.Show("Firmware is to big for a 1280, Please upgrade your hardware!!");
                    return(false);
                }
                //port = new ArduinoSTK();
                port.BaudRate = 57600;
            }
            else if (board == BoardDetect.boards.b2560 || board == BoardDetect.boards.b2560v2)
            {
                port = new ArduinoSTKv2
                {
                    BaudRate = 115200
                };
            }
            port.DataBits  = 8;
            port.StopBits  = System.IO.Ports.StopBits.One;
            port.Parity    = System.IO.Ports.Parity.None;
            port.DtrEnable = true;

            try
            {
                port.PortName = comport;

                port.Open();

                if (port.connectAP())
                {
                    log.Info("starting");
                    updateProgress(0, "Uploading " + FLASH.Length + " bytes to Board: " + board);

                    // this is enough to make ap_var reset
                    //port.upload(new byte[256], 0, 2, 0);

                    port.Progress += updateProgress;

                    if (!port.uploadflash(FLASH, 0, FLASH.Length, 0))
                    {
                        if (port.IsOpen)
                        {
                            port.Close();
                        }
                        throw new Exception("Upload failed. Lost sync. Try Arduino!!");
                    }

                    port.Progress -= updateProgress;

                    updateProgress(100, "Upload Complete");

                    log.Info("Uploaded");

                    int   start  = 0;
                    short length = 0x100;

                    byte[] flashverify = new byte[FLASH.Length + 256];

                    updateProgress(0, "Verify Firmware");

                    while (start < FLASH.Length)
                    {
                        updateProgress((int)((start / (float)FLASH.Length) * 100), "Verify Firmware");
                        port.setaddress(start);
                        //log.Info("Downloading " + length + " at " + start);
                        port.downloadflash(length).CopyTo(flashverify, start);
                        start += length;
                    }

                    for (int s = 0; s < FLASH.Length; s++)
                    {
                        if (FLASH[s] != flashverify[s])
                        {
                            CustomMessageBox.Show("Upload succeeded, but verify failed: exp " + FLASH[s].ToString("X") + " got " + flashverify[s].ToString("X") + " at " + s);
                            port.Close();
                            return(false);
                        }
                    }

                    updateProgress(100, "Verify Complete");
                }
                else
                {
                    updateProgress(0, "Failed upload");
                    CustomMessageBox.Show("Communication Error - no connection");
                }
                port.Close();

                try
                {
                    ((SerialPort)port).Open();
                }
                catch { }

                //CustomMessageBox.Show("1. If you are updating your firmware from a previous version, please verify your parameters are appropriate for the new version.\n2. Please ensure your accelerometer is calibrated after installing or re-calibrated after updating the firmware.");

                try
                {
                    ((SerialPort)port).Close();
                }
                catch { }

                updateProgress(100, "Done");
            }
            catch (Exception ex)
            {
                updateProgress(0, "Failed upload");
                CustomMessageBox.Show("Check port settings or Port in use? " + ex);
                try
                {
                    port.Close();
                }
                catch { }
                return(false);
            }
            MainV2.comPort.giveComport = false;
            return(true);
        }
Example #36
0
        private void removeImageViewer()
        {
            //    VisitRepository visitRepo = new VisitRepository();
            //    VisitModel v = visitRepo.GetById(IVLVariables.ActiveVisitID);
            //    v.NoOfImages = v.NoOfImages - thumbnail_FLP.SelectedThumbnailFileNames.Count;
            //    visitRepo.Update(v);
            List <int>    removedImageIds      = new List <int>();
            List <string> removeImageFilePaths = new List <string>();

            foreach (var item in thumbnail_FLP.SelectedThumbnailFileNames)
            {
                foreach (var item1 in thumbnail_FLP.Controls)
                {
                    if (item1 is ImageViewer)
                    {
                        ImageViewer imgView = item1 as ImageViewer;
                        if (item.Equals(imgView.ImageLocation))
                        {
                            if (File.Exists(imgView.ImageLocation))//This
                            {
                                //ImageModel imgVal = imageRepo.GetById(imgView.ImageID);
                                //imgVal.HideShowRow = true;
                                //imageRepo.Update(imgVal);
                                if (image_names.Contains(imgView.ImageLocation))
                                {
                                    image_names.Remove(imgView.ImageLocation);
                                }
                                removedImageIds.Add(imgView.ImageID);
                                removeImageFilePaths.Add(imgView.ImageLocation);
                                thumbnail_FLP.Controls.Remove(item1 as Control);
                            }
                            else
                            {
                                CustomMessageBox.Show(DeletedImageMsg, DeletedImageHeader, CustomMessageBoxButtons.OK, CustomMessageBoxIcon.Warning);
                                return;
                            }
                        }
                    }
                }
            }
            Dictionary <string, object> img = new Dictionary <string, object>();

            img.Add("ImageIds", removedImageIds);
            img.Add("ImageLocations", removeImageFilePaths);
            deleteimgs(img);
            this.thumbnail_FLP.selectedThumbnails.Clear();
            this.thumbnail_FLP.SelectedThumbnailFileNames.Clear();
            thumbnail_FLP.TotalThumbnails = this.thumbnail_FLP.Controls.Count;
            ImageViewer[] item2 = new ImageViewer[thumbnail_FLP.Controls.Count];//to update the items in thumbnail after deleting image.By Ashutosh 11-08-2017.
            for (int i = 0; i < thumbnail_FLP.Controls.Count; i++)
            {
                item2[i]       = thumbnail_FLP.Controls[i] as ImageViewer;
                item2[i].Index = item2.Length - i;
            }
            for (int i = 0; i < thumbnail_FLP.Controls.Count; i++)
            {
                item2[i] = thumbnail_FLP.Controls[i] as ImageViewer;
                if (i == 0)
                {
                    this.thumbnailSelection(item2[i]);
                    break;
                }
            }
            RefreshThumbNailImageName();
        }
Example #37
0
        /// <summary>
        /// Detect board version
        /// </summary>
        /// <param name="port"></param>
        /// <returns> boards enum value</returns>
        public static boards DetectBoard(string port)
        {
            SerialPort serialPort = new SerialPort();

            serialPort.PortName = port;

            if (!MainV2.MONO)
            {
                try
                {
                    // check the device reported productname
                    var ports = Win32DeviceMgmt.GetAllCOMPorts();

                    foreach (var item in ports)
                    {
                        log.InfoFormat("{0}: {1} - {2}", item.name, item.description, item.board);

                        //if (port.ToLower() == item.name.ToLower())
                        {
                            //USB\VID_0483&PID_DF11   -- stm32 bootloader

                            // new style bootloader
                            if (item.hardwareid.StartsWith(@"USB\VID_0483&PID_5740")) //USB\VID_0483&PID_5740&REV_0200)
                            {
                                if (item.board == "fmuv2" || item.board.ToLower() == "fmuv2-bl")
                                {
                                    log.Info("is a fmuv2");
                                    return(boards.px4v2);
                                }
                                if (item.board == "fmuv3" || item.board.ToLower() == "fmuv3-bl")
                                {
                                    log.Info("is a fmuv3");
                                    return(boards.px4v3);
                                }
                                if (item.board == "fmuv4" || item.board.ToLower() == "fmuv4-bl")
                                {
                                    log.Info("is a fmuv4");
                                    return(boards.px4v4);
                                }
                                if (item.board == "fmuv5" || item.board.ToLower() == "fmuv5-bl")
                                {
                                    log.Info("is a fmuv5");
                                }
                                if (item.board == "revo-mini" || item.board.ToLower() == "revo-mini-bl")
                                {
                                    log.Info("is a revo-mini");
                                    //return boards.revomini;
                                }
                                if (item.board == "mini-pix" || item.board.ToLower() == "mini-pix-bl")
                                {
                                    log.Info("is a mini-pix");
                                    //return boards.minipix;
                                }
                                if (item.board == "mindpx-v2" || item.board.ToLower() == "mindpx-v2-bl")
                                {
                                    log.Info("is a mindpx-v2");
                                    //return boards.mindpxv2;
                                }

                                chbootloader = item.board.ToLower().Replace("-bl", "");
                                return(boards.chbootloader);
                            }

                            // old style bootloader

                            if (item.board == "PX4 FMU v5.x")
                            {//USB\VID_26AC&PID_0032\0
                                log.Info("is a PX4 FMU v5.x (fmuv5)");
                                return(boards.fmuv5);
                            }

                            if (item.board == "PX4 FMU v4.x")
                            {
                                log.Info("is a px4v4 pixracer");
                                return(boards.px4v4);
                            }

                            if (item.board == "PX4 FMU v2.x")
                            {
                                CustomMessageBox.Show(Strings.PleaseUnplugTheBoardAnd);

                                DateTime DEADLINE = DateTime.Now.AddSeconds(30);

                                while (DateTime.Now < DEADLINE)
                                {
                                    string[] allports = SerialPort.GetPortNames();

                                    foreach (string port1 in allports)
                                    {
                                        log.Info(DateTime.Now.Millisecond + " Trying Port " + port1);
                                        try
                                        {
                                            using (var up = new Uploader(port1, 115200))
                                            {
                                                up.identify();
                                                Console.WriteLine(
                                                    "Found board type {0} boardrev {1} bl rev {2} fwmax {3} on {4}",
                                                    up.board_type,
                                                    up.board_rev, up.bl_rev, up.fw_maxsize, port1);

                                                if (up.fw_maxsize == 2080768 && up.board_type == 9 && up.bl_rev >= 5)
                                                {
                                                    log.Info("is a px4v3");
                                                    return(boards.px4v3);
                                                }
                                                else
                                                {
                                                    log.Info("is a px4v2");
                                                    return(boards.px4v2);
                                                }
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                            log.Error(ex);
                                        }
                                    }
                                }

                                log.Info("Failed to detect px4 board type");
                                return(boards.none);
                            }
                        }
                    }
                } catch { }

                ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_SerialPort"); // Win32_USBControllerDevice
                ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
                foreach (ManagementObject obj2 in searcher.Get())
                {
                    log.InfoFormat("-----------------------------------");
                    log.InfoFormat("Win32_USBDevice instance");
                    log.InfoFormat("-----------------------------------");

                    foreach (var item in obj2.Properties)
                    {
                        log.InfoFormat("{0}: {1}", item.Name, item.Value);
                    }


                    // check vid and pid
                    if (obj2.Properties["PNPDeviceID"].Value.ToString().Contains(@"USB\VID_2341&PID_0010"))
                    {
                        // check port name as well
                        if (obj2.Properties["Name"].Value.ToString().ToUpper().Contains(serialPort.PortName.ToUpper()))
                        {
                            log.Info("is a 2560-2");
                            return(boards.b2560v2);
                        }
                    }

                    if (obj2.Properties["PNPDeviceID"].Value.ToString().Contains(@"USB\VID_26AC&PID_0010"))
                    {
                        // check port name as well
                        //if (obj2.Properties["Name"].Value.ToString().ToUpper().Contains(serialPort.PortName.ToUpper()))
                        {
                            log.Info("is a px4");
                            return(boards.px4);
                        }
                    }

                    if (obj2.Properties["PNPDeviceID"].Value.ToString().Contains(@"USB\VID_26AC&PID_0032"))
                    {
                        // check port name as well
                        //if (obj2.Properties["Name"].Value.ToString().ToUpper().Contains(serialPort.PortName.ToUpper()))
                        {
                            log.Info("is a fmuv5");
                            return(boards.fmuv5);
                        }
                    }

                    // chibios or normal px4
                    if (obj2.Properties["PNPDeviceID"].Value.ToString().Contains(@"USB\VID_0483&PID_5740") || obj2.Properties["PNPDeviceID"].Value.ToString().Contains(@"USB\VID_26AC&PID_0011"))
                    {
                        CustomMessageBox.Show(Strings.PleaseUnplugTheBoardAnd);

                        DateTime DEADLINE = DateTime.Now.AddSeconds(30);

                        while (DateTime.Now < DEADLINE)
                        {
                            string[] allports = SerialPort.GetPortNames();

                            foreach (string port1 in allports)
                            {
                                log.Info(DateTime.Now.Millisecond + " Trying Port " + port1);
                                try
                                {
                                    using (var up = new Uploader(port1, 115200))
                                    {
                                        up.identify();
                                        Console.WriteLine(
                                            "Found board type {0} boardrev {1} bl rev {2} fwmax {3} on {4}",
                                            up.board_type,
                                            up.board_rev, up.bl_rev, up.fw_maxsize, port1);

                                        if (up.fw_maxsize == 2080768 && up.board_type == 9 && up.bl_rev >= 5)
                                        {
                                            log.Info("is a px4v3");
                                            return(boards.px4v3);
                                        }
                                        else if (up.fw_maxsize == 2080768 && up.board_type == 50 && up.bl_rev >= 5)
                                        {
                                            log.Info("is a fmuv5");
                                            return(boards.fmuv5);
                                        }
                                        else
                                        {
                                            log.Info("is a px4v2");
                                            return(boards.px4v2);
                                        }
                                    }
                                }
                                catch (Exception ex)
                                {
                                    log.Error(ex);
                                }
                            }
                        }

                        log.Info("Failed to detect px4 board type");
                        return(boards.none);
                    }

                    if (obj2.Properties["PNPDeviceID"].Value.ToString().Contains(@"USB\VID_26AC&PID_0021"))
                    {
                        log.Info("is a px4v3 X2.1");
                        return(boards.px4v3);
                    }

                    if (obj2.Properties["PNPDeviceID"].Value.ToString().Contains(@"USB\VID_26AC&PID_0012"))
                    {
                        log.Info("is a px4v4 pixracer");
                        return(boards.px4v4);
                    }

                    if (obj2.Properties["PNPDeviceID"].Value.ToString().Contains(@"USB\VID_26AC&PID_0013"))
                    {
                        log.Info("is a px4v4pro pixhawk 3 pro");
                        return(boards.px4v4pro);
                    }

                    if (obj2.Properties["PNPDeviceID"].Value.ToString().Contains(@"USB\VID_26AC&PID_0001"))
                    {
                        log.Info("is a px4v2 bootloader");
                        return(boards.px4v2);
                    }

                    if (obj2.Properties["PNPDeviceID"].Value.ToString().Contains(@"USB\VID_26AC&PID_0016"))
                    {
                        log.Info("is a px4v2 bootloader");
                        CustomMessageBox.Show(
                            "You appear to have a bootloader with a bad PID value, please update your bootloader.");
                        return(boards.px4v2);
                    }

                    //|| obj2.Properties["PNPDeviceID"].Value.ToString().Contains(@"USB\VID_26AC&PID_0012") || obj2.Properties["PNPDeviceID"].Value.ToString().Contains(@"USB\VID_26AC&PID_0013") || obj2.Properties["PNPDeviceID"].Value.ToString().Contains(@"USB\VID_26AC&PID_0014") || obj2.Properties["PNPDeviceID"].Value.ToString().Contains(@"USB\VID_26AC&PID_0015") || obj2.Properties["PNPDeviceID"].Value.ToString().Contains(@"USB\VID_26AC&PID_0016")

                    if (obj2.Properties["PNPDeviceID"].Value.ToString().Contains(@"USB\VID_27AC&PID_1140"))
                    {
                        log.Info("is a vrbrain 4.0 bootloader");
                        return(boards.vrbrainv40);
                    }

                    if (obj2.Properties["PNPDeviceID"].Value.ToString().Contains(@"USB\VID_27AC&PID_1145"))
                    {
                        log.Info("is a vrbrain 4.5 bootloader");
                        return(boards.vrbrainv45);
                    }

                    if (obj2.Properties["PNPDeviceID"].Value.ToString().Contains(@"USB\VID_27AC&PID_1150"))
                    {
                        log.Info("is a vrbrain 5.0 bootloader");
                        return(boards.vrbrainv50);
                    }

                    if (obj2.Properties["PNPDeviceID"].Value.ToString().Contains(@"USB\VID_27AC&PID_1151"))
                    {
                        log.Info("is a vrbrain 5.1 bootloader");
                        return(boards.vrbrainv51);
                    }

                    if (obj2.Properties["PNPDeviceID"].Value.ToString().Contains(@"USB\VID_27AC&PID_1152"))
                    {
                        log.Info("is a vrbrain 5.2 bootloader");
                        return(boards.vrbrainv52);
                    }

                    if (obj2.Properties["PNPDeviceID"].Value.ToString().Contains(@"USB\VID_27AC&PID_1154"))
                    {
                        log.Info("is a vrbrain 5.4 bootloader");
                        return(boards.vrbrainv54);
                    }

                    if (obj2.Properties["PNPDeviceID"].Value.ToString().Contains(@"USB\VID_27AC&PID_1910"))
                    {
                        log.Info("is a vrbrain core 1.0 bootloader");
                        return(boards.vrcorev10);
                    }

                    if (obj2.Properties["PNPDeviceID"].Value.ToString().Contains(@"USB\VID_27AC&PID_1351"))
                    {
                        log.Info("is a vrubrain 5.1 bootloader");
                        return(boards.vrubrainv51);
                    }

                    if (obj2.Properties["PNPDeviceID"].Value.ToString().Contains(@"USB\VID_27AC&PID_1352"))
                    {
                        log.Info("is a vrubrain 5.2 bootloader");
                        return(boards.vrubrainv52);
                    }
                }
            }
            else
            {
                // if its mono
                if ((int)DialogResult.Yes == CustomMessageBox.Show("Is this a APM 2+?", "APM 2+", MessageBoxButtons.YesNo))
                {
                    return(boards.b2560v2);
                }
                else
                {
                    if ((int)DialogResult.Yes ==
                        CustomMessageBox.Show("Is this a PX4/PIXHAWK/PIXRACER?", "PX4/PIXHAWK", MessageBoxButtons.YesNo))
                    {
                        if ((int)DialogResult.Yes ==
                            CustomMessageBox.Show("Is this a PIXRACER?", "PIXRACER", MessageBoxButtons.YesNo))
                        {
                            return(boards.px4v4);
                        }
                        if ((int)DialogResult.Yes ==
                            CustomMessageBox.Show("Is this a CUBE?", "CUBE", MessageBoxButtons.YesNo))
                        {
                            return(boards.px4v3);
                        }
                        if ((int)DialogResult.Yes ==
                            CustomMessageBox.Show("Is this a PIXHAWK?", "PIXHAWK", MessageBoxButtons.YesNo))
                        {
                            return(boards.px4v2);
                        }
                        return(boards.px4);
                    }
                    else
                    {
                        return(boards.b2560);
                    }
                }
            }

            if ((int)DialogResult.Yes == CustomMessageBox.Show("Is this a Linux board?", "Linux", MessageBoxButtons.YesNo))
            {
                if ((int)DialogResult.Yes == CustomMessageBox.Show("Is this Bebop2?", "Bebop2", MessageBoxButtons.YesNo))
                {
                    return(boards.bebop2);
                }

                if ((int)DialogResult.Yes == CustomMessageBox.Show("Is this Disco?", "Disco", MessageBoxButtons.YesNo))
                {
                    return(boards.disco);
                }
            }

            if (serialPort.IsOpen)
            {
                serialPort.Close();
            }

            serialPort.DtrEnable = true;
            serialPort.BaudRate  = 57600;
            serialPort.Open();

            Thread.Sleep(100);

            int a = 0;

            while (a < 20) // 20 * 50 = 1 sec
            {
                //Console.WriteLine("write " + DateTime.Now.Millisecond);
                serialPort.DiscardInBuffer();
                serialPort.Write(new byte[] { (byte)'0', (byte)' ' }, 0, 2);
                a++;
                Thread.Sleep(50);

                //Console.WriteLine("btr {0}", serialPort.BytesToRead);
                if (serialPort.BytesToRead >= 2)
                {
                    byte b1 = (byte)serialPort.ReadByte();
                    byte b2 = (byte)serialPort.ReadByte();
                    if (b1 == 0x14 && b2 == 0x10)
                    {
                        serialPort.Close();
                        log.Info("is a 1280");
                        return(boards.b1280);
                    }
                }
            }

            if (serialPort.IsOpen)
            {
                serialPort.Close();
            }

            log.Warn("Not a 1280");

            Thread.Sleep(500);

            serialPort.DtrEnable = true;
            serialPort.BaudRate  = 115200;
            serialPort.Open();

            Thread.Sleep(100);

            a = 0;
            while (a < 4)
            {
                byte[] temp = new byte[] { 0x6, 0, 0, 0, 0 };
                temp = BoardDetect.genstkv2packet(serialPort, temp);
                a++;
                Thread.Sleep(50);

                try
                {
                    if (temp[0] == 6 && temp[1] == 0 && temp.Length == 2)
                    {
                        serialPort.Close();
                        //HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Enum\USB\VID_2341&PID_0010\640333439373519060F0\Device Parameters
                        if (!MainV2.MONO &&
                            !Thread.CurrentThread.CurrentCulture.IsChildOf(CultureInfoEx.GetCultureInfo("zh-Hans")))
                        {
                            ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_SerialPort");
                            // Win32_USBControllerDevice
                            ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
                            foreach (ManagementObject obj2 in searcher.Get())
                            {
                                //Console.WriteLine("Dependant : " + obj2["Dependent"]);

                                // all apm 1-1.4 use a ftdi on the imu board.

                                /*    obj2.Properties.ForEach(x =>
                                 * {
                                 *  try
                                 *  {
                                 *      log.Info(((PropertyData)x).Name.ToString() + " = " + ((PropertyData)x).Value.ToString());
                                 *  }
                                 *  catch { }
                                 * });
                                 */
                                // check vid and pid
                                if (obj2.Properties["PNPDeviceID"].Value.ToString().Contains(@"USB\VID_2341&PID_0010"))
                                {
                                    // check port name as well
                                    if (
                                        obj2.Properties["Name"].Value.ToString()
                                        .ToUpper()
                                        .Contains(serialPort.PortName.ToUpper()))
                                    {
                                        log.Info("is a 2560-2");
                                        return(boards.b2560v2);
                                    }
                                }
                            }

                            log.Info("is a 2560");
                            return(boards.b2560);
                        }
                    }
                }
                catch
                {
                }
            }

            serialPort.Close();
            log.Warn("Not a 2560");

            if ((int)DialogResult.Yes == CustomMessageBox.Show("Is this a APM 2+?", "APM 2+", MessageBoxButtons.YesNo))
            {
                return(boards.b2560v2);
            }
            else
            {
                if ((int)DialogResult.Yes ==
                    CustomMessageBox.Show("Is this a PX4/PIXHAWK?", "PX4/PIXHAWK", MessageBoxButtons.YesNo))
                {
                    if ((int)DialogResult.Yes ==
                        CustomMessageBox.Show("Is this a PIXHAWK?", "PIXHAWK", MessageBoxButtons.YesNo))
                    {
                        return(boards.px4v2);
                    }
                    return(boards.px4);
                }
                else
                {
                    return(boards.b2560);
                }
            }
        }
Example #38
0
        private void TXT_terminal_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\r')
            {
                if (comPort.IsOpen)
                {
                    try
                    {
                        var cmd = "";
                        lock (thisLock)
                        {
                            if (MainV2.MONO)
                            {
                                cmd = TXT_terminal.Text.Substring(inputStartPos,
                                                                  TXT_terminal.Text.Length - inputStartPos);
                            }
                            else
                            {
                                cmd = TXT_terminal.Text.Substring(inputStartPos,
                                                                  TXT_terminal.Text.Length - inputStartPos - 1);
                            }
                            TXT_terminal.Select(inputStartPos, TXT_terminal.Text.Length - inputStartPos);
                            TXT_terminal.SelectedText = "";
                            if (cmd.Length > 0 && (cmdHistory.Count == 0 || cmdHistory.Last() != cmd))
                            {
                                cmdHistory.Add(cmd);
                                history = cmdHistory.Count;
                            }
                        }

                        log.Info("Command: " + cmd);

                        // do not change this  \r is correct - no \n
                        if (cmd == "+++")
                        {
                            comPort.Write(Encoding.ASCII.GetBytes(cmd), 0, cmd.Length);
                            lastsend = DateTime.Now;
                        }
                        else
                        {
                            comPort.Write(Encoding.ASCII.GetBytes(cmd + "\r"), 0, cmd.Length + 1);
                            lastsend = DateTime.Now;
                        }
                    }
                    catch
                    {
                        CustomMessageBox.Show(Strings.ErrorCommunicating, Strings.ERROR);
                    }
                }
            }

            /*
             * if (comPort.IsOpen)
             * {
             *  try
             *  {
             *      comPort.Write(new byte[] { (byte)e.KeyChar }, 0, 1);
             *  }
             *  catch { MessageBox.Show("Error writing to com port"); }
             * }
             * e.Handled = true;*/
        }
Example #39
0
        public void CustomMessageBox()
        {
            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                CustomMessageBox messageBox = new CustomMessageBox()
                {
                    Caption            = "Queue update on server?",
                    Message            = "You can queue update on our server for quick update or via half an hour scheduler on phone",
                    LeftButtonContent  = "Yes",
                    RightButtonContent = "No"
                };

                int selected = 0;
                if (App.fb_selected)
                {
                    selected += 1;
                }
                if (App.tw_selected)
                {
                    selected += 10;
                }
                if (App.ld_selected)
                {
                    selected += 100;
                }
                statusUpdateItem newitem = new statusUpdateItem
                {
                    status              = statusString,
                    startTime           = App.finalStartTime,
                    endTime             = App.finalExpTime,
                    selected            = selected,
                    picFolder           = "",
                    uploadStatus        = 0,
                    fbAccessToken       = App.fbaccesstokenkey,
                    twAccessToken       = App.twaccesstokenkey,
                    twAccessTokenSecret = App.twaccesstokensecret,
                    ldAccessToken       = App.ldaccesstokenkey
                };
                messageBox.Dismissed += (s1, e1) =>
                {
                    switch (e1.Result)
                    {
                    case CustomMessageBoxResult.LeftButton:
                        UploadService serverUpload = new UploadService();
                        serverUpload.dispatcher    = Dispatcher;
                        serverUpload.item          = newitem;
                        serverUpload.StartUpload();
                        break;

                    case CustomMessageBoxResult.RightButton:
                        StatusUpdateItems.Add(newitem);
                        statusUpdateDb.StatusUpdateItems.InsertOnSubmit(newitem);
                        statusUpdateDb.SubmitChanges();

                        break;

                    case CustomMessageBoxResult.None:
                        StatusUpdateItems.Add(newitem);
                        statusUpdateDb.StatusUpdateItems.InsertOnSubmit(newitem);
                        statusUpdateDb.SubmitChanges();

                        StartPeriodicTask();
                        break;

                    default:
                        StatusUpdateItems.Add(newitem);
                        statusUpdateDb.StatusUpdateItems.InsertOnSubmit(newitem);
                        statusUpdateDb.SubmitChanges();

                        StartPeriodicTask();
                        break;
                    }
                };

                messageBox.Show();
            });
        }
Example #40
0
        private void CMB_apmversion_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (startup)
            {
                return;
            }

            var selection = int.Parse(CMB_apmversion.Text.Substring(0, 1));

            try
            {
                if (selection == 0)
                {
                    // apm1
                    MainV2.comPort.setParam("BATT_VOLT_PIN", 0);
                    MainV2.comPort.setParam("BATT_CURR_PIN", 1);
                }
                else if (selection == 1)
                {
                    // apm2
                    MainV2.comPort.setParam("BATT_VOLT_PIN", 1);
                    MainV2.comPort.setParam("BATT_CURR_PIN", 2);
                }
                else if (selection == 2)
                {
                    //apm2.5
                    MainV2.comPort.setParam("BATT_VOLT_PIN", 13);
                    MainV2.comPort.setParam("BATT_CURR_PIN", 12);
                }
                else if (selection == 3)
                {
                    //px4
                    MainV2.comPort.setParam("BATT_VOLT_PIN", 100);
                    MainV2.comPort.setParam("BATT_CURR_PIN", 101);
                    MainV2.comPort.setParam(new[] { "VOLT_DIVIDER", "BATT_VOLT_MULT" }, 1);
                    TXT_divider.Text = "1";
                }
                else if (selection == 4)
                {
                    //px4
                    MainV2.comPort.setParam("BATT_VOLT_PIN", 2);
                    MainV2.comPort.setParam("BATT_CURR_PIN", 3);
                }
                else if (selection == 5)
                {
                    //vrbrain 5
                    MainV2.comPort.setParam("BATT_VOLT_PIN", 10);
                    MainV2.comPort.setParam("BATT_CURR_PIN", 11);
                    MainV2.comPort.setParam(new[] { "VOLT_DIVIDER", "BATT_VOLT_MULT" }, 10);
                    TXT_divider.Text = "10";
                }
                else if (selection == 6)
                {
                    //vr micro brain 5
                    MainV2.comPort.setParam("BATT_VOLT_PIN", 10);
                    MainV2.comPort.setParam("BATT_CURR_PIN", -1);
                    MainV2.comPort.setParam(new[] { "VOLT_DIVIDER", "BATT_VOLT_MULT" }, 10);
                    TXT_divider.Text = "10";
                }
                else if (selection == 7)
                {
                    //vr brain 4
                    MainV2.comPort.setParam("BATT_VOLT_PIN", 6);
                    MainV2.comPort.setParam("BATT_CURR_PIN", 7);
                    MainV2.comPort.setParam(new[] { "VOLT_DIVIDER", "BATT_VOLT_MULT" }, 10);
                    TXT_divider.Text = "10";
                }
            }
            catch
            {
                CustomMessageBox.Show("Set BATT_????_PIN Failed", Strings.ERROR);
            }
        }
Example #41
0
        public static string CheckLogFile(string FileName)
        {
            var dir = Application.StartupPath + Path.DirectorySeparatorChar + "LogAnalyzer" +
                      Path.DirectorySeparatorChar;

            var runner = dir + "runner.exe";

            var zip = dir + "LogAnalyzer.zip";

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

            if (!File.Exists(runner))
            {
                Loading.ShowLoading("Downloading LogAnalyzer");
                bool gotit = false;
                if (Environment.Is64BitOperatingSystem)
                {
                    gotit = Common.getFilefromNet(
                        "http://firmware.ardupilot.org/Tools/MissionPlanner/LogAnalyzer/LogAnalyzer64.zip",
                        zip);
                }
                else
                {
                    gotit = Common.getFilefromNet(
                        "http://firmware.ardupilot.org/Tools/MissionPlanner/LogAnalyzer/LogAnalyzer.zip",
                        zip);
                }

                // download zip
                if (gotit)
                {
                    Loading.ShowLoading("Extracting zip file");
                    // extract zip
                    FastZip fzip = new FastZip();
                    fzip.ExtractZip(zip, dir, "");
                }
                else
                {
                    CustomMessageBox.Show("Failed to download LogAnalyzer");
                    return("");
                }
            }

            if (!File.Exists(runner))
            {
                CustomMessageBox.Show("Failed to download LogAnalyzer");
                return("");
            }

            var sb = new StringBuilder();

            Process P = new Process();

            P.StartInfo.FileName  = runner;
            P.StartInfo.Arguments = @" -x """ + FileName + @".xml"" -s """ + FileName + @"""";

            P.StartInfo.UseShellExecute  = false;
            P.StartInfo.WorkingDirectory = dir;

            P.StartInfo.RedirectStandardOutput = true;
            P.StartInfo.RedirectStandardError  = true;

            P.OutputDataReceived += (sender, args) => sb.AppendLine(args.Data);
            P.ErrorDataReceived  += (sender, args) => sb.AppendLine(args.Data);

            try
            {
                Loading.ShowLoading("Running LogAnalyzer");

                P.Start();

                P.BeginOutputReadLine();
                P.BeginErrorReadLine();

                // until we are done
                P.WaitForExit();

                log.Info(sb.ToString());
            }
            catch
            {
                CustomMessageBox.Show("Failed to start LogAnalyzer");
            }

            Loading.Close();

            return(FileName + ".xml");
        }
Example #42
0
        private void StartSITL(string exepath, string model, string homelocation, string extraargs = "", int speedup = 1)
        {
            if (String.IsNullOrEmpty(homelocation))
            {
                CustomMessageBox.Show(Strings.Invalid_home_location, Strings.ERROR);
                return;
            }

            if (!File.Exists(exepath))
            {
                CustomMessageBox.Show(Strings.Failed_to_download_the_SITL_image, Strings.ERROR);
                return;
            }

            // kill old session
            try
            {
                if (simulator != null)
                {
                    simulator.Kill();
                }
            }
            catch
            {
            }

            // override default model
            if (cmb_model.Text != "")
            {
                model = cmb_model.Text;
            }

            var config = GetDefaultConfig(model);

            if (!string.IsNullOrEmpty(config))
            {
                extraargs += @" --defaults """ + config + @"""";
            }

            extraargs += " " + txt_cmdline.Text + " ";

            if (chk_wipe.Checked)
            {
                extraargs += " --wipe ";
            }

            string simdir = sitldirectory + model + Path.DirectorySeparatorChar;

            Directory.CreateDirectory(simdir);

            string path = Environment.GetEnvironmentVariable("PATH");

            Environment.SetEnvironmentVariable("PATH", sitldirectory + ";" + simdir + ";" + path, EnvironmentVariableTarget.Process);

            Environment.SetEnvironmentVariable("HOME", simdir, EnvironmentVariableTarget.Process);

            ProcessStartInfo exestart = new ProcessStartInfo();

            exestart.FileName         = exepath;
            exestart.Arguments        = String.Format("-M{0} -O{1} -s{2} --uartA tcp:0 {3}", model, homelocation, speedup, extraargs);
            exestart.WorkingDirectory = simdir;
            exestart.WindowStyle      = ProcessWindowStyle.Minimized;
            exestart.UseShellExecute  = true;

            try
            {
                simulator = System.Diagnostics.Process.Start(exestart);
            }
            catch (Exception ex)
            {
                CustomMessageBox.Show("Failed to start the simulator\n" + ex.ToString(), Strings.ERROR);
                return;
            }

            System.Threading.Thread.Sleep(2000);

            MainV2.View.ShowScreen(MainV2.View.screens[0].Name);

            var client = new Comms.TcpSerial();

            try
            {
                client.client = new TcpClient("127.0.0.1", 5760);

                MainV2.comPort.BaseStream = client;

                SITLSEND = new UdpClient("127.0.0.1", 5501);

                Thread.Sleep(200);

                MainV2.instance.doConnect(MainV2.comPort, "preset", "5760");
            }
            catch
            {
                CustomMessageBox.Show(Strings.Failed_to_connect_to_SITL_instance, Strings.ERROR);
                return;
            }
        }
Example #43
0
        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if (keyData == (Keys.Control | Keys.S))
            {
                var exepath = CheckandGetSITLImage("ArduCopter.elf");
                var model   = "+";

                var config = GetDefaultConfig(model);
                var max    = 10;

                for (int a = max; a >= 0; a--)
                {
                    var extra = "";

                    if (!string.IsNullOrEmpty(config))
                    {
                        extra += @" --defaults """ + config + @""" -P SERIAL0_PROTOCOL=2 -P SERIAL1_PROTOCOL=2 ";
                    }

                    var home = new PointLatLngAlt(markeroverlay.Markers[0].Position).newpos((double)NUM_heading.Value, a * 4);

                    if (max == a)
                    {
                        extra += String.Format(
                            " -M{4} -s1 --home {3} --instance {0} --uartA tcp:0 {1} -P SYSID_THISMAV={2} ",
                            a, "", a + 1, BuildHomeLocation(home, (int)NUM_heading.Value), model);
                    }
                    else
                    {
                        extra += String.Format(
                            " -M{4} -s1 --home {3} --instance {0} --uartA tcp:0 {1} -P SYSID_THISMAV={2} ",
                            a, "--uartD tcpclient:127.0.0.1:" + (5770 + 10 * a), a + 1, BuildHomeLocation(home, (int)NUM_heading.Value), model);
                    }

                    string simdir = sitldirectory + model + (a + 1) + Path.DirectorySeparatorChar;

                    Directory.CreateDirectory(simdir);

                    string path = Environment.GetEnvironmentVariable("PATH");

                    Environment.SetEnvironmentVariable("PATH", sitldirectory + ";" + simdir + ";" + path, EnvironmentVariableTarget.Process);

                    Environment.SetEnvironmentVariable("HOME", simdir, EnvironmentVariableTarget.Process);

                    ProcessStartInfo exestart = new ProcessStartInfo();
                    exestart.FileName         = exepath;
                    exestart.Arguments        = extra;
                    exestart.WorkingDirectory = simdir;
                    exestart.WindowStyle      = ProcessWindowStyle.Minimized;
                    exestart.UseShellExecute  = true;

                    Process.Start(exestart);
                }

                try
                {
                    var client = new Comms.TcpSerial();

                    client.client = new TcpClient("127.0.0.1", 5760);

                    MainV2.comPort.BaseStream = client;

                    SITLSEND = new UdpClient("127.0.0.1", 5501);

                    Thread.Sleep(200);

                    MainV2.instance.doConnect(MainV2.comPort, "preset", "5760");

                    return(true);
                }
                catch
                {
                    CustomMessageBox.Show(Strings.Failed_to_connect_to_SITL_instance, Strings.ERROR);
                    return(true);
                }
            }

            if (keyData == (Keys.Control | Keys.D))
            {
                var exepath = CheckandGetSITLImage("ArduCopter.elf");
                var model   = "+";

                var config = GetDefaultConfig(model);
                var max    = 10;

                for (int a = max; a >= 0; a--)
                {
                    var extra = "";

                    if (!string.IsNullOrEmpty(config))
                    {
                        extra += @" --defaults """ + config + @""" -P SERIAL0_PROTOCOL=2 -P SERIAL1_PROTOCOL=2 ";
                    }

                    var home = new PointLatLngAlt(markeroverlay.Markers[0].Position).newpos((double)NUM_heading.Value, a * 4);

                    if (max == a)
                    {
                        extra += String.Format(
                            " -M{4} -s1 --home {3} --instance {0} --uartA tcp:0 {1} -P SYSID_THISMAV={2} ",
                            a, "", a + 1, BuildHomeLocation(home, (int)NUM_heading.Value), model);
                    }
                    else
                    {
                        extra += String.Format(
                            " -M{4} -s1 --home {3} --instance {0} --uartA tcp:0 {1} -P SYSID_THISMAV={2} ",
                            a, "" /*"--uartD tcpclient:127.0.0.1:" + (5770 + 10 * a)*/, a + 1, BuildHomeLocation(home, (int)NUM_heading.Value), model);
                    }

                    string simdir = sitldirectory + model + (a + 1) + Path.DirectorySeparatorChar;

                    Directory.CreateDirectory(simdir);

                    string path = Environment.GetEnvironmentVariable("PATH");

                    Environment.SetEnvironmentVariable("PATH", sitldirectory + ";" + simdir + ";" + path, EnvironmentVariableTarget.Process);

                    Environment.SetEnvironmentVariable("HOME", simdir, EnvironmentVariableTarget.Process);

                    ProcessStartInfo exestart = new ProcessStartInfo();
                    exestart.FileName         = exepath;
                    exestart.Arguments        = extra;
                    exestart.WorkingDirectory = simdir;
                    exestart.WindowStyle      = ProcessWindowStyle.Minimized;
                    exestart.UseShellExecute  = true;

                    Process.Start(exestart);
                }

                try
                {
                    for (int a = max; a >= 0; a--)
                    {
                        var mav = new MAVLinkInterface();

                        var client = new Comms.TcpSerial();

                        client.client = new TcpClient("127.0.0.1", 5760 + (10 * (a)));

                        mav.BaseStream = client;

                        //SITLSEND = new UdpClient("127.0.0.1", 5501);

                        Thread.Sleep(200);

                        MainV2.instance.doConnect(mav, "preset", "5760");

                        MainV2.Comports.Add(mav);
                    }

                    return(true);
                }
                catch
                {
                    CustomMessageBox.Show(Strings.Failed_to_connect_to_SITL_instance, Strings.ERROR);
                    return(true);
                }
            }

            return(base.ProcessCmdKey(ref msg, keyData));
        }
Example #44
0
        public int WizardValidate()
        {
            comport = CMB_port.Text;

            if (comport == "")
            {
                CustomMessageBox.Show(Strings.SelectComport, Strings.ERROR);
                return(0);
            }

            // ensure we are using a comport
            if (!(MainV2.comPort.BaseStream is SerialPort))
            {
                MainV2.comPort.BaseStream = new SerialPort();
            }

            if (!fwdone)
            {
                pdr = new ProgressReporterDialogue();

                pdr.DoWork += pdr_DoWork;

                ThemeManager.ApplyThemeTo(pdr);

                pdr.RunBackgroundOperationAsync();

                if (pdr.doWorkArgs.CancelRequested || !string.IsNullOrEmpty(pdr.doWorkArgs.ErrorMessage))
                {
                    return(0);
                }

                pdr.Dispose();
            }

            if (MainV2.comPort.BaseStream.IsOpen)
            {
                MainV2.comPort.BaseStream.Close();
            }

            // setup for over usb
            MainV2.comPort.BaseStream.BaudRate = 115200;
            MainV2.comPort.BaseStream.PortName = comport;


            MainV2.comPort.Open(true);

            // try again
            if (!MainV2.comPort.BaseStream.IsOpen)
            {
                CustomMessageBox.Show("Error connecting. Please unplug, plug back in, wait 10 seconds, and click OK",
                                      "Try Again");
                MainV2.comPort.Open(true);
            }

            if (!MainV2.comPort.BaseStream.IsOpen)
            {
                return(0);
            }

            if (string.IsNullOrEmpty(pdr.doWorkArgs.ErrorMessage))
            {
                if (Wizard.config.ContainsKey("fwtype") && Wizard.config.ContainsKey("fwframe"))
                {
                    if (Wizard.config["fwtype"].ToString() == "copter" && Wizard.config["fwframe"].ToString() == "tri")
                    {
                        // check if its a tri, and skip the frame type screen
                        return(2);
                    }
                }
                if (Wizard.config.ContainsKey("fwtype") && Wizard.config["fwtype"].ToString() == "copter")
                {
                    // check if its a quad, and show the frame type screen
                    return(1);
                }
                if (Wizard.config.ContainsKey("fwtype") && Wizard.config["fwtype"].ToString() == "rover")
                {
                    // check if its a rover, and show the compass cal screen - skip accel
                    return(3);
                }
                else
                {
                    // skip the frame type screen as its not valid for anythine else
                    return(2);
                }
            }

            return(0);
        }
Example #45
0
        public async void StartSwarmSeperate()
        {
            var exepath = CheckandGetSITLImage("ArduCopter.elf");
            var model   = "+";

            var config = await GetDefaultConfig(model);

            var max = 10.0;

            if (InputBox.Show("how many?", "how many?", ref max) != DialogResult.OK)
            {
                return;
            }

            max--;

            for (int a = (int)max; a >= 0; a--)
            {
                var extra = " --disable-fgview -r50 ";

                if (!string.IsNullOrEmpty(config))
                {
                    extra += @" --defaults """ + config + @""" -P SERIAL0_PROTOCOL=2 -P SERIAL1_PROTOCOL=2 ";
                }

                var home = new PointLatLngAlt(markeroverlay.Markers[0].Position).newpos((double)NUM_heading.Value, a * 4);

                if (max == a)
                {
                    extra += String.Format(
                        " -M{4} -s1 --home {3} --instance {0} --uartA tcp:0 {1} -P SYSID_THISMAV={2} ",
                        a, "", a + 1, BuildHomeLocation(home, (int)NUM_heading.Value), model);
                }
                else
                {
                    extra += String.Format(
                        " -M{4} -s1 --home {3} --instance {0} --uartA tcp:0 {1} -P SYSID_THISMAV={2} ",
                        a, "" /*"--uartD tcpclient:127.0.0.1:" + (5770 + 10 * a)*/, a + 1,
                        BuildHomeLocation(home, (int)NUM_heading.Value), model);
                }

                string simdir = sitldirectory + model + (a + 1) + Path.DirectorySeparatorChar;

                Directory.CreateDirectory(simdir);

                string path = Environment.GetEnvironmentVariable("PATH");

                Environment.SetEnvironmentVariable("PATH", sitldirectory + ";" + simdir + ";" + path,
                                                   EnvironmentVariableTarget.Process);

                Environment.SetEnvironmentVariable("HOME", simdir, EnvironmentVariableTarget.Process);

                ProcessStartInfo exestart = new ProcessStartInfo();
                exestart.FileName         = await exepath;
                exestart.Arguments        = extra;
                exestart.WorkingDirectory = simdir;
                exestart.WindowStyle      = ProcessWindowStyle.Minimized;
                exestart.UseShellExecute  = true;

                Process.Start(exestart);
            }

            try
            {
                for (int a = (int)max; a >= 0; a--)
                {
                    var mav = new MAVLinkInterface();

                    var client = new Comms.TcpSerial();

                    client.client = new TcpClient("127.0.0.1", 5760 + (10 * (a)));

                    mav.BaseStream = client;

                    //SITLSEND = new UdpClient("127.0.0.1", 5501);

                    Thread.Sleep(200);

                    MainV2.instance.doConnect(mav, "preset", "5760");

                    try
                    {
                        mav.GetParam("SYSID_THISMAV");
                        mav.setParam("SYSID_THISMAV", a + 1, true);

                        mav.GetParam("FRAME_CLASS");
                        mav.setParam("FRAME_CLASS", 1, true);
                    }
                    catch
                    {
                    }

                    MainV2.Comports.Add(mav);
                }

                return;
            }
            catch
            {
                CustomMessageBox.Show(Strings.Failed_to_connect_to_SITL_instance, Strings.ERROR);
                return;
            }
        }
Example #46
0
 private void label8_Click(object sender, EventArgs e)
 {
     usebeta = true;
     CustomMessageBox.Show("Using beta FW");
 }
Example #47
0
        private void findfirmware(Firmware.software fwtoupload)
        {
            var dr = CustomMessageBox.Show(Strings.AreYouSureYouWantToUpload + fwtoupload.name + Strings.QuestionMark,
                                           Strings.Continue, MessageBoxButtons.YesNo);

            if (dr == (int)DialogResult.Yes)
            {
                try
                {
                    MainV2.comPort.BaseStream.Close();
                }
                catch
                {
                }
                fw.Progress -= fw_ProgressPDR;
                fw.Progress += fw_Progress1;

                var history = (CMB_history.SelectedValue == null) ? "" : CMB_history.SelectedValue.ToString();

                if (history != "")
                {
                    foreach (var propertyInfo in fwtoupload.GetType().GetFields())
                    {
                        try
                        {
                            if (propertyInfo.Name.Contains("url"))
                            {
                                var oldurl = propertyInfo.GetValue(fwtoupload).ToString();
                                if (oldurl == "")
                                {
                                    continue;
                                }
                                var newurl = Firmware.getUrl(history, oldurl);
                                propertyInfo.SetValue(fwtoupload, newurl);
                            }
                        }
                        catch { }
                    }

                    //history = "";
                }

                var updated = fw.update(MainV2.comPortName, fwtoupload, history, Win32DeviceMgmt.GetAllCOMPorts());

                if (updated)
                {
                    if (fwtoupload.url2560_2 != null && fwtoupload.url2560_2.ToLower().Contains("copter") &&
                        fwtoupload.name.ToLower().Contains("3.1"))
                    {
                        CustomMessageBox.Show(Strings.WarningAC31, Strings.Warning);
                    }

                    if (fwtoupload.url2560_2 != null && fwtoupload.url2560_2.ToLower().Contains("copter") &&
                        fwtoupload.name.ToLower().Contains("3.2"))
                    {
                        CustomMessageBox.Show(Strings.WarningAC32, Strings.Warning);
                    }
                }
                else
                {
                    CustomMessageBox.Show(Strings.ErrorUploadingFirmware, Strings.ERROR);
                }
            }
        }
        List <PointLatLngAlt> getGEAltPath(List <PointLatLngAlt> list)
        {
            double alt = 0;
            double lat = 0;
            double lng = 0;

            int pos = 0;

            List <PointLatLngAlt> answer = new List <PointLatLngAlt>();

            //http://code.google.com/apis/maps/documentation/elevation/
            //http://maps.google.com/maps/api/elevation/xml
            string coords = "";

            foreach (PointLatLngAlt loc in list)
            {
                if (loc == null)
                {
                    continue;
                }

                coords = coords + loc.Lat.ToString(new System.Globalization.CultureInfo("en-US")) + "," +
                         loc.Lng.ToString(new System.Globalization.CultureInfo("en-US")) + "|";
            }
            coords = coords.Remove(coords.Length - 1);

            if (list.Count < 2 || coords.Length > (2048 - 256))
            {
                CustomMessageBox.Show("Too many/few WP's or to Big a Distance " + (distance / 1000) + "km", Strings.ERROR);
                return(answer);
            }

            try
            {
                using (
                    XmlTextReader xmlreader =
                        new XmlTextReader("https://maps.google.com/maps/api/elevation/xml?path=" + coords + "&samples=" +
                                          (distance / 100).ToString(new System.Globalization.CultureInfo("en-US")) +
                                          "&sensor=false&key=" + GoogleMapProvider.APIKey))
                {
                    while (xmlreader.Read())
                    {
                        xmlreader.MoveToElement();
                        switch (xmlreader.Name)
                        {
                        case "elevation":
                            alt = double.Parse(xmlreader.ReadString(), new System.Globalization.CultureInfo("en-US"));
                            Console.WriteLine("DO it " + lat + " " + lng + " " + alt);
                            PointLatLngAlt loc = new PointLatLngAlt(lat, lng, alt, "");
                            answer.Add(loc);
                            pos++;
                            break;

                        case "lat":
                            lat = double.Parse(xmlreader.ReadString(), new System.Globalization.CultureInfo("en-US"));
                            break;

                        case "lng":
                            lng = double.Parse(xmlreader.ReadString(), new System.Globalization.CultureInfo("en-US"));
                            break;

                        default:
                            break;
                        }
                    }
                }
            }
            catch
            {
                CustomMessageBox.Show("Error getting GE data", Strings.ERROR);
            }

            return(answer);
        }
Example #49
0
        /// <summary>
        /// Read intel hex file
        /// </summary>
        /// <param name="sr"></param>
        /// <returns></returns>
        byte[] readIntelHEXv2(StreamReader sr)
        {
            byte[] FLASH = new byte[1024 * 1024];

            int  optionoffset = 0;
            int  total        = 0;
            bool hitend       = false;

            while (!sr.EndOfStream)
            {
                updateProgress((int)(((float)sr.BaseStream.Position / (float)sr.BaseStream.Length) * 100), "Reading Hex");

                string line = sr.ReadLine();

                if (line.StartsWith(":"))
                {
                    int length  = Convert.ToInt32(line.Substring(1, 2), 16);
                    int address = Convert.ToInt32(line.Substring(3, 4), 16);
                    int option  = Convert.ToInt32(line.Substring(7, 2), 16);
                    // log.InfoFormat("len {0} add {1} opt {2}", length, address, option);

                    if (option == 0)
                    {
                        string data = line.Substring(9, length * 2);
                        for (int i = 0; i < length; i++)
                        {
                            byte byte1 = Convert.ToByte(data.Substring(i * 2, 2), 16);
                            FLASH[optionoffset + address] = byte1;
                            address++;
                            if ((optionoffset + address) > total)
                            {
                                total = optionoffset + address;
                            }
                        }
                    }
                    else if (option == 2)
                    {
                        optionoffset = (int)Convert.ToUInt16(line.Substring(9, 4), 16) << 4;
                    }
                    else if (option == 1)
                    {
                        hitend = true;
                    }
                    int checksum = Convert.ToInt32(line.Substring(line.Length - 2, 2), 16);

                    byte checksumact = 0;
                    for (int z = 0; z < ((line.Length - 1 - 2) / 2); z++) // minus 1 for : then mins 2 for checksum itself
                    {
                        checksumact += Convert.ToByte(line.Substring(z * 2 + 1, 2), 16);
                    }
                    checksumact = (byte)(0x100 - checksumact);

                    if (checksumact != checksum)
                    {
                        CustomMessageBox.Show("The hex file loaded is invalid, please try again.");
                        throw new Exception("Checksum Failed - Invalid Hex");
                    }
                }
                //Regex regex = new Regex(@"^:(..)(....)(..)(.*)(..)$"); // length - address - option - data - checksum
            }

            if (!hitend)
            {
                CustomMessageBox.Show("The hex file did no contain an end flag. aborting");
                throw new Exception("No end flag in file");
            }

            Array.Resize <byte>(ref FLASH, total);

            return(FLASH);
        }
        private void BUT_Calibrateradio_Click(object sender, EventArgs e)
        {
            if (run)
            {
                BUT_Calibrateradio.Text = Strings.Completed;
                run = false;
                return;
            }

            CustomMessageBox.Show(
                "Ensure your transmitter is on and receiver is powered and connected\nEnsure your motor does not have power/no props!!!");

            var oldrc     = MainV2.comPort.MAV.cs.raterc;
            var oldatt    = MainV2.comPort.MAV.cs.rateattitude;
            var oldpos    = MainV2.comPort.MAV.cs.rateposition;
            var oldstatus = MainV2.comPort.MAV.cs.ratestatus;

            MainV2.comPort.MAV.cs.raterc       = 10;
            MainV2.comPort.MAV.cs.rateattitude = 0;
            MainV2.comPort.MAV.cs.rateposition = 0;
            MainV2.comPort.MAV.cs.ratestatus   = 0;

            try
            {
                MainV2.comPort.requestDatastream(MAVLink.MAV_DATA_STREAM.RC_CHANNELS, 10);
            }
            catch
            {
            }

            BUT_Calibrateradio.Text = Strings.Click_when_Done;

            CustomMessageBox.Show(
                "Click OK and move all RC sticks and switches to their\nextreme positions so the red bars hit the limits.");

            run = true;


            while (run)
            {
                Application.DoEvents();

                Thread.Sleep(5);

                MainV2.comPort.MAV.cs.UpdateCurrentSettings(currentStateBindingSource.UpdateDataSource(MainV2.comPort.MAV.cs), true, MainV2.comPort);

                // check for non 0 values
                if (MainV2.comPort.MAV.cs.ch1in > 800 && MainV2.comPort.MAV.cs.ch1in < 2200)
                {
                    rcmin[0] = Math.Min(rcmin[0], MainV2.comPort.MAV.cs.ch1in);
                    rcmax[0] = Math.Max(rcmax[0], MainV2.comPort.MAV.cs.ch1in);

                    rcmin[1] = Math.Min(rcmin[1], MainV2.comPort.MAV.cs.ch2in);
                    rcmax[1] = Math.Max(rcmax[1], MainV2.comPort.MAV.cs.ch2in);

                    rcmin[2] = Math.Min(rcmin[2], MainV2.comPort.MAV.cs.ch3in);
                    rcmax[2] = Math.Max(rcmax[2], MainV2.comPort.MAV.cs.ch3in);

                    rcmin[3] = Math.Min(rcmin[3], MainV2.comPort.MAV.cs.ch4in);
                    rcmax[3] = Math.Max(rcmax[3], MainV2.comPort.MAV.cs.ch4in);

                    rcmin[4] = Math.Min(rcmin[4], MainV2.comPort.MAV.cs.ch5in);
                    rcmax[4] = Math.Max(rcmax[4], MainV2.comPort.MAV.cs.ch5in);

                    rcmin[5] = Math.Min(rcmin[5], MainV2.comPort.MAV.cs.ch6in);
                    rcmax[5] = Math.Max(rcmax[5], MainV2.comPort.MAV.cs.ch6in);

                    rcmin[6] = Math.Min(rcmin[6], MainV2.comPort.MAV.cs.ch7in);
                    rcmax[6] = Math.Max(rcmax[6], MainV2.comPort.MAV.cs.ch7in);

                    rcmin[7] = Math.Min(rcmin[7], MainV2.comPort.MAV.cs.ch8in);
                    rcmax[7] = Math.Max(rcmax[7], MainV2.comPort.MAV.cs.ch8in);

                    rcmin[8] = Math.Min(rcmin[8], MainV2.comPort.MAV.cs.ch9in);
                    rcmax[8] = Math.Max(rcmax[8], MainV2.comPort.MAV.cs.ch9in);

                    rcmin[9] = Math.Min(rcmin[9], MainV2.comPort.MAV.cs.ch10in);
                    rcmax[9] = Math.Max(rcmax[9], MainV2.comPort.MAV.cs.ch10in);

                    rcmin[10] = Math.Min(rcmin[10], MainV2.comPort.MAV.cs.ch11in);
                    rcmax[10] = Math.Max(rcmax[10], MainV2.comPort.MAV.cs.ch11in);

                    rcmin[11] = Math.Min(rcmin[11], MainV2.comPort.MAV.cs.ch12in);
                    rcmax[11] = Math.Max(rcmax[11], MainV2.comPort.MAV.cs.ch12in);

                    rcmin[12] = Math.Min(rcmin[12], MainV2.comPort.MAV.cs.ch13in);
                    rcmax[12] = Math.Max(rcmax[12], MainV2.comPort.MAV.cs.ch13in);

                    rcmin[13] = Math.Min(rcmin[13], MainV2.comPort.MAV.cs.ch14in);
                    rcmax[13] = Math.Max(rcmax[13], MainV2.comPort.MAV.cs.ch14in);

                    rcmin[14] = Math.Min(rcmin[14], MainV2.comPort.MAV.cs.ch15in);
                    rcmax[14] = Math.Max(rcmax[14], MainV2.comPort.MAV.cs.ch15in);

                    rcmin[15] = Math.Min(rcmin[15], MainV2.comPort.MAV.cs.ch16in);
                    rcmax[15] = Math.Max(rcmax[15], MainV2.comPort.MAV.cs.ch16in);

                    BARroll.minline = (int)rcmin[chroll - 1];
                    BARroll.maxline = (int)rcmax[chroll - 1];

                    BARpitch.minline = (int)rcmin[chpitch - 1];
                    BARpitch.maxline = (int)rcmax[chpitch - 1];

                    BARthrottle.minline = (int)rcmin[chthro - 1];
                    BARthrottle.maxline = (int)rcmax[chthro - 1];

                    BARyaw.minline = (int)rcmin[chyaw - 1];
                    BARyaw.maxline = (int)rcmax[chyaw - 1];

                    setBARStatus(BAR5, rcmin[4], rcmax[4]);
                    setBARStatus(BAR6, rcmin[5], rcmax[5]);
                    setBARStatus(BAR7, rcmin[6], rcmax[6]);
                    setBARStatus(BAR8, rcmin[7], rcmax[7]);

                    setBARStatus(BAR9, rcmin[8], rcmax[8]);
                    setBARStatus(BAR10, rcmin[9], rcmax[9]);
                    setBARStatus(BAR11, rcmin[10], rcmax[10]);
                    setBARStatus(BAR12, rcmin[11], rcmax[11]);
                    setBARStatus(BAR13, rcmin[12], rcmax[12]);
                    setBARStatus(BAR14, rcmin[13], rcmax[13]);
                }
            }

            if (rcmin[0] > 800 && rcmin[0] < 2200)
            {
            }
            else
            {
                CustomMessageBox.Show("Bad channel 1 input, canceling");
                return;
            }

            CustomMessageBox.Show("Ensure all your sticks are centered and throttle is down, and click ok to continue");

            MainV2.comPort.MAV.cs.UpdateCurrentSettings(currentStateBindingSource.UpdateDataSource(MainV2.comPort.MAV.cs), true, MainV2.comPort);

            rctrim[0] = Constrain(MainV2.comPort.MAV.cs.ch1in, 0);
            rctrim[1] = Constrain(MainV2.comPort.MAV.cs.ch2in, 1);
            rctrim[2] = Constrain(MainV2.comPort.MAV.cs.ch3in, 2);
            rctrim[3] = Constrain(MainV2.comPort.MAV.cs.ch4in, 3);
            rctrim[4] = Constrain(MainV2.comPort.MAV.cs.ch5in, 4);
            rctrim[5] = Constrain(MainV2.comPort.MAV.cs.ch6in, 5);
            rctrim[6] = Constrain(MainV2.comPort.MAV.cs.ch7in, 6);
            rctrim[7] = Constrain(MainV2.comPort.MAV.cs.ch8in, 7);

            rctrim[8]  = Constrain(MainV2.comPort.MAV.cs.ch9in, 8);
            rctrim[9]  = Constrain(MainV2.comPort.MAV.cs.ch10in, 9);
            rctrim[10] = Constrain(MainV2.comPort.MAV.cs.ch11in, 10);
            rctrim[11] = Constrain(MainV2.comPort.MAV.cs.ch12in, 11);
            rctrim[12] = Constrain(MainV2.comPort.MAV.cs.ch13in, 12);
            rctrim[13] = Constrain(MainV2.comPort.MAV.cs.ch14in, 13);
            rctrim[14] = Constrain(MainV2.comPort.MAV.cs.ch15in, 14);
            rctrim[15] = Constrain(MainV2.comPort.MAV.cs.ch16in, 15);

            var data = "---------------\n";

            for (var a = 0; a < rctrim.Length; a++)
            {
                // we want these to save no matter what
                BUT_Calibrateradio.Text = Strings.Saving;
                try
                {
                    if (rcmin[a] != rcmax[a])
                    {
                        MainV2.comPort.setParam("RC" + (a + 1).ToString("0") + "_MIN", rcmin[a], true);
                        MainV2.comPort.setParam("RC" + (a + 1).ToString("0") + "_MAX", rcmax[a], true);
                    }
                    if (rctrim[a] < 1195 || rctrim[a] > 1205)
                    {
                        MainV2.comPort.setParam("RC" + (a + 1).ToString("0") + "_TRIM", rctrim[a], true);
                    }
                }
                catch
                {
                    if (MainV2.comPort.MAV.param.ContainsKey("RC" + (a + 1).ToString("0") + "_MIN"))
                    {
                        CustomMessageBox.Show("Failed to set Channel " + (a + 1));
                    }
                }

                data = data + "CH" + (a + 1) + " " + rcmin[a] + " | " + rcmax[a] + "\n";
            }

            MainV2.comPort.MAV.cs.raterc       = oldrc;
            MainV2.comPort.MAV.cs.rateattitude = oldatt;
            MainV2.comPort.MAV.cs.rateposition = oldpos;
            MainV2.comPort.MAV.cs.ratestatus   = oldstatus;

            try
            {
                MainV2.comPort.requestDatastream(MAVLink.MAV_DATA_STREAM.RC_CHANNELS, oldrc);
            }
            catch
            {
            }

            CustomMessageBox.Show(
                "Here are the detected radio options\nNOTE Channels not connected are displayed as 1500 +-2\nNormal values are around 1100 | 1900\nChannel:Min | Max \n" +
                data, "Radio");

            BUT_Calibrateradio.Text = Strings.Completed;
        }
Example #51
0
        /// <summary>
        /// upload to px4 standalone
        /// </summary>
        /// <param name="filename"></param>
        public bool UploadPX4(string filename)
        {
            Uploader up;

            updateProgress(0, "Reading Hex File");
            px4uploader.Firmware fw;
            try
            {
                fw = px4uploader.Firmware.ProcessFirmware(filename);
            }
            catch (Exception ex)
            {
                CustomMessageBox.Show("Error loading firmware file\n\n" + ex.ToString(), "Error");
                return(false);
            }

            try
            {
                // check if we are seeing heartbeats
                MainV2.comPort.BaseStream.Open();
                MainV2.comPort.giveComport = true;

                if (MainV2.comPort.getHeartBeat().Length > 0)
                {
                    MainV2.comPort.doReboot(true);
                    MainV2.comPort.Close();
                }
                else
                {
                    MainV2.comPort.BaseStream.Close();
                    CustomMessageBox.Show("Please unplug the board, and then press OK and plug back in.\nMission Planner will look for 30 seconds to find the board");
                }
            }
            catch (Exception ex)
            {
                log.Error(ex);
                CustomMessageBox.Show("Please unplug the board, and then press OK and plug back in.\nMission Planner will look for 30 seconds to find the board");
            }

            DateTime DEADLINE = DateTime.Now.AddSeconds(30);

            updateProgress(0, "Scanning comports");

            while (DateTime.Now < DEADLINE)
            {
                string[] allports = SerialPort.GetPortNames();

                foreach (string port in allports)
                {
                    log.Info(DateTime.Now.Millisecond + " Trying Port " + port);

                    updateProgress(-1, "Connecting");

                    try
                    {
                        up = new Uploader(port, 115200);
                    }
                    catch (Exception ex)
                    {
                        //System.Threading.Thread.Sleep(50);
                        Console.WriteLine(ex.Message);
                        continue;
                    }

                    try
                    {
                        up.identify();
                        updateProgress(-1, "Identify");
                        log.InfoFormat("Found board type {0} boardrev {1} bl rev {2} fwmax {3} on {4}", up.board_type, up.board_rev, up.bl_rev, up.fw_maxsize, port);
                    }
                    catch (Exception)
                    {
                        Console.WriteLine("Not There..");
                        //Console.WriteLine(ex.Message);
                        up.close();
                        continue;
                    }

                    try
                    {
                        up.verifyotp();
                    }
                    catch { CustomMessageBox.Show("This board does not contain a valid certificate of authenticity.", "Invalid Cert"); up.__reboot(); up.close(); return(false); }

                    try
                    {
                        up.currentChecksum(fw);
                    }
                    catch
                    {
                        up.__reboot();
                        up.close();
                        CustomMessageBox.Show("No need to upload. already on the board");
                        return(true);
                    }

                    try
                    {
                        up.ProgressEvent += new Uploader.ProgressEventHandler(up_ProgressEvent);
                        up.LogEvent      += new Uploader.LogEventHandler(up_LogEvent);

                        updateProgress(0, "Upload");
                        up.upload(fw);
                        updateProgress(100, "Upload Done");
                    }
                    catch (Exception ex)
                    {
                        updateProgress(0, "ERROR: " + ex.Message);
                        log.Info(ex);
                        Console.WriteLine(ex.ToString());
                        return(false);
                    }
                    finally
                    {
                        up.close();
                    }

                    // wait for IO firmware upgrade and boot to a mavlink state
                    CustomMessageBox.Show("Please wait for the musical tones to finish before clicking OK");

                    return(true);
                }
            }

            updateProgress(0, "ERROR: No Responce from board");
            return(false);
        }
Example #52
0
        private void Log_Load(object sender, EventArgs e)
        {
            status = serialstatus.Connecting;

            comPort = GCSViews.Terminal.comPort;

            try
            {
                Console.WriteLine("Log_load " + comPort.IsOpen);

                if (!comPort.IsOpen)
                {
                    comPort.Open();
                }

                //Console.WriteLine("Log dtr");

                //comPort.toggleDTR();

                Console.WriteLine("Log discard");

                comPort.DiscardInBuffer();

                Console.WriteLine("Log w&sleep");

                try
                {
                    // try provoke a response
                    comPort.Write("\n\n?\r\n\n");
                }
                catch
                {
                }

                // 10 sec
                waitandsleep(10000);
            }
            catch (Exception ex)
            {
                log.Error("Error opening comport", ex);
                CustomMessageBox.Show("Error opening comport");
                return;
            }

            var t11 = new System.Threading.Thread(delegate()
            {
                var start = DateTime.Now;

                threadrun = true;

                if (comPort.IsOpen)
                {
                    readandsleep(100);
                }

                try
                {
                    if (comPort.IsOpen)
                    {
                        comPort.Write("\n\n\n\nexit\r\nlogs\r\n"); // more in "connecting"
                    }
                }
                catch
                {
                }

                while (threadrun)
                {
                    try
                    {
                        updateDisplay();

                        System.Threading.Thread.Sleep(1);
                        if (!comPort.IsOpen)
                        {
                            break;
                        }
                        while (comPort.BytesToRead >= 4)
                        {
                            comPort_DataReceived((object)null, (SerialDataReceivedEventArgs)null);
                        }
                    }
                    catch (Exception ex)
                    {
                        log.Error("crash in comport reader " + ex);
                    } // cant exit unless told to
                }
                log.Info("Comport thread close");
            })
            {
                Name = "comport reader", IsBackground = true
            };

            t11.Start();

            // doesnt seem to work on mac
            //comPort.DataReceived += new SerialDataReceivedEventHandler(comPort_DataReceived);
        }
Example #53
0
        public void Activate()
        {
            var copy = new Dictionary <string, double>((Dictionary <string, double>)MainV2.comPort.MAV.param);

            if (!copy.ContainsKey("CAM_TRIGG_TYPE"))
            {
                Enabled = false;
                return;
            }

            startup = true;

            CMB_shuttertype.SelectedItem = Enum.GetName(typeof(ChannelCameraShutter),
                                                        (Int32)MainV2.comPort.MAV.param["CAM_TRIGG_TYPE"]);

            foreach (string item in copy.Keys)
            {
                if (item.EndsWith("_FUNCTION"))
                {
                    switch (MainV2.comPort.MAV.param[item].ToString())
                    {
                    case "6":
                        mavlinkComboBoxPan.Text = item.Replace("_FUNCTION", "");
                        break;

                    case "7":
                        mavlinkComboBoxTilt.Text = item.Replace("_FUNCTION", "");
                        break;

                    case "8":
                        mavlinkComboBoxRoll.Text = item.Replace("_FUNCTION", "");
                        break;

                    case "10":
                        CMB_shuttertype.Text = item.Replace("_FUNCTION", "");
                        break;

                    default:
                        break;
                    }
                }
            }

            startup = false;

            try
            {
                updateShutter();
                updatePitch();
                updateRoll();
                updateYaw();

                CHK_stab_tilt.setup(1, 0, ParamHead + "STAB_TILT", MainV2.comPort.MAV.param);
                CHK_stab_roll.setup(1, 0, ParamHead + "STAB_ROLL", MainV2.comPort.MAV.param);
                CHK_stab_pan.setup(1, 0, ParamHead + "STAB_PAN", MainV2.comPort.MAV.param);

                NUD_CONTROL_x.setup(-180, 180, 1, 1, ParamHead + "CONTROL_X", MainV2.comPort.MAV.param);
                NUD_CONTROL_y.setup(-180, 180, 1, 1, ParamHead + "CONTROL_Y", MainV2.comPort.MAV.param);
                NUD_CONTROL_z.setup(-180, 180, 1, 1, ParamHead + "CONTROL_Z", MainV2.comPort.MAV.param);

                NUD_NEUTRAL_x.setup(-180, 180, 1, 1, ParamHead + "NEUTRAL_X", MainV2.comPort.MAV.param);
                NUD_NEUTRAL_y.setup(-180, 180, 1, 1, ParamHead + "NEUTRAL_Y", MainV2.comPort.MAV.param);
                NUD_NEUTRAL_z.setup(-180, 180, 1, 1, ParamHead + "NEUTRAL_Z", MainV2.comPort.MAV.param);

                NUD_RETRACT_x.setup(-180, 180, 1, 1, ParamHead + "RETRACT_X", MainV2.comPort.MAV.param);
                NUD_RETRACT_y.setup(-180, 180, 1, 1, ParamHead + "RETRACT_Y", MainV2.comPort.MAV.param);
                NUD_RETRACT_z.setup(-180, 180, 1, 1, ParamHead + "RETRACT_Z", MainV2.comPort.MAV.param);
            }
            catch (Exception ex)
            {
                CustomMessageBox.Show("Failed to set Param\n" + ex);
                Enabled = false;
            }
        }
Example #54
0
        void comPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            try
            {
                while (comPort.BytesToRead > 0 && threadrun)
                {
                    updateDisplay();

                    string line = "";

                    comPort.ReadTimeout = 500;
                    try
                    {
                        line = comPort.ReadLine(); //readline(comPort);
                        if (!line.Contains("\n"))
                        {
                            line = line + "\n";
                        }
                    }
                    catch
                    {
                        line = comPort.ReadExisting();
                        //byte[] data = readline(comPort);
                        //line = Encoding.ASCII.GetString(data, 0, data.Length);
                    }

                    receivedbytes += line.Length;

                    //string line = Encoding.ASCII.GetString(data, 0, data.Length);

                    switch (status)
                    {
                    case serialstatus.Connecting:

                        if (line.Contains("ENTER") || line.Contains("GROUND START") || line.Contains("reset to FLY") || line.Contains("interactive setup") || line.Contains("CLI") || line.Contains("Ardu"))
                        {
                            try
                            {
                                //System.Threading.Thread.Sleep(200);
                                //comPort.Write("\n\n\n\n");
                            }
                            catch { }

                            System.Threading.Thread.Sleep(500);

                            // clear history
                            this.Invoke((System.Windows.Forms.MethodInvoker) delegate()
                            {
                                TXT_seriallog.Clear();
                            });

                            // comPort.Write("logs\r");
                            status = serialstatus.Done;
                        }
                        break;

                    case serialstatus.Closefile:
                        sw.Close();

                        DateTime logtime = new DFLog().GetFirstGpsTime(logfile);

                        if (logtime != DateTime.MinValue)
                        {
                            string newlogfilename = MainV2.LogDir + Path.DirectorySeparatorChar + logtime.ToString("yyyy-MM-dd HH-mm-ss") + ".log";
                            try
                            {
                                File.Move(logfile, newlogfilename);
                                logfile = newlogfilename;
                            }
                            catch (Exception ex) { log.Error(ex); CustomMessageBox.Show("Failed to rename file " + logfile + "\nto " + newlogfilename, Strings.ERROR); }
                        }

                        TextReader tr = new StreamReader(logfile);

                        //

                        this.Invoke((System.Windows.Forms.MethodInvoker) delegate()
                        {
                            TXT_seriallog.AppendText("Creating KML for " + logfile);
                        });

                        LogOutput lo = new LogOutput();

                        while (tr.Peek() != -1)
                        {
                            lo.processLine(tr.ReadLine());
                        }

                        tr.Close();

                        try
                        {
                            lo.writeKML(logfile + ".kml");
                        }
                        catch { }     // usualy invalid lat long error
                        status = serialstatus.Done;
                        comPort.DiscardInBuffer();
                        break;

                    case serialstatus.Createfile:
                        receivedbytes = 0;
                        Directory.CreateDirectory(MainV2.LogDir);
                        logfile = MainV2.LogDir + Path.DirectorySeparatorChar + DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss") + " " + currentlog + ".log";
                        sw      = new StreamWriter(logfile);
                        status  = serialstatus.Waiting;
                        lock (thisLock)
                        {
                            this.Invoke((System.Windows.Forms.MethodInvoker) delegate()
                            {
                                TXT_seriallog.Clear();
                            });
                        }
                        //if (line.Contains("Dumping Log"))
                        {
                            status = serialstatus.Reading;
                        }
                        break;

                    case serialstatus.Done:
                        //
                        // if (line.Contains("start") && line.Contains("end"))
                    {
                        Regex regex2 = new Regex(@"^Log ([0-9]+)[,\s]", RegexOptions.IgnoreCase);
                        if (regex2.IsMatch(line))
                        {
                            MatchCollection matchs = regex2.Matches(line);
                            logcount = int.Parse(matchs[0].Groups[1].Value);
                            genchkcombo(logcount);
                            //status = serialstatus.Done;
                        }
                    }
                        if (line.Contains("No logs"))
                        {
                            status = serialstatus.Done;
                        }
                        break;

                    case serialstatus.Reading:
                        if (line.Contains("packets read") || line.Contains("Done") || line.Contains("logs enabled"))
                        {
                            status = serialstatus.Closefile;
                            Console.Write("CloseFile: " + line);
                            break;
                        }
                        sw.Write(line);
                        continue;

                    case serialstatus.Waiting:
                        if (line.Contains("Dumping Log") || line.Contains("GPS:") || line.Contains("NTUN:") || line.Contains("CTUN:") || line.Contains("PM:"))
                        {
                            status = serialstatus.Reading;
                            Console.Write("Reading: " + line);
                        }
                        break;
                    }
                    lock (thisLock)
                    {
                        this.BeginInvoke((MethodInvoker) delegate()
                        {
                            Console.Write(line);

                            TXT_seriallog.AppendText(line.Replace((char)0x0, ' '));

                            // auto scroll
                            if (TXT_seriallog.TextLength >= 10000)
                            {
                                TXT_seriallog.Text = TXT_seriallog.Text.Substring(TXT_seriallog.TextLength / 2);
                            }

                            TXT_seriallog.SelectionStart = TXT_seriallog.Text.Length;

                            TXT_seriallog.ScrollToCaret();

                            TXT_seriallog.Refresh();
                        });
                    }
                }

                //log.Info("exit while");
            }
            catch (Exception ex) { CustomMessageBox.Show("Error reading data" + ex.ToString()); }
        }
Example #55
0
        Hashtable loadParamFile(string Filename)
        {
            Hashtable param = new Hashtable();

            StreamReader sr = new StreamReader(Filename);

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

                if (line.Contains("NOTE:"))
                {
                    CustomMessageBox.Show(line, "Saved Note");
                }

                if (line.StartsWith("#"))
                {
                    continue;
                }

                string[] items = line.Split(new char[] { ' ', ',', '\t' }, StringSplitOptions.RemoveEmptyEntries);

                if (items.Length != 2)
                {
                    continue;
                }

                string name  = items[0];
                float  value = float.Parse(items[1], new System.Globalization.CultureInfo("en-US"));

                MAVLink.modifyParamForDisplay(true, name, ref value);

                if (name == "SYSID_SW_MREV")
                {
                    continue;
                }
                if (name == "WP_TOTAL")
                {
                    continue;
                }
                if (name == "CMD_TOTAL")
                {
                    continue;
                }
                if (name == "FENCE_TOTAL")
                {
                    continue;
                }
                if (name == "SYS_NUM_RESETS")
                {
                    continue;
                }
                if (name == "ARSPD_OFFSET")
                {
                    continue;
                }
                if (name == "GND_ABS_PRESS")
                {
                    continue;
                }
                if (name == "GND_TEMP")
                {
                    continue;
                }
                if (name == "CMD_INDEX")
                {
                    continue;
                }
                if (name == "LOG_LASTFILE")
                {
                    continue;
                }

                param[name] = value;
            }
            sr.Close();

            return(param);
        }
Example #56
0
        public async void StartSwarmChain()
        {
            var exepath = CheckandGetSITLImage("ArduCopter.elf");
            var model   = "+";

            var config = await GetDefaultConfig(model);

            var max = 10.0;

            if (InputBox.Show("how many?", "how many?", ref max) != DialogResult.OK)
            {
                return;
            }

            max--;

            for (int a = (int)max; a >= 0; a--)
            {
                var extra = " --disable-fgview -r50";

                if (!string.IsNullOrEmpty(config))
                {
                    extra += @" --defaults """ + config + @""" -P SERIAL0_PROTOCOL=2 -P SERIAL1_PROTOCOL=2 ";
                }

                var home = new PointLatLngAlt(markeroverlay.Markers[0].Position).newpos((double)NUM_heading.Value, a * 4);

                if (max == a)
                {
                    extra += String.Format(
                        " -M{4} -s1 --home {3} --instance {0} --uartA tcp:0 {1} -P SYSID_THISMAV={2} ",
                        a, "", a + 1, BuildHomeLocation(home, (int)NUM_heading.Value), model);
                }
                else
                {
                    extra += String.Format(
                        " -M{4} -s1 --home {3} --instance {0} --uartA tcp:0 {1} -P SYSID_THISMAV={2} ",
                        a, "--uartD tcpclient:127.0.0.1:" + (5772 + 10 * a), a + 1,
                        BuildHomeLocation(home, (int)NUM_heading.Value), model);
                }

                string simdir = sitldirectory + model + (a + 1) + Path.DirectorySeparatorChar;

                Directory.CreateDirectory(simdir);

                string path = Environment.GetEnvironmentVariable("PATH");

                Environment.SetEnvironmentVariable("PATH", sitldirectory + ";" + simdir + ";" + path,
                                                   EnvironmentVariableTarget.Process);

                Environment.SetEnvironmentVariable("HOME", simdir, EnvironmentVariableTarget.Process);

                ProcessStartInfo exestart = new ProcessStartInfo();
                exestart.FileName         = await exepath;
                exestart.Arguments        = extra;
                exestart.WorkingDirectory = simdir;
                exestart.WindowStyle      = ProcessWindowStyle.Minimized;
                exestart.UseShellExecute  = true;

                File.AppendAllText(Settings.GetUserDataDirectory() + "sitl.bat",
                                   "mkdir " + (a + 1) + "\ncd " + (a + 1) + "\n" + @"""" + exepath + @"""" + " " + extra + " &\n");

                File.AppendAllText(Settings.GetUserDataDirectory() + "sitl1.sh",
                                   "mkdir " + (a + 1) + "\ncd " + (a + 1) + "\n" + @"""../" +
                                   Path.GetFileName(await exepath).Replace("C:", "/mnt/c").Replace("\\", "/").Replace(".exe", ".elf") + @"""" + " " +
                                   extra.Replace("C:", "/mnt/c").Replace("\\", "/") + " &\nsleep .3\ncd ..\n");

                Process.Start(exestart);
            }

            try
            {
                var client = new Comms.TcpSerial();

                client.client = new TcpClient("127.0.0.1", 5760);

                MainV2.comPort.BaseStream = client;

                SITLSEND = new UdpClient("127.0.0.1", 5501);

                Thread.Sleep(200);

                MainV2.instance.doConnect(MainV2.comPort, "preset", "5760");

                return;
            }
            catch
            {
                CustomMessageBox.Show(Strings.Failed_to_connect_to_SITL_instance, Strings.ERROR);
                return;
            }
        }
Example #57
0
 public void ShowError(string Message)
 {
     Application.Current.Dispatcher.Invoke(() => CustomMessageBox.ShowOK(Message, Resources.ErrorOccured, Resources.Ok, MessageBoxImage.Error));
 }
Example #58
0
        static void handleException(Exception ex)
        {
            MissionPlanner.Utilities.Tracking.AddException(ex);

            log.Debug(ex.ToString());

            GetStackTrace(ex);

            // hyperlinks error
            if (ex.Message == "Requested registry access is not allowed." || ex.ToString().Contains("System.Windows.Forms.LinkUtilities.GetIELinkBehavior"))
            {
                return;
            }
            if (ex.Message == "The port is closed.")
            {
                CustomMessageBox.Show("Serial connection has been lost");
                return;
            }
            if (ex.Message == "A device attached to the system is not functioning.")
            {
                CustomMessageBox.Show("Serial connection has been lost");
                return;
            }
            if (ex.GetType() == typeof(MissingMethodException))
            {
                CustomMessageBox.Show("Please Update - Some older library dlls are causing problems\n" + ex.Message);
                return;
            }
            if (ex.GetType() == typeof(ObjectDisposedException) || ex.GetType() == typeof(InvalidOperationException)) // something is trying to update while the form, is closing.
            {
                return;                                                                                               // ignore
            }
            if (ex.GetType() == typeof(FileNotFoundException) || ex.GetType() == typeof(BadImageFormatException))     // i get alot of error from people who click the exe from inside a zip file.
            {
                CustomMessageBox.Show("You are missing some DLL's. Please extract the zip file somewhere. OR Use the update feature from the menu " + ex.ToString());
                // return;
            }
            if (ex.StackTrace.Contains("System.IO.Ports.SerialStream.Dispose"))
            {
                return; // ignore
            }

            DialogResult dr = CustomMessageBox.Show("An error has occurred\n" + ex.ToString() + "\n\nReport this Error???", "Send Error", MessageBoxButtons.YesNo);

            if (DialogResult.Yes == dr)
            {
                try
                {
                    string data = "";
                    foreach (System.Collections.DictionaryEntry de in ex.Data)
                    {
                        data += String.Format("-> {0}: {1}", de.Key, de.Value);
                    }


                    // Create a request using a URL that can receive a post.
                    WebRequest request = WebRequest.Create("http://vps.oborne.me/mail.php");
                    request.Timeout = 10000; // 10 sec
                    // Set the Method property of the request to POST.
                    request.Method = "POST";
                    // Create POST data and convert it to a byte array.
                    string postData = "message=" + Environment.OSVersion.VersionString + " " + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString()
                                      + " " + Application.ProductVersion
                                      + "\nException " + ex.ToString().Replace('&', ' ').Replace('=', ' ')
                                      + "\nStack: " + ex.StackTrace.ToString().Replace('&', ' ').Replace('=', ' ')
                                      + "\nTargetSite " + ex.TargetSite + " " + ex.TargetSite.DeclaringType
                                      + "\ndata " + data;
                    byte[] byteArray = Encoding.ASCII.GetBytes(postData);
                    // Set the ContentType property of the WebRequest.
                    request.ContentType = "application/x-www-form-urlencoded";
                    // Set the ContentLength property of the WebRequest.
                    request.ContentLength = byteArray.Length;
                    // Get the request stream.
                    using (Stream dataStream = request.GetRequestStream())
                    {
                        // Write the data to the request stream.
                        dataStream.Write(byteArray, 0, byteArray.Length);
                    }
                    // Get the response.
                    using (WebResponse response = request.GetResponse())
                    {
                        // Display the status.
                        Console.WriteLine(((HttpWebResponse)response).StatusDescription);
                        // Get the stream containing content returned by the server.
                        using (Stream dataStream = response.GetResponseStream())
                        {
                            // Open the stream using a StreamReader for easy access.
                            using (StreamReader reader = new StreamReader(dataStream))
                            {
                                // Read the content.
                                string responseFromServer = reader.ReadToEnd();
                                // Display the content.
                                Console.WriteLine(responseFromServer);
                            }
                        }
                    }
                }
                catch
                {
                    CustomMessageBox.Show("Could not send report! Typically due to lack of internet connection.");
                }
            }
        }
Example #59
0
 public bool ShowYesNo(string Message, string Title)
 {
     return(Application.Current.Dispatcher.Invoke(() => CustomMessageBox.ShowYesNo(Message, Title, Resources.Yes, Resources.No, MessageBoxImage.Warning) == MessageBoxResult.Yes));
 }
Example #60
0
        private void Form1_Load(object sender, EventArgs e)
        {
            rowno = 1;

            OpenFileDialog openFileDialog1 = new OpenFileDialog();

            openFileDialog1.Filter           = "Log Files|*.log;*.bin";
            openFileDialog1.FilterIndex      = 2;
            openFileDialog1.RestoreDirectory = true;

            openFileDialog1.InitialDirectory = MainV2.LogDir;

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    Stream stream;

                    if (openFileDialog1.FileName.ToLower().EndsWith(".bin"))
                    {
                        // extract log
                        List <string> loglines = BinaryLog.ReadLog(openFileDialog1.FileName);
                        // convert log to memory stream;
                        stream = new MemoryStream();
                        // create single string with entire log
                        foreach (string line in loglines)
                        {
                            stream.Write(ASCIIEncoding.ASCII.GetBytes(line), 0, line.Length);
                        }
                        // back to stream start
                        stream.Seek(0, SeekOrigin.Begin);
                    }
                    else
                    {
                        stream = File.Open(openFileDialog1.FileName, FileMode.Open, FileAccess.Read, FileShare.Read);
                    }

                    var logdata = DFLog.ReadLog(stream);

                    this.Text = "Log Browser - " + Path.GetFileName(openFileDialog1.FileName);
                    m_dtCSV   = new DataTable();

                    log.Info("process to datagrid");

                    foreach (var item in logdata)
                    {
                        if (item.items != null)
                        {
                            while (m_dtCSV.Columns.Count < (item.items.Length + typecoloum))
                            {
                                m_dtCSV.Columns.Add();
                            }

                            DataRow dr = m_dtCSV.NewRow();

                            dr[0] = item.lineno;
                            dr[1] = item.time.ToString("yyyy-MM-dd HH:mm:ss.fff");

                            for (int a = 0; a < item.items.Length; a++)
                            {
                                dr[a + typecoloum] = item.items[a];
                            }

                            m_dtCSV.Rows.Add(dr);
                        }
                    }

                    log.Info("Done");

                    //PopulateDataTableFromUploadedFile(stream);

                    stream.Close();

                    log.Info("set dgv datasourse");

                    dataGridView1.DataSource = m_dtCSV;

                    dataGridView1.Columns[0].Visible = false;

                    log.Info("datasource set");
                }
                catch (Exception ex) { CustomMessageBox.Show("Failed to read File: " + ex.ToString()); }

                foreach (DataGridViewColumn column in dataGridView1.Columns)
                {
                    column.SortMode = DataGridViewColumnSortMode.NotSortable;
                }

                log.Info("Get map");

                DrawMap();

                log.Info("map done");

                CreateChart(zg1);
            }
            else
            {
                this.Close();
                return;
            }
        }