Example #1
0
        private void SendMessage()
        {
            Color btPrevColor = btSend.BackColor;
            Color btNewColor;

            btSend.Enabled = false;
            if (tbSendMessage.Text.Length > 0)
            {
                try {
                    SerialPortActions.WriteOnPort(tbSendMessage.Text);
                    tbSendMessage.Clear();
                    btNewColor = Color.LimeGreen;
                }
                catch {
                    btNewColor = Color.Red;
                }
            }
            else
            {
                btNewColor = Color.Red;
            }

            btSend.BackColor = btNewColor;
            var timer = new Timer {
                Interval = 1500
            };

            timer.Tick += delegate {
                btSend.BackColor = btPrevColor;
                btSend.Enabled   = true;
                timer.Stop();
                timer.Dispose();
            };
            timer.Start();
        }
Example #2
0
 /// <summary>
 ///     Releases all unmanaged resources (which implements IDisposable)
 /// </summary>
 public void Dispose()
 {
     // You must release all unmanaged resources here when program is stopped to prevent the memory leaks.
     for (var i = 0; i < OpenedPorts.Count; i++)
     {
         SerialPortActions.DestroyPort(OpenedPorts.Values.ElementAt(i));
     }
 }
Example #3
0
 public void UpdatePortsListView(object sender = null, EventArgs e = null)
 {
     // clear list
     lvPorts.Items.Clear();
     string[] ports = SerialPortActions.GetPortsList(true, false);
     if (ports.Length == 0)
     {
         lvPorts.Items.Add("No available ports found.");
     }
     else
     {
         // populate list
         if (Plugin.OpenedPorts.Count > 0)
         {
             foreach (string portLongName in ports)
             {
                 ListViewItem addedItem = lvPorts.Items.Add(portLongName);
                 // set opened port color
                 if (Plugin.OpenedPorts.ContainsKey(portLongName))
                 {
                     // highlight current port
                     if (Plugin.SelectedPort.IsAlive() &&
                         Plugin.OpenedPorts[portLongName].PortName == Plugin.SelectedPort.PortName)
                     {
                         addedItem.ForeColor = Color.Gold;
                     }
                     else
                     {
                         addedItem.ForeColor = Color.LimeGreen;
                     }
                 }
             }
         }
         // skip coloring if 0 opened ports
         else
         {
             foreach (string portLongName in ports)
             {
                 lvPorts.Items.Add(portLongName);
             }
         }
     }
     tbSendMessage.Enabled = btSend.Enabled = Plugin.SelectedPort.IsAlive();
 }
Example #4
0
        /// <summary>
        ///     This is the main method called by VoxCommando when performing plugin actions. All actions go through here.
        /// </summary>
        /// <param name="actionNameArray">
        ///     An array of strings representing action name. Example action: xbmc.send >>>
        ///     actionNameArray[0] is the plugin name (xbmc), actionNameArray[1] is "send".
        /// </param>
        /// <param name="actionParameters">An array of strings representing our action parameters.</param>
        /// <returns>an actionResult</returns>
        public actionResult doAction(string[] actionNameArray, string[] actionParameters)
        {
            var          ar            = new actionResult();
            const string unknownAction = "Unknown " + nameof(Serial) + " plugin action.";

            if (actionNameArray.Length < 2)
            {
                ar.setError(unknownAction);
                return(ar);
            }

            try {
                switch (actionNameArray[1].ToUpper())
                {
                case "OPEN": {     // [PortName pattern], (BaudRate), (DTR), (Parity), (StopBits), (DataBits)
                    #region Parsing action parameters

                    Regex portNameRegex;
                    if (actionParameters.Length < 1 || !IsValidRegex(actionParameters[0], out portNameRegex))
                    {
                        ar.setError("'Port name pattern' missing or invalid.");
                        return(ar);
                    }

                    var info = "";
                    // parse baud rate
                    int baudRate;
                    if (actionParameters.Length < 2 || !int.TryParse(actionParameters[1], out baudRate))
                    {
                        baudRate = 9600;
                        info     = "'Baud rate' undefined. Using 9600.\r\n";
                    }
                    // parse DTR
                    bool dtrEnable;
                    if (actionParameters.Length < 3 || !bool.TryParse(actionParameters[2], out dtrEnable))
                    {
                        dtrEnable = false;
                        info     += "'Use DTR' undefined. Using false.\r\n";
                    }
                    // parse parity
                    Parity parity;
                    if (actionParameters.Length < 4 || !Enum.TryParse(actionParameters[3], true, out parity))
                    {
                        parity = Parity.None;
                        info  += "'Parity' undefined. Using none.\r\n";
                    }
                    // parse stop bits
                    StopBits stopBits;
                    if (actionParameters.Length < 5 || !Enum.TryParse(actionParameters[4], true, out stopBits))
                    {
                        stopBits = StopBits.One;
                        info    += "'Stop bits' undefined. Using one.\r\n";
                    }
                    // parse data bits
                    int dataBits;
                    if (actionParameters.Length < 6 || !int.TryParse(actionParameters[5], out dataBits))
                    {
                        dataBits = 8;
                        info    += "'Data bits' undefined. Using 8.\r\n";
                    }

                    #endregion

                    // [select] First step - searching it in opened ports
                    foreach (string portLongName in OpenedPorts.Keys)
                    {
                        if (portNameRegex.Match(portLongName).Success)
                        {
                            Match match = ComNameRegex.Match(portLongName);
                            if (!match.Success)
                            {
                                ar.setError("Port must have 'COM' type.");
                                return(ar);
                            }
                            string portComName = match.Value;
                            if (SelectedPort.PortName == portComName)
                            {
                                ar.setError($"{portLongName} already selected.");
                            }
                            else
                            {
                                SerialPortActions.SelectPort(portComName);
                                ar.setInfo($"'{portLongName}' selected.");
                            }
                            return(ar);
                        }
                    }

                    // [open] If not found, look for it through all system ports.
                    string[] portsNames = SerialPortActions.GetPortsList(true, false);
                    foreach (string portLongName in portsNames)
                    {
                        // user pattern match
                        if (portNameRegex.Match(portLongName).Success)
                        {
                            try {
                                SerialPortActions.OpenPort(portLongName, baudRate, dtrEnable, parity, stopBits, dataBits);
                                info += $"'{portLongName}' opened and selected.";
                                ar.setInfo(info);
                            }
                            catch (Exception ex) {
                                ar.setError(ex.Message);
                            }
                            return(ar);
                        }
                    }

                    // failed
                    ar.setError("Matching port not found.");
                    return(ar);
                }

                case "GETPORTS": {     // (Friendly names), (Show only opened)
                    bool friendlyNames;
                    if (actionParameters.Length < 1 || !bool.TryParse(actionParameters[0], out friendlyNames))
                    {
                        friendlyNames = false;
                    }
                    bool onlyOpenedPorts;
                    if (actionParameters.Length < 2 || !bool.TryParse(actionParameters[1], out onlyOpenedPorts))
                    {
                        onlyOpenedPorts = false;
                    }

                    string[] portsNames = SerialPortActions.GetPortsList(friendlyNames, onlyOpenedPorts);
                    if (portsNames.Length == 0)
                    {
                        ar.setError("No open ports.");
                    }
                    else
                    {
                        ar.setSuccess(string.Join("\r\n", portsNames));
                    }
                    break;
                }

                case "WRITE": {     // [Message to write on port]
                    if (actionParameters.Length < 1)
                    {
                        ar.setError("1 parameter expected.");
                        return(ar);
                    }

                    ar = SerialPortActions.WriteOnPort(actionParameters[0]);
                    break;
                }

                case "CLOSE": {     // <No parameters>
                    ar = SerialPortActions.DestroyPort(SelectedPort);
                    break;
                }

                case "MICRO": {
                    if (actionNameArray.Length < 3)
                    {
                        ar.setError(unknownAction);
                        return(ar);
                    }
                    // any that action requires port to be closed.
                    SelectedPort.Close();
                    ar = ArduinoActions.DoDriverAction(actionNameArray, actionParameters);
                    SelectedPort.Open();
                    break;
                }

                default: {
                    ar.setError(unknownAction);
                    break;
                }
                }
            }
            catch (Exception ex) {
                ar.setError(ex.ToString());
            }

            return(ar);
        }
Example #5
0
        private void lvPorts_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                ListViewItem portView = lvPorts.FocusedItem;
                // if item not selected or "No ports" selected
                if (portView == null ||
                    portView.Text == noPortsFound)
                {
                    return;
                }
                string portLongName = portView.Text;

                // tricky way to show pop-up menu
                MenuItem         mi;
                SerialPortStream port;
                if (Plugin.OpenedPorts.TryGetValue(portLongName, out port))
                {
                    mi        = new MenuItem("Close port");
                    mi.Click += delegate { SerialPortActions.DestroyPort(port); };

                    if (Plugin.SelectedPort.IsAlive() &&
                        port.PortName != Plugin.SelectedPort.PortName)
                    {
                        // add 'select port' entry
                        var mi2 = new MenuItem("Select port");
                        mi2.Click += delegate { SerialPortActions.SelectPort(port.PortName); };

                        new ContextMenu(new[] { mi, mi2 })
                        .Show(lvPorts, new Point(e.X, e.Y));
                        return;
                    }
                }
                else
                {
                    mi = new MenuItem("Open port");

                    #region 'open port' form design implementation

                    mi.Click += delegate {
                        //
                        // labTitle
                        //
                        var labTitle = new Label {
                            AutoSize = true,
                            Location = new Point(12, 4),
                            Size     = new Size(86, 14),
                            Text     = "Open new port"
                        };
                        //
                        // cbEnableDtr
                        //
                        var cbEnableDtr = new CheckBox {
                            AutoSize   = true,
                            Location   = new Point(11, 46),
                            Size       = new Size(191, 34),
                            CheckAlign = ContentAlignment.MiddleRight,
                            Text       = "Enable DTR\r\n(reload board after connection)"
                        };
                        //
                        // numBaudRate
                        //
                        var numBaudRate = new NumericUpDown {
                            Anchor = AnchorStyles.Top | AnchorStyles.Left
                                     | AnchorStyles.Right,
                            BackColor = Color.FromArgb(55, 55, 55),
                            ForeColor = Color.Gainsboro,
                            Location  = new Point(75, 14),
                            Size      = new Size(122, 23),
                            Increment = 100m,
                            Maximum   = 999999999999m,
                            Minimum   = 9600m,
                            Value     = 9600m
                        };
                        //
                        // labBaudRate
                        //
                        var labBaudRate = new Label {
                            AutoSize = true,
                            Location = new Point(8, 17),
                            Size     = new Size(60, 15),
                            Text     = "Baud rate:"
                        };
                        //
                        // btOk
                        //
                        var btOk = new Button {
                            Anchor         = AnchorStyles.Bottom | AnchorStyles.Left,
                            BackColor      = Color.FromArgb(0, 122, 204),
                            ForeColor      = Color.White,
                            FlatAppearance =
                            {
                                BorderSize = 0
                            },
                            FlatStyle    = FlatStyle.Flat,
                            Location     = new Point(11, 90),
                            Size         = new Size(88, 23),
                            Text         = "OK",
                            DialogResult = DialogResult.OK
                        };
                        //
                        // btCancel
                        //
                        var btCancel = new Button {
                            Anchor         = AnchorStyles.Bottom | AnchorStyles.Right,
                            BackColor      = Color.FromArgb(0, 122, 204),
                            ForeColor      = Color.White,
                            FlatAppearance =
                            {
                                BorderSize = 0
                            },
                            FlatStyle    = FlatStyle.Flat,
                            Location     = new Point(109, 90),
                            Size         = new Size(88, 23),
                            Text         = "Cancel",
                            DialogResult = DialogResult.Cancel
                        };
                        //
                        // panMain
                        //
                        var panMain = new Panel {
                            Anchor = AnchorStyles.Top | AnchorStyles.Bottom
                                     | AnchorStyles.Left
                                     | AnchorStyles.Right,
                            BackColor = Color.FromArgb(50, 50, 50),
                            Location  = new Point(1, 25),
                            Size      = new Size(208, 124),
                            Controls  =
                            {
                                cbEnableDtr,
                                numBaudRate,
                                labBaudRate,
                                btOk,
                                btCancel
                            }
                        };
                        //
                        // formOpenPort
                        //
                        var formOpenPort = new Form {
                            ClientSize      = new Size(210, 150),
                            Font            = new Font("Segoe UI", 9F, FontStyle.Regular, GraphicsUnit.Point, 0),
                            BackColor       = Color.FromArgb(202, 81, 0),
                            ForeColor       = Color.Gainsboro,
                            FormBorderStyle = FormBorderStyle.None,
                            StartPosition   = FormStartPosition.CenterParent,
                            Controls        =
                            {
                                labTitle,
                                panMain
                            }
                        };

                        btCancel.Click += delegate { formOpenPort.Close(); };
                        btOk.Click     += delegate {
                            SerialPortActions.OpenPort(
                                portLongName,
                                (int)numBaudRate.Value,
                                cbEnableDtr.Checked
                                );
                        };

                        formOpenPort.ShowDialog();
                    };

                    #endregion
                }
                new ContextMenu(new[] { mi })
                .Show(lvPorts, new Point(e.X, e.Y));
            }
        }